我需要在 a) 初始化 map 时和 b) 本地图移动时设置指向 map 的指针。 为了获取标记,我像这样调用 API:
var bounds = map.getBounds();
然后获取边界以获得正确的标记。
问题是,当我将 API 调用放入其中时
google.maps.event.addListener(map, "bounds_changed", function(){})
拖动 map 时它被频繁调用,但如果我使用
google.maps.event.addListener(map, "idle", function(){})
初始化时map.getBounds为空。
编辑:更多代码
$(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
});
编辑:使用 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;
}
关于javascript - 在 map 空闲时调用maps.getBounds() null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29098720/