拖动背景是否可以改变背景位置?

3
我有一个使用世界地图图像作为背景的HTML地图。
我可以编写一个JavaScript函数来更改
的背景位置,但是我想在用户单击地图然后拖动时更改背景位置,就像谷歌地图一样。
因此,我在这里提供了一个示例页面:http://lab.qacode.com/map,它使用http://lab.qacode.com/map/map.jpg
如果您有任何建议或提示,我将不胜感激。

我现在会尝试为您写点什么... - Oscar Godson
@Oscar Godson // !! 谢谢!! - Moon
1个回答

7
An easy way to make this work is to use jQuery UI's draggable. HTML
<div id="map">
    <div class="map-canvas"></div>    
</div>

JavaScript

// Pre-select elements
var map = $("#map"),
    canvas = map.find(".map-canvas");

// Calculate canvas constraints
var maxLeft = map.width()-canvas.width(),
    maxTop = map.height()-canvas.height();

// Make canvas draggable
canvas.draggable({
    drag: function(e, ui) {
        // Check if canvas is within constraints
        if (ui.position.left > 0) {
            ui.position.left = 0;
        } else if (ui.position.left < maxLeft) {
            ui.position.left = maxLeft;
        }
        if (ui.position.top > 0) {
            ui.position.top = 0;
        } else if (ui.position.top < maxTop) {
            ui.position.top = maxTop;
        }
    }
});

放置标记

可以在地图上放置标记(或其他内容)。这很容易,坐标是基于画布内的像素。在测试案例中,标记距离画布左侧和顶部均为150像素。

// Create simple dot marker
$("<div></div>")
    .addClass("map-marker")
    .appendTo(canvas)
    .offset(function(){
        return { left: 150, top: 150 };
    })
    // Append a label
    .append("<span><- Dot</span>");

现在我们来讲一些更高级的内容,即(臭名昭著的)谷歌地图图钉。
// Create draggable Google Maps pin marker
var pin =
$("<div></div>")
    .addClass("google-pin")
    .appendTo(canvas)
    .offset(function(){
        return { left: 50, top: 50 };
    })
    // Bind mouseup/down for visual confirmation of grab
    .bind({
        mousedown: function(){
            var os = pin.offset();
            pin.offset(function(){
                return { top: os.top-3 };
            });
        },
        mouseup: function(){
            var os = pin.offset();
            pin.offset(function(){
                return { top: os.top+3 };
            });
        }
    })
    // Make it draggable
    .draggable({
        start: function(e,ui){
            ui.helper.offset(function(){
                return { top: ui.offset.top-2 };
            });
        },
        container: canvas
    });

查看 jsFiddle上的测试用例


@Marcus Ekwall // 感谢您提供的脚本。它完美地运行了,但我需要使用背景图像,而不是实际的img元素。 - Moon
@Marcus Ekwall // 它完美地工作了。我非常感激。但是...我们已经建立了一个完全工作的地图,它使用背景位置。有没有一种方法可以用jquery更改背景位置? - Moon
@Moon,当然有。但是draggable不能与background-position一起使用。无论如何,我已经为您添加了约束 :) - mekwall
@Moon,您真的检查了Google Maps中所有可能的功能吗?这里有自定义叠加层自定义地图样式。这里甚至还有Moon。还可以看看CloudMade - mekwall
@Marcus Ekwall // 哈哈哈,“这里甚至有月亮”那部分太有趣了,哈哈。谢谢你,Marcus。我非常非常感激。今晚我会查看那些自定义地图样式。 - Moon
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接