CraZyDroiD
CraZyDroiD

Reputation: 7105

Prevent closing popup when clicking on same marker in Leaflet

I have a code which renders a popup to a marker using leaflet and it's as follows:

const lat = e.latlng.lat;
   if ($('#lmap').css("cursor") === 'crosshair') {
      const note = `<div>popup<div>`;
      const newMarker = new L.marker(e.latlng,{draggable:true}).addTo(lmap);
      if (!(note === "")) {
         newMarker.bindPopup(note, {closeOnClick: false, autoClose: false, closeButton: true}).openPopup();
      }
   }

Here

closeButton: true 

is used to render a close button in my popup. But the problem is popup closes when i click on the marker also. How can i prevent closing of the popup when clicking on the marker and just to close it when clicking on the close button in the popup.

Upvotes: 2

Views: 3769

Answers (1)

Falke Design
Falke Design

Reputation: 11338

Don't add the popup directly to marker, create a popup "layer" and open it, when clicked on the marker:

// a global variable
var popup = L.popup({closeOnClick: false, autoClose: false, closeButton: true});


//your function from above
const newMarker = new L.marker(e.latlng,{draggable:true}).addTo(lmap);
newMarker.on('click',(e)=>{
    popup.options.offset = e.target.options.icon.options.popupAnchor;
    popup.setContent('TEST').setLatLng(e.target.getLatLng()).addTo(map)
})

Upvotes: 2

Related Questions