从起点限制标记移动(谷歌地图API 3)

时间:2014-10-09 15:41:39

标签: google-maps google-maps-api-3

我在地图上放置了一个标记,其中draggable属性为true。我想限制移动标记距离原始位置不超过500米。我该怎么做?我尝试过更好的方法吗?

我尝试了拖动事件。我用代码I found on SO测量距离。但我不知道如何防止阻力。我尝试返回false,尝试查看函数参数是否已取消或类似。

google.maps.event.addListener(marker, 'drag', function(e) 
{
    var distance = Application.getMapDistance(data[0].geometry.location, marker.getPosition());
    document.title = distance;
    if (distance > 500)
        return false; //not working, e has no cancel or something like that
});

修改

显然有人对我的问题不满意。是的,基本逻辑是将google marker位置设置为持久良好,但这样,当标记移出边界时标记会闪烁。 我很确定谷歌可以做得更好。

google.maps.event.addListener(marker, 'drag', function(e) 
        {
            var distance = Application.getMapDistance(data[0].geometry.location, marker.getPosition());
            document.title = distance;
            if (distance > 500)
                marker.setPosition(lastGoodPosition);
            else
                lastGoodPosition = marker.getPosition();
        });

1 个答案:

答案 0 :(得分:2)

use bounds = map.getBounds();

Then in the marker dragend event, I check whether the new location falls within the defined bounds, and if not, revert the marker to the last saved position:

google.maps.event.addListener(marker, 'dragend', function () {

var position = marker.getPosition();
bounds.contains(position) ? lastPosition = position : marker.setPosition(lastPosition);

});

set zoom level like that initial map have limit as per your requirement

see a demo on http://jsfiddle.net/upsidown/89DJC/