Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a GoogleMap Canvas element is already idle

My question is pretty straight forward.

google.maps.event.addListenerOnce(map, 'idle', function() {
    // code
});

This snippet of code will trigger after the map is currently busy zooming or panning. Not when it's already idle.

Is there a way to check the status of the canvas in an if statement? So when it's already idle you'll do the // code without adding a listener?

like image 637
Sem Avatar asked Feb 04 '13 09:02

Sem


2 Answers

There is no documented property that signals the idle-status of the map, but you may implement it on your own.

Assuming you call this right after the initialization of the map:

google.maps.event.addListener (map, 'idle', function(){
           this.lastBounds=this.getBounds();
}); 

Then you may check if the lastBounds-property is equal to the current bounds of the map:

if (map.lastBounds==map.getBounds()){
    //call function immediately
}else{
    //add listener
}
like image 119
Dr.Molle Avatar answered Oct 23 '22 04:10

Dr.Molle


The solution for the accepted answer doesn't work for the v3. The Map::getBounds method uses the bounds object factory so it returns a new object for each call. So comparing against the last bounds always returns false.

The workaround is to use the 'bounds_changed' event instead as the following.

var isIdle = false; // Initializing the idle flag before the map is created

var map = new google.maps.Map(/* Map initialization arguments */)

map.addListener('idle', function() {
    isIdle = true;
});
map.addListener('bounds_changed', function() {
    isIdle = false;
});

if(isIdle) {
    // Do the idle stuff
} else {
    map.addListenerOnce('idle', function() {
        // Do idle stuff
    });
}
like image 35
Sergey Avatar answered Oct 23 '22 04:10

Sergey