如何限制可拖动图钉在地图可见区域之外

时间:2013-06-06 16:20:08

标签: bing-maps

我正在使用Bing Maps v7并创建了一个可拖动的图钉。我从这里拿了代码。

http://www.garzilla.net/vemaps/Draggable-Push-Pins-with-Bing-Maps-7.aspx

我需要将拖动限制在可见地图区域之外。

我有一个已定义的地图区域,其中禁用了缩放平移和可拖动的引脚,用户可以将引脚放在那里。

问题:图钉可以在地图之外拖动,然后没有选项可以取回它。

1 个答案:

答案 0 :(得分:0)

Pushpin类上,您有几个事件来管理在拖动开始,拖动和拖动结束时执行的操作,请参阅MSDN:http://msdn.microsoft.com/en-us/library/gg427615.aspx

所以,简单来说,你所要做的就是处理你选择的事件(在你的情况下,我建议在图钉上使用drag)并取消事件或者只是自己修改图钉的位置。

查看图钉被限制为最小纬度值的实例示例(您可以根据当前地图视图更新拖动事件以限制到特定区域):

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <head>
      <title>Bing Maps AJAX V7 - Restricted draggable pushpin</title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
      <script type="text/javascript">
      var map = null;
      var minLatitude = 49;

      function getMap()
      {
        map = new Microsoft.Maps.Map(document.getElementById('myMap'), 
        {
            credentials: 'YOURKEY',
            center: new Microsoft.Maps.Location(50, 3),
            zoom: 6
        });
      }

      function addDraggablePushpin()
      {
        var pushpinOptions = {draggable: true}; 
        var pushpin= new Microsoft.Maps.Pushpin(map.getCenter(), pushpinOptions); 
        map.entities.push(pushpin);

        Microsoft.Maps.Events.addHandler(pushpin, 'drag', function() {
            var loc = pushpin.getLocation();

            // Verify if it's in a certain area if not, cancel event
            if(loc.latitude < minLatitude) {
                pushpin.setLocation(new Microsoft.Maps.Location(minLatitude, loc.longitude));
            }
        });
      }
      </script>
   </head>
   <body onload="getMap();">
      <div id='myMap' style="position:relative; width:400px; height:400px;"></div>
      <div>
         <input type="button" value="AddDraggablePushpin" onclick="addDraggablePushpin();" />
      </div>
   </body>
</html>
相关问题