下面有一段代码使用bounds.extend()和map.fitBounds()调整地图大小以容纳所有标记。我希望地图可以将start_point作为中心,并缩小到适当的水平,以便看到每个标记。
然而,它最终放大到start_point。我试图(commen)每次都没有在geocoder.geocode回调函数中调用bounds.extend(),而是将标记添加到数组中并在一个单独的循环中调用bounds.extend(),这也是无效的。
我仔细检查了标记是否已成功创建,如果我手动缩小,我可以看到它们。
mark_pins()被调用为ajax成功回调函数,我没有在这里包含。
我错过了什么吗?
var map;
var start_point = new google.maps.LatLng(37.519002, -122.131);
var bounds = new google.maps.LatLngBounds();
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: start_point,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(map_canvas, map_options);
}
google.maps.event.addDomListener(window, 'load', initialize);
function mark_pins(trucks){
var geocoder = new google.maps.Geocoder();
var markersArray = [];
for (i = 0; i < trucks.length; i++) {
// iterate each truck address
geocoder.geocode( { 'address' : trucks[i]['address']}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
marker.setMap(map);
bounds.extend(results[0].geometry.location);
//markersArray.push(marker);
} else {
alert('Internal error: ' + status + address);
}
});
}
var bounds = new google.maps.LatLngBounds();
for (i = 0; i< markersArray.length; i++) {
//code
//bounds.extend(new google.maps.LatLng(markersArray[i][1], markersArray[i][2]));
}
bounds.extend(start_point);
map.setCenter(start_point);
map.fitBounds(bounds);
}
答案 0 :(得分:5)
地理编码器是异步的。在结果返回之前,您的代码会调用map.fitBounds(bounds)
。发布的代码也从不调用mark_pins函数。
function mark_pins(trucks) {
var geocoder = new google.maps.Geocoder();
var markersArray = [];
for (i = 0; i < trucks.length; i++) {
// iterate each truck address
geocoder.geocode({
'address': trucks[i]['address']
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
marker.setMap(map);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
} else {
alert('Internal error: ' + status + address);
}
});
}
}