1

I am using Leaflet to display a map in Angular8. I want to add a marker to the clicked location. Everything works fine, except the fact that a marker is being added after I finish dragging the map, and I do not know how to prevent that.

My .html file looks like this:

<div id="mycontainer" class="container">
  <div class="map-container">
    <div class="map-frame">
      <div id="map"  (click)="addMarker($event)"></div>
    </div>
  </div>
</div>

And my addMarker function looks like:

addMarker(event){
let latlng = this.map.mouseEventToLatLnt(event);
L.marker([latlng['lat'],latlng['lng']]).addTo(this.map);
}

I have tried checking if the mouseEvent movement attributes are different from 0, but it didnt have any effect. I also tried to use a Boolean which would be set to false on dragstart and to true dragend/dragleave/dragexit event of the map, but none of that worked as well.

1 Answer 1

1

This is all about managing your event handlers. I'm going to remove the HTML into onclick function and do it all in one place in the js:

<div id="map"></div>

What we'll do is add an event listener to the map that listens for a mousedown event. Once that mousedown is heard, we will listen for one of two events on the map: either a mouseup, or a drag.

// Add initial event listener to map for a mouse down
leafletMap.addEventListener('mousedown', function(){

  // Start listening for a mouseup event
  leafletMap.addEventListener('mouseup', mouseupHandler)

  // Also start listening for a drag event
  leafletMap.addEventListener('drag', dragHandler)

})

Each handler has its own job. If a mouseup is heard without any drag being heard first, it will fire off your function to place a marker at that point. If a drag event is heard first, it will simply remove the 'mouseup' eventlistener from the map.

function mouseupHandler(e){
  placeMarker(e)
  cleanUpEventListeners()
}

function dragHandler(){
  cleanUpEventListeners()
}


function placeMarker(e){
  L.marker(e.latlng).addTo(leafletMap)
}

function cleanUpEventListeners(){
  leafletMap.removeEventListener('mouseup', mouseupHandler)
  leafletMap.removeEventListener('drag', dragHandler)
}

You'll notice that regardless of whether the mouseup or drag is heard first, it calls cleanUpEventListeners, which removes the two eventlisteners from the map. If we don't do this, then every time the map hears a mousedown, it will add those eventlisteners again, and we end up attaching a bunch of eventlisteners again and again.

Here is a working codesandbox with some console.log statements in each handler so you can track what is happening.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.