我有一个非常奇怪的错误,当我尝试调整 map 大小时以适应我放置在 map 上的标记时,它一直导致我的浏览器卡住。
我的调整代码供引用:
function sizeMap() {
// create a new bounds object to define the new boundry
var bounds = new google.maps.LatLngBounds();
// loop through each the string latlang values held in the latlng
// aray
for ( var i = 0; i <latlngArray.length ; i++) {
// create a new LatLng object based on the string value
var tempLatLng = new google.maps.LatLng(latlngArray[i]);
// extend the latlng bounds based on the new location
bounds.extend(tempLatLng);
}
// map.fitBounds(bounds); <== everything seems to work fine until this line is uncommented
}
问题是我无法使用 Firebug 正确调试它,因为它会卡住! 有人对问题可能有什么想法吗?
提前致谢。
更新:
在回答 puckheads 问题时,以下代码显示了 latlng 数组的填充位置:
function geocodeAddress (address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
loadMarker(results[0].geometry.location,"Info here",address);
latlngArray.push(results[0].geometry.location); <== latlngs are first added here they are as a result of a call to the google geocode service with a standard string address.
} else {
alert("Geocode was not successful for the following reason: " +" "+ status);
}
});
}
最佳答案
问题正如其他人所提到的,您尝试创建一个 LatLng 对象并将另一个 LatLng 对象作为参数。它只接受 2 或 3 个参数,其中前两个是数字。 https://developers.google.com/maps/documentation/javascript/reference#LatLng
但是,您可以完全跳过创建新 LatLng 对象的部分,并在循环内使用数组中的当前对象。
这解决了问题:http://jsfiddle.net/y9ze8a1f/1/
function sizeMap() {
// create a new bounds object to define the new boundry
var bounds = new google.maps.LatLngBounds();
// loop through each the string latlang values held in the latlng
// aray
for ( var i = 0; i <latlngArray.length ; i++) {
// This is causing the issue, you can only create a LatLng with two separate latitude and longitude arguments
//var tempLatLng = new google.maps.LatLng(latlngArray[i]);
bounds.extend(latlngArray[i]);
}
map.fitBounds(bounds);
}
如果您想基于旧的 LatLng 创建一个新的 LatLng,您可以使用 LatLng 方法 lat()
和 lng()
function sizeMap() {
// create a new bounds object to define the new boundry
var bounds = new google.maps.LatLngBounds();
// loop through each the string latlang values held in the latlng
// aray
for ( var i = 0; i <latlngArray.length ; i++) {
// create a new LatLng object based on the string value
var tempLatLng = new google.maps.LatLng(latlngArray[i].lat(), latlngArray[i].lng());
// extend the latlng bounds based on the new location
bounds.extend(tempLatLng);
}
map.fitBounds(bounds);
}
关于javascript - map.fitBounds(bounds) 导致浏览器卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9656374/