Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

javascript - Leaflet: adjust popup to picture size

I'm trying to include pictures in my leaflet popups, but the popup-size doesn't adjust to the picture size. I found a solution to this on github:

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

While that solution fixes the size of the popup, the result is shifted and the popup doesn't show up centered over the icon/marker... Any way to change that?

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

screenshot from 2016-07-03 14 19 25

Also the other proposed solution (setting the maxWidth on the popup) doesn't help in my case. The popup width keeps on being the default width of 300px...

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply specifying maxWidth: "auto" option on the popup seems enough…

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

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


EDIT

Unfortunately, if the image is not loaded yet in browser cache, the popup will open right away with default size, and adjust its size but not its position once the image is fully loaded and displayed. As a result, the popup is shifted and its arrow is misplaced compared to the marker it is bound to.

A simple workaround is to listen to the image "load" event and to re-open the popup at that moment:

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 is a more general solution: capture the <IMG>'s "load" event on all Leaflet popups and force them to update() every 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/

Reference: Leaflet issue #5484 (comment)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...