【问题标题】:get current latlng bounds?获取当前的纬度界限?
【发布时间】:2011-12-20 11:01:41
【问题描述】:

我想保存用户正在观看的当前位置并在点击几下后恢复。

如何获取当前的经度范围以便可以在其上使用 map.fitBounds?

【问题讨论】:

标签: google-maps-api-3


【解决方案1】:

这是在“bounds_changed”事件中捕获当前地图边界的代码

google.maps.event.addListener(map, 'bounds_changed', function() {
        try {
            if( initialBounds == null ) {
                initialBounds = map.getBounds(); 
            }
        } catch( err ) {
            alert( err );
        }
    });

然后,您可以使用此代码返回绑定的地图

google.maps.event.addDomListener(controlUI, 'click', function() {
        // map.setCenter(home)
        if( initialBounds != null ) {
            map.fitBounds( initialBounds );
        }
    });

【讨论】:

    【解决方案2】:

    Google Maps API v3 中的getBounds()

    所以要获得我们的纬度和经度,我们需要将getBounds() 移动到bounds_changed 事件监听器。

         var map = new google.maps.Map(document.getElementById("map"), {
                 zoom: 10,
                 center: new google.maps.LatLng(lat, lng),
                 mapTypeId: google.maps.MapTypeId.ROADMAP
         });
         google.maps.event.addListener(map, 'bounds_changed', function() {
                  var bounds =  map.getBounds();
                  var ne = bounds.getNorthEast();
                  var sw = bounds.getSouthWest();
                  console.log(ne.lat());
                  console.log(ne.lng());
                  console.log(sw.lat());
                  console.log(sw.lng());
         });
    

    当视口边界发生变化时会触发此事件。如果您在其中有一些 ajax 调用,则每次 map 的位置更改时,都会触发 ajax 调用。

    因此,在这种情况下,更好的解决方案是将getBounds() 移动到idle 事件侦听器中。当地图在缩放后空闲时触发此事件。

         var map = new google.maps.Map(document.getElementById("map"), {
                 zoom: 10,
                 center: new google.maps.LatLng(lat, lng),
                 mapTypeId: google.maps.MapTypeId.ROADMAP
          });
         google.maps.event.addListener(map, 'idle', function() {
                  var bounds =  map.getBounds();
                  var ne = bounds.getNorthEast();
                  var sw = bounds.getSouthWest();
                  console.log(ne.lat());
                  console.log(ne.lng());
                  console.log(sw.lat());
                  console.log(sw.lng());
         });
    

    【讨论】:

      猜你喜欢
      • 2015-09-07
      • 1970-01-01
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 2013-10-11
      相关资源
      最近更新 更多