【问题标题】:Limit marker movement from starting point (google maps API 3)从起点限制标记移动(谷歌地图 API 3)
【发布时间】:2014-10-09 15:41:38
【问题描述】:

我在地图上放置了一个可拖动属性为 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 可以做得更好。

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();
        });

【问题讨论】:

  • 您是否尝试过在标记被拖出界限时重置标记位置?
  • 不,我虽然有更好的方法。通过将标记位置设置为新坐标,我预计会出现一些闪烁。
  • 不自​​己开发标记类和拖拽实现,想不出更好的办法。

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


【解决方案1】:

使用 bounds = map.getBounds();

然后在标记拖动事件中,我检查新位置是否在定义的范围内,如果不是,则将标记恢复到上次保存的位置:

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

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

});

像初始地图一样设置缩放级别,根据您的要求有限制

http://jsfiddle.net/upsidown/89DJC/上查看演示

【讨论】:

  • bounds 会给我一个正方形,但我需要一个圆(半径 500m)。 Dragend 不是我正在寻找的解决方案,因为它会使用户感到困惑,为什么标记会改变。还是谢谢。
猜你喜欢
  • 2017-09-21
  • 2013-04-25
  • 1970-01-01
  • 2013-04-08
  • 2020-05-07
  • 2011-07-19
  • 1970-01-01
  • 2017-01-10
  • 1970-01-01
相关资源
最近更新 更多