I am using Google Maps API v3 on a website I am developing. I have a drop-down box beneath my map which allows the user to switch between different sets of markers to be displayed on the map. Each marker is displayed using marker.setMap()
.
My problem is that the map sometimes takes a long time to display the new markers, especially in IE. I want to show a "Loading" animation while the map is switching markers. But I don't know how to detect when the map has finished displaying the new data (there is no page load, since this is all AJAX). Is there a callback or event listener for a setMap()
event, so I can call a function to stop the "Loading" animation when the last marker has finished loading?
There doesn't seem to be a callback or event listener for setMap(), but I figured out a way to accomplish what I wanted. I am loading the Google Map using jQuery. Here is my code.
When initializing the map, I set up a listener for the 'idle' event, which hides the "loading" animation. The 'idle' event is triggered whenever the map is finished redrawing after a scroll or zoom change:
google.maps.event.addListener(this.map, 'idle', function() {
$('#loading').hide();
});
And in my function to clear overlays, I first show the loading animation, then clear each marker using setMap(null). Then I very slightly recenter the map by changing the longitude by .000000001. This happens after all the setMap() calls, and triggers the 'idle' event which hides the loading animation.
// clear overlays from the map
function clearOverlays() {
$('#loading').show();
// clear the markers from the active data array
if (activeData) {
for (i in activeData) { activeData[i].setMap(null); }
}
activeData = '';
// very slightly recenter the map to trigger the 'idle' event
var centerlat = MYMAP.map.getCenter().lat();
var centerlng = MYMAP.map.getCenter().lng() + .000000001;
recenter = new google.maps.LatLng(centerlat, centerlng);
MYMAP.map.setCenter(recenter);
}
It is a bit of a hack, but I hope someone else finds this useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With