I have a google maps set up with pointers. I've set it up so whenever the zoom changes or the viewport does it loads a new set of pointers accordingly:
google.maps.event.addListener(xmap, 'zoom_changed', function(event){
tm.update();
});
google.maps.event.addListener(xmap, 'bounds_changed', function(event){
tm.update();
});
google.maps.event.addListenerOnce(xmap, 'tilesloaded', function(){
tm.update();
});
I have also set it so that clicking on any pointer would open an infobox that would be populated with data from an ajax query. The problem is that I need to set it up so that if lets say a pointer is to the far edges of the view port it should pan to the center or to a position where when the infowindow opens up it can be viewed in the entire port.
The issue arises is that at times the infowindow when it loads can be too big for the view port and causes the map to pan and that in turn triggers the update function repopulating the pointers again.
WHats the best w开发者_JS百科ay to handle this.
So what you could perhaps do is have something like a boolean flag to indicate whether or not to call tm.update(). In your event handler for marker clicks (to open the infowindows), set it to false. Then in your bounds_changed event handler, only call tm.update if that boolean value is true. Then perhaps at the end of bounds_changed, reset it back to true.
Another guess - not to remove and overwrite markers that is already visible (falling into map.getBounds()). When you recive response with new markers to add - verify, if it's not already there.
UPDATE: After bounds_changed you have new bounds. Then you query your server and get marker coords and other associated data you need. When you adding markers on to the map, save references to them, say, in hash. If you have some unique id - it's perfect. In other case, invent some kind of identifier for marker. Then we need to add new markers and possibly remove some of them, that is hidden. Like this:
// somewhere initially
var markersOnMap = {}
// when got data and adding new markers
markersData = array of markers you've received from request
for (var i=0; i < markersData.length; i++)
{
var datum = markersData[i];
if (typeof(markersOnMap[datum.id]) == 'undefined')
{
// add marker to map
var marker = new google.maps.Marker({
position: ...,
etc.
});
marker.setMap(mymap);
markersOnMap[datum.id] = marker;
}
}
// you may clean up hidden markers or
// leave it for future or what you want.
// suppose we delete out of view markers
for (var id in markersOnMap)
{
if (!mymap.getBounds().contains(markersOnMap[id].getPosition()))
{
// get rid of it
markersOnMap[id].setMap(null);
delete markersOnMap[id];
}
}
精彩评论