1

I need to detect when mouse over mapbox gl js ends movement in order to make a request to the server only when mouse has stopped the movement but it doesn't exist a "mouseStop" event or anything similar in Mapbox GL JS Api reference

Any idea how to solve this?

TomazicM
  • 25,601
  • 22
  • 29
  • 39
Toni BCN
  • 327
  • 1
  • 4
  • 17
  • How would you define "mouse has stopped the movement" event? – TomazicM Dec 01 '22 at 10:10
  • 2
    Mouse movement (or, reciprocally, stopping) events get triggered a bazillion times during interaction - you really don't want to use either as request hooks. Rather, each mousemove starts/restarts a timeout (so that, while the mouse is moving, it never actually times out) which only triggers a request after no movement has been registered for the timeout duration. – geozelot Dec 01 '22 at 10:20
  • @TomazicM I mean when mouse stops moving over the map, imagine an "mousemoveends" triggered just after mouse stops move. – Toni BCN Dec 01 '22 at 10:44
  • @geozelot Do you have an example that implements this idea? – Toni BCN Dec 01 '22 at 10:46
  • Even if/when you implement the solution that @geozelot proposed and is the only sensible one, you'll have to decide what "mouse stops moving" means for you, meaning how much time after the last detected mouse move has to pass to consider it as "mouse has stopped moving" event. – TomazicM Dec 01 '22 at 10:58

1 Answers1

1

I have found a solution that works for me along the lines of @geozelot's comments and based on 2on solution of https://stackoverflow.com/questions/17646825/how-to-detect-when-mouse-has-stopped implemented in jsfiddle

I've made this jsfiddle I've decided that timer was equal to 150ms, I think it is enough to detect when "mouse stops" @TomazicM you could try it.

Relevant code:

const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v11',
  center: [2.175, 41.40],
  zoom: 12
});

let timer;

function mouseStopped(){

document.getElementById("coordinates").innerHTML = "Mouse stopped";
console.log("Mouse stopped");

}

map.on("mousemove", function (e) {

clearTimeout(timer); timer = setTimeout(mouseStopped,150);

document.getElementById("coordinates").innerHTML = ${e.lngLat.lng}, ${e.lngLat.lat};

});

Toni BCN
  • 327
  • 1
  • 4
  • 17