0

I need to add new draggable CircleMarker to the map when a user clicks on the map. Then the user should be able to move the circles around to change their position.

The code below works adding new markers and dragging them around, however a new marker is also added after the drag ends.

Now this is the sequence of events fired when a user moves a marker:

"marker:mousedown"
"map:mousedown"
"marker:mouseup"
"map:mouseup"
"map:click"

Due to the last (unexpected) map click event fired, a new marker is added after the drag ends.

Notice I used the bubblingMouseEvents option on the marker, assuming that would prevent the mousedown and mouseup events, generated when dragging a marker, to reach the map, but it doesn't seem to work.

So why a map click event is fired after dragging the marker and how can I prevent it? Using Leaflet v1.7.

Demo fiddler

map.on('click', (e) => {
  const marker = L.circleMarker(e.latlng, {
    color: '#f03',
    fillColor: '#f03',
    fillOpacity: 0.80,
    bubblingMouseEvents: false,
  })
  .on('mousedown', () => {
    map.dragging.disable();
    map.on('mousemove', (e) => marker.setLatLng(e.latlng))
  })
  .on('mouseup', () => {
    console.log('marker:up')
    map.dragging.enable();
    map.off('mousemove')
  })

  marker.addTo(map);
})
5
  • 1
    Question is essentially the same as this one: How to avoid popup open after drag and so also is the solution.
    – TomazicM
    Aug 30 at 10:40
  • @TomazicM the context is similar (and thanks for answering to the other question BTW), but here it might be useful to focus on exactly why the events are fired in the order I presented in the example. I do believe understanding how events are fired is very important
    – Stefano
    Sep 2 at 17:55
  • You discovered yourself what is the order of events being fired. Once you see it's not up to your liking and you can't change it, you use solution for your other question.
    – TomazicM
    Sep 2 at 18:10
  • Seeing the result does not mean you understand why that happen. Here bubblingMouseEvents=false, so why the event on the marker goes down to the map? Isn't what the property should prevent? Also, why dragging the marker (which is mousedown+mousemove+mouseup on the circle) generates also a click event on the map, whereas if you do the same on any point on the map (outside the circle) - therefore creating the same chain of events, the click event on the map is not fired?
    – Stefano
    Sep 2 at 20:11
  • Being long (50 years) in the software business I learned to be pragmatic. When I don't understand some software behavior, I don't loose too much time trying to understand the logic behind it. I take it as is and try to find solution that circumvents the problem.
    – TomazicM
    Sep 2 at 20:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.