The Google Map bounds_changed event fires several times when dragging

I have a Google map with markers. I want my markers to be updated when moving / enlarging the map ...

Google recommends using the bounds_changed event for this, but when I move the map, the event fires for every pixel I move the map to . I want the map to be updated only when the user has stopped moving the map, i.e. when he released the mouse button after dragging.

How can i do this?

+57
javascript javascript-events dom-events google-maps
Dec 02 '10 at
source share
6 answers

Turns out it was a mistake: http://code.google.com/p/gmaps-api-issues/issues/detail?id=1371 .

The Google team recommends using the idle event. For example:

 google.maps.event.addListener(map, 'idle', function() { }); 
+114
Dec 04 '10 at
source share

While the selected answer is suitable for most conditions. If you want to control the delay yourself, you can simply use something like:

  var mapupdater; {....} google.maps.event.addListener(map, "bounds_changed", mapSettleTime); function mapSettleTime() { clearTimeout(mapupdater); mapupdater=setTimeout(getMapMarkers,500); } 
+10
06 Oct '12 at 23:14
source share

Add a timeout that runs your code 500 ms after the event occurs, each time the event clears the timeout and creates a new one.

 google.maps.event.addListener(map, 'bounds_changed', (function () { var timer; return function() { clearTimeout(timer); timer = setTimeout(function() { // here goes an ajax call }, 500); } }())); 
+6
Jun 29 '12 at 8:28
source share

You should check how the debounce function works. A good article by Taylor Keyes defines this as follows:

This function is designed to limit the number of function calls: scroll events, mouse events, and keystroke events - these are all great examples of events we might want to capture, but it can be quite complicated if we collect them every time they shoot

So, you define a function somewhere in your code:

 function debounce(fn, time) { let timeout; return function() { const args = arguments; const functionCall = () => fn.apply(this, args); clearTimeout(timeout); timeout = setTimeout(functionCall, time); } } 

Then you just use this function when adding a listener:

 google.maps.event.addListener(myMap, 'bounds_changed', debounce(() => { /* Do something here */ }, 250)); 

250 ms seems to be a good frequency to use here.

+3
Mar 22 '18 at 1:33
source share

try using both zoom_changed and dragend

+1
Dec 02 '10 at 18:39
source share

Here is a small snippet that will remove all the extra calls to 'bound_changed':

 var timeout; google.maps.event.addListener(map, 'bounds_changed', function () { window.clearTimeout(timeout); timeout = window.setTimeout(function () { //do stuff on event }, 500); }); //time in ms, that will reset if next 'bounds_changed' call is send, otherwise code will be executed after that time is up 
+1
Oct 05 '13 at
source share



All Articles