Casey Cao Casey Cao -4 years ago 140
jQuery Question

leaflet how to make dynamic picture popup using js

hello I am using leaflet to display dynamic images on a map:
I have a var img which represent the url of image src

var img="http://xx.xx.xx.xx/"

$("<img/>").attr("src", img).appendTo("#images");

And I have a popup window(HTML) which include my images id:images

var marker = L.marker([lat,lng]).bindPopup('<div id="images"></div>').addTo(map);

But the picture is not showing on the popup? anyone has simply solution? thanks

Answer Source

My best guess is (since you didn't share your complete code and did not add an example) that you are trying to access the element with id images when it's not attached to the DOM yet. The HTML string you provided as popup content gets turned into an actual element and appended to the DOM when the popup opens.

Your best option here is to not use a HTML string as popup content but an actual HTML element and keep a reference:

// Create element
var div = L.DomUtil.create('div', 'my-div');

Use the element as popup content:

// Create marker bind popup with content and add to map;
new L.Marker([0, 0]).bindPopup(div).addTo(map);

Now you can use the div reference to append new elements:

// Create img element and append to div
var img = L.DomUtil.create('img', 'my-img', div);
img.src = '';

This will work when the popup is opened and closed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download