【发布时间】:2015-05-29 18:43:14
【问题描述】:
我遇到了一个奇怪的问题,即 fitBounds 在 ajax 调用后无法正常工作。在初始页面加载时,fitBounds 工作正常,并且将 5 个标记居中。但是,在我单击其中一个下拉过滤器或分页(触发 ajax 函数以更新标记)后,它不想加载,即使它似乎试图根据标记的位置使地图居中是。过滤器肯定有效,因为我还在地图旁边输出了所有制造商位置的列表。
我还注意到,如果我将查询调整为一次仅显示 1 个标记,fitBounds 往往会更好地工作,尽管并非一直如此。似乎“for循环”中的某些东西可能会抛出一些东西。但我仍然没有 100% 的成功率,只显示 1 个标记。在大多数情况下,我似乎工作得更好一些。
无论我使用 ajax 函数输出多少标记,最终,在多次单击过滤器后,地图都会滞后。有时它会显示一个标记,但它后面的地图不会是正确的。有时,每次触发过滤器时,该地图都会开始变得越来越失真。另一个奇怪的是,一旦我触发了新标记的ajax功能,如果我将鼠标悬停在地图上的缩放栏上,它会自动滑到底部并且无法移动。如果我尝试通过单击和拖动来移动地图,整个地图就会变成纯灰色。
下面是页面加载后加载标记的第一个函数。它工作正常,此时 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 调用的另一个函数。同样,如果需要将多个标记添加到地图中,似乎会遇到麻烦。但是,这些函数在不使用 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
【问题讨论】:
-
请提供一个Minimal, Complete, Tested and Readable example 来证明这个问题。
标签: javascript jquery ajax google-maps google-maps-api-3