Leaflet: setting the popup to the image size

I am trying to include pictures in the flyer popups, but the popup does not adjust the image size. I found a solution for this on github:

https://github.com/Leaflet/Leaflet/issues/724

While this solution fixes the size of the popup, the result shifts and the popup does not appear in the center of the icon / marker ... Any way to change this?

.leaflet-popup-content { width:auto !important; } 

screenshot from 2016-07-03 14 19 25

Also, another proposed solution (setting maxWidth in a popup) in my case does not help. The default popup width is 300 pixels ...

 function pop_Fotos(feature, layer) { var popupContent = '<img style="max-height:500px;max-width:500px;" src="..."); layer.bindPopup(popupContent, {maxWidth: 500, closeOnClick: true}); } 

screenshot from 2016-07-03 14 49 15

+6
source share
2 answers

Just specifying the maxWidth: "auto" option in the popup seems like enough ...

 layer.bindPopup(popupContent, { maxWidth: "auto" }); 

Demo: http://jsfiddle.net/3v7hd2vx/29/


EDIT

Unfortunately, if the image has not yet been loaded into the browser cache, a pop-up window will immediately open with the default size and adjust its size, but not its position, as soon as the image is fully loaded and displayed. As a result, the pop-up window shifts and its arrow is inappropriate compared to the marker to which it is attached.

A simple workaround is to listen for the "load" event and reopen the popup at this point:

 popupContent = document.createElement("img"); popupContent.onload = function () { layer.openPopup(); }; popupContent.src = "path/to/image"; layer.bindPopup(popupContent, { maxWidth: "auto" }); 

Updated demo: http://jsfiddle.net/3v7hd2vx/32/


EDIT 2

Here's a more general solution: capture the <IMG> "load" event in all Leaflet popups and force them to update() each time.

 document.querySelector(".leaflet-popup-pane").addEventListener("load", function (event) { var tagName = event.target.tagName, popup = map._popup; // Currently open popup, if any. if (tagName === "IMG" && popup) { popup.update(); } }, true); // Capture the load event, because it does not bubble. 

Demo: https://jsfiddle.net/3v7hd2vx/277/

Link: Leaflet No. 5484 (comment)

+6
source

My content was a little more diverse than just a simple image, but the width, of course, still depended on the loading time of the images in the content (and it was normal when the image was in the browser’s cache).

So, when I hit this problem, in short, what I did with jQuery:

 function addpopup(mymarker, mycontent) { var myid = "thismarker"; // or whatever mymarker.bindPopup("<div id='"+myid+"'>" + mycontent + "</div>", {maxWidth: "auto"}); mymap.on("popupopen", function(e){ $("#"+myid+" img").one("load", function(){ e.popup.update(); }); }); } 
+2
source

All Articles