Home > Net >  Leaflet - map not changed event
Leaflet - map not changed event

Time:01-03

When a user is panning heavily on a map, I want to stop loading the data and reload the data only when the user stops panning = the viewport/bounds are not changed anymore. Is there a possibility to listen to the "event", that a map does not change within a specific time frame?

To remove the data I check how much the viewport changes and given a certain threshold the data are removed. Now when the user stops the panning event, but only if this is true for multiple seconds, I assume the panning is finished and I want to reload the data. Waiting for some seconds is required, because after each little pan event, the moveend event is fired.

Any suggestions how to check that the maps viewport/bounds did not change for a certain time?

CodePudding user response:

For situations like this, you use a "debounce" function.

Its name comes from physical buttons. When you press down on a mechanical button, you might not get a perfect "off" and "on" signal but it might bounce between off and on for a short time.

This is the same problem you have. You have two states:

  • the user is moving
  • the user is not moving

and you need a clean "off" and "on" signal.

It can be as simple as this:

function makeDebounced(func, timeout) {
  let timer;
  return (...args) => {
    clearTimeout(timer); // no need to check for undefined.
    timer = setTimeout(() => func(...args), timeout);
  };
}

function stoppedMoving(name) {
  console.log(`You've stopped moving on the map, ${name}`);
}

const debouncedStoppedMoving = makeDebounced(stoppedMoving, 2000);

map.addEventListener('moveend', () => {
  debouncedStoppedMoving("Alice");
});

When the moveend event fires, the timeout in timer is set. If within 2000ms the event is fired again, the timer is cleared and a new one is started. If no new event is triggered, the timeout fires and your function is called.

The library underscore.js has a debounce function that also includes the option to cancel it and handles this nicer.

  • Related