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();
Share:
41,013

Related videos on Youtube

nexus_6
Author by

nexus_6

Updated on March 25, 2020

Comments

  • nexus_6
    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
    erik over 8 years
    Ok, then that means, that you always have to create the popup first and then bind it to the marker. :-(
  • erik
    erik over 8 years
    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);
  • erik
    erik over 8 years
    And to set a fixed width for your popups, add to your styles: .leaflet-popup-content { width:500px; }
  • betakilo
    betakilo over 3 years
    I'd say this is what the OP (and I) was looking for.
  • alex351
    alex351 almost 3 years
    bravo Richard, great find