Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

idle event on Google-maps with jQuery

I set a google map in my site, and I want to reload the markers whenever the map's bounds changes (by drag or zoom).

I was using jQuery to add the map and clear the markers at first:

$('#map_canvas').gmap();
$('#map_canvas').gmap('clear', 'markers');

and then, add the markers with:

$('#map_canvas').gmap('addMarker', {'position': position, 'bounds': true });

My question: How can I "catch" the event of moving the map? I already read that there is the idle event, and I saw an example:

google.maps.event.addListener(map, 'idle', function() {
});

but anything that I put instead of the "map" variable doesn't work... I also tried:

map = new google.maps.Map(document.getElementById("map_canvas"));

Does anyone has an idea?

Thanks a lot,

Danny

like image 748
Dan Avatar asked Sep 15 '11 08:09

Dan


2 Answers

For others having this issue:

You can get the map object/variable like this:

$('#map_canvas').gmap();
var map = $('#map_canvas').gmap('get', 'map');

Once you have the map object, you can attach event listeners to it:

$(map).addEventListener('idle', function() {
    console.log('Map is now idle');
    console.log(map.getCenter());
});

HTH

like image 122
Peter Avatar answered Sep 22 '22 05:09

Peter


inside your defined function you can do whatever you want. It is called always the map bounds change. For example:

google.maps.event.addListener(map, 'idle', function() {
 var bounds = map.getBounds();
 var sw = bounds.getSouthWest();
 var ne = bounds.getNorthEast();
 alert("minimum lat of current map view: " + sw.lat());
});

"map" should be the google map you created before.

var map = new google.maps.Map( document.getElementById('map_canvas'), myOptions );

Cheers! Thomas

like image 37
user1295226 Avatar answered Sep 22 '22 05:09

user1295226