leafletjs marker bindpopup() with options
Asked Answered
C

3

23

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.

Cosec answered 26/5, 2014 at 16:44 Comment(0)
C
18

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();
Consultation answered 27/5, 2014 at 2:32 Comment(3)
Ok, then that means, that you always have to create the popup first and then bind it to the marker. :-(Camboose
Well, 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);Camboose
And to set a fixed width for your popups, add to your styles: .leaflet-popup-content { width:500px; }Camboose
J
10

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.

Jumble answered 9/3, 2019 at 11:28 Comment(2)
I'd say this is what the OP (and I) was looking for.Terti
bravo Richard, great findAromatic
S
6

For maxWidth you should do this:

var popup = L.popup({
    maxWidth:400
});
marker.bindPopup(popup).openPopup();
Scaliger answered 27/5, 2014 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.