我遇到了一个奇怪的问题,在 ajax 调用后 fitBounds 无法工作。在初始页面加载时,fitBounds 工作正常,并且以 5 个标记为中心。但是,在我单击下拉过滤器或分页之一(这会触发 ajax 函数来更新标记)后,它不想加载,即使它似乎试图根据标记应在的位置将 map 居中是的。过滤器肯定有效,因为我还在 map 旁边输出所有制造商位置的列表。
我还注意到,如果我将查询调整为一次仅显示 1 个标记,fitBounds 往往会工作得更好,尽管并非总是如此。似乎“for 循环”中的某些东西可能会抛出一些东西。但我仍然没有 100% 的成功率,只显示 1 个标记。在大多数情况下,我似乎工作得更好一些。
无论我用ajax函数输出多少标记,最终,在多次点击过滤器后, map 就像滞后了一样。有时它会显示一个标记,但其后面的 map 并不正确。有时,每次过滤器被触发时, map 都会开始变得越来越扭曲。另一个奇怪的事情是,一旦我触发新标记的ajax函数,如果我将鼠标悬停在 map 上的缩放栏上,它会自动滑到底部并且无法移动。如果我尝试通过单击和拖动来移动 map ,整个 map 就会变成纯灰色。
下面是页面加载后加载标记的第一个函数。它运行良好,此时 fitBounds 也运行良好。
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
center: new google.maps.LatLng(-30, -209.6),
zoom: 3,
maxZoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// create the map
var map = new google.maps.Map(mapCanvas, mapOptions);
// array to hold the markers
var markers = [];
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
// Loop through array and add markers to map
for( i = 0; i < jqueryarray.length; i++ ) {
var position = new google.maps.LatLng(jqueryarray[i]['lat'], jqueryarray[i]['long']);
var marker = new google.maps.Marker({
position: position,
map: map,
icon: mapIcon, // just assume this has been set
title: jqueryarray[i]['title']
});
// increase bounds and fit to map
bounds.extend (position);
map.fitBounds (bounds);
markers.push(marker);
} // end of the for loop
这是触发下拉菜单过滤器后由 ajax 调用的另一个函数。同样,如果需要将多个标记添加到 map 中,似乎就会遇到麻烦。不过,这些函数在不使用 fitBounds 的情况下也可以完美运行,因此我使用 fitBounds 的方式肯定存在问题。
// this function adds new map markers after a select menu change
function addNewMarkers(json, count) {
for (var i = 0; i < count; i++ ) {
markers[i].setMap(null);
}
// reset the markers array
markers = [];
// Create a new viewpoint bound. Do I need this again?
var bounds = new google.maps.LatLngBounds ();
//bounds = new google.maps.LatLngBounds(null);
// Loop through our array and add markers to map
for( i = 0; i < json.length; i++ ) {
var myPosition = new google.maps.LatLng(json[i].lat, json[i].long);
var marker = new google.maps.Marker({
position: myPosition,
map: map,
icon: mapIcon, // assume this has been set
title: json[i].title
});
// increase bounds and fit to map
bounds.extend (myPosition);
map.fitBounds (bounds);
markers.push(marker);
} // end of for loop
} // end of addNewMarkers function
最佳答案
您在循环的每次迭代中调用 map.fitBounds(bounds)
。
将此调用移至循环之后,而不是每次都调用它。在调用 fitBounds()
之前,您需要将所有点添加到边界。
此外,两个代码块之间存在大量重复的代码。您应该将其移至一个可以从两个地方调用的通用函数中。
关于javascript - 谷歌地图 fitBounds 不适用于 ajax 功能 - 似乎只适用于一个标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30536868/