leafletjs marker bindpopup() with options
41,013
Solution 1
Are you sure that you're reading the Leaflet reference documentation? It specifies that you can bind a popup with options by creating it and calling .bindPopup with it. For instance,
var popup = L.popup()
.setContent("I am a standalone popup.");
marker.bindPopup(popup).openPopup();
Solution 2
You can pass an object of popup options as the second argument of bindPopup, like this:
marker.bindPopup("<strong>Hello world!</strong><br />I am a popup.", {maxWidth: 500});
I've tested this in Leaflet 1.4, and it also seems be available in earlier versions of bindPopup.
Solution 3
For maxWidth you should do this:
var popup = L.popup({
maxWidth:400
});
marker.bindPopup(popup).openPopup();
Related videos on Youtube
Author by
nexus_6
Updated on March 25, 2020Comments
-
nexus_6 about 4 years
The leaflet documention shows you can add a popup to a marker with
marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
or create a standalone popup with
var popup = L.popup() .setLatLng([51.5, -0.09]) .setContent("I am a standalone popup.") .openOn(map);
Is there no way to set popup options and bind it to a marker? I want to be able to set my own maxwidth for popups and have them open/close when you click a marker.
-
erik over 8 yearsOk, then that means, that you always have to create the popup first and then bind it to the marker. :-(
-
erik over 8 yearsWell, this one-liner is possible:
var mark1=L.marker([51.5, -0.09]).bindPopup(L.popup({maxWidth:500}).setContent("I am a standalone popup.")).addTo(map);
-
erik over 8 yearsAnd to set a fixed width for your popups, add to your styles:
.leaflet-popup-content { width:500px; }
-
betakilo over 3 yearsI'd say this is what the OP (and I) was looking for.
-
alex351 almost 3 yearsbravo Richard, great find