Google Maps: InfoWindow closing after auto pan
I have a map with a bunch of markers, and a table of data that corresponds to each marker. When the user clic开发者_StackOverflow社区ks on an item in the table, the InfoWindow
for the corresponding marker is opened. Everything works fine when the map is zoomed out and the markers are all visible, but if the map is zoomed in, and an InfoWindow
for an off-screen marker is opened by clicking the item in the table, here is what happens:
- The map scrolls to the correct location, where the
InfoWindow
already appears open - The map stops panning, and the
InfoWindow
disappears.
Any suggestions as to what might be going on and how to solve this?
Alright, the issue related to the fact that I was using the Marker Clusterer on the map... essentially, the following was happening:
- Click item in table,
InfoWindow
opens - Map gets panned to the location to display the
InfoWindow
- When panning is complete, the Marker Clusterer was then re-drawing (if needed), and forcing the
InfoWindow
closed.
My solution was that when an item in the table is clicked, I get the corresponding Marker's
latlng, manually pan to this location, wait for the panning to complete via the 'idle' listener, and when complete (and the Clusterer has done it's re-draw), THEN I open the InfoWindow
.
// get map, marker positions
var mapLatLng = GLOBAL_map.getCenter();
var markerLatLng = GLOBAL_markers[index].getPosition();
// pan the map
if(!markerLatLng.equals(mapLatLng)) {
// map will need to pan
GLOBAL_map.panTo(markerLatLng);
google.maps.event.addListenerOnce(GLOBAL_map, 'idle', function() {
// open InfoWindow
GLOBAL_infowindow.setContent(GLOBAL_markers_content[index]);
GLOBAL_infowindow.open(GLOBAL_map, GLOBAL_markers[index]);
});
} else {
// map won't be panning, which wouldn't trigger 'idle' listener
GLOBAL_infowindow.setContent(GLOBAL_markers_content[index]);
GLOBAL_infowindow.open(GLOBAL_map, GLOBAL_markers[index]);
}
This drove me crazy. My solution is simpler, though. I just set a timer so I don't refresh the map within one second after a pin is clicked.
start with the global:
// global timer variable
var clickTime = Date.now() - 1001;
then define you marker click like:
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
clickTime = Date.now();
});
then set up your idle like:
google.maps.event.addListener(map, 'idle', function () {
if (Date.now() > (clickTime + 1000))
updateMap();
});
Don't use idle
event. Use dragend
and zoom_changed
events from the API spec instead which will allow you to open your infoBoxes without refreshing the map.
google.maps.event.addListener(map, 'dragend', function() {
getMarkers();
});
google.maps.event.addListener(map, 'zoom_changed', function() {
getMarkers();
});
精彩评论