在映射空闲时调用maps.getBounds()为null

maps.getBounds() null when calling on map idle

本文关键字:getBounds null maps 调用 映射      更新时间:2023-09-26

我需要在a)映射初始化时和b)映射移动时设置指向映射的指针。为了获得标记,我对我的API调用如下:

var bounds = map.getBounds();

然后获取边界以获得正确的标记。

问题是,当我把那个API-call放进的时候

google.maps.event.addListener(map, "bounds_changed", function(){})

它在拖动地图时被调用得太频繁了,但如果我使用

google.maps.event.addListener(map, "idle", function(){})

map.getBounds在初始化时为null。

编辑:更多代码

$(document).ready(function(){    initialize(); });
function initialize() {    mapOptions = {
      zoom : 13,
      minZoom : minimumZoomLevel,
      scrollwheel : false,
      panControl : false    };    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
   google.maps.event.addListener(map, "idle", function() {
      myfunction();    }); });
function myfunction(){    var bounds = map.getBounds(); }

界限为空!

我在这里使用这段代码:http://boascervejas.com.br它工作正常:

var mapgoogle = null;
//do some stuff
var mapOptions = //something here
mapgoogle = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListener(mapgoogle, 'idle', function() {
   var bounds = mapgoogle.getBounds();
   console.log(bounds);
   //it's only called when the "end of the drag" is fired
});

EDIT:jsfiddle的完整工作示例(http://jsfiddle.net/pjhk3Lm9/):

js:

var map = null;
function initialize(lat, lng) {
   var myLatlng = new google.maps.LatLng(lat,lng);
   var mapOptions = {
      mapTypeControl: false,
      streetViewControl: false,
      center: myLatlng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    google.maps.event.addListener(map, 'idle', function() {
        console.log(map.getBounds());  
    })
};

navigator.geolocation.getCurrentPosition(
    function(position) {
        initialize(position.coords.latitude, position.coords.longitude);
    },
    function(position) {
        initialize(-23.5354986,-46.6839113);
    }
);
//html and css
<div id="map-canvas"></div>
#map-canvas {
    width: 400px;
    height: 400px;
    border:1px solid #FF0000;
}