I am trying to create a leaflet popup with dynamic content, it works but the popup bubble is not aligned with the marker.
Here is a screenshot, its clear that the popup bubble is not centered over the marker.
Here is the code
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {
maxZoom: 18,
id: 'examples.map-i875mjb7'
}).addTo(map);
m = L.marker([51.5, -0.09]).addTo(map);
m.bindPopup("<b>Hello world!</b><br />I am a popup<span id='a'></span>", {maxWidth: "none"})
m.openPopup();
$('#a').html('abcdefghijklmnopqrstuvwxyz')
Also here is a minimal jsfiddle example that describes the problem: http://jsfiddle.net/nk93shkt/
How do I fix this?
It looks like leaflet is determining the width of the infobox when it renders it. You're adding text after it's been displayed so leaflet no longer knows its actual size, and thus cannot center it properly.
Try the setPopupContent()
method from the documentation in this slightly long-winded example:
m = L.marker([51.5, -0.09]).addTo(map);
m.bindPopup("<b>Hello world!</b><br />I am a popup<span></span>", {maxWidth: "none"})
m.openPopup();
var a = m.getPopup();
var b = a._content.replace("<span></span>","<span>asdasdasda</span>");
m.setPopupContent(b);
JSFIDDLE
Just in case this is an issue for anyone without dynamic content; the issue of an offset popup for any customised icons can be explored in this documentation
see:
var greenIcon = L.icon({
iconUrl: 'leaf-green.png',
shadowUrl: 'leaf-shadow.png',
iconSize: [38, 95], // size of the icon
shadowSize: [50, 64], // size of the shadow
iconAnchor: [22, 94], // point of the icon which will correspond to marker's location
shadowAnchor: [4, 62], // the same for the shadow
popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor
});
From the example and edit the popupAnchor:
value to fit your specific zoning requirements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With