How to show an image and a link on a popup when clicking on a leaflet marker?

Currently, I have this code to show an image on a popup when clicking on the marker:

const marker3 = L.marker([22.78257, -94.5612], {icon: redIcon}).on('click', onClick2).addTo(map);

// When click on red marker, open popup with the image
function onClick2(e) {
    popupContent = document.createElement("img");
    popupContent.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Stack_Exchange_logo_and_wordmark.svg/375px-Stack_Exchange_logo_and_wordmark.svg.png";
    marker3.bindPopup(popupContent, {
        maxWidth: "auto"
    });
}

I want to also show a link to the image on the popup, so that when clicked, it can be displayed full size on a new tab on the browser. Preferable the link is edited or something, so that it does not take much space on the screen.

Answer

How about changing the popupContent like below so that you can change the popup content flexibly? (The link should work in your environment.)

Also, I think onClick function is not necessary.

const src = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/75/Stack_Exchange_logo_and_wordmark.svg/375px-Stack_Exchange_logo_and_wordmark.svg.png";
const popupContent = document.createElement("div")
popupContent.innerHTML = "<img src='" + src + "'>"
                       + "<a target='_blank' href='" + src + "'>See the image</a>"

const map = L.map('map').setView([10, 20]);
const marker = L.marker([10, 20]).bindPopup(
    popupContent,
    { maxWidth: "auto" }
).addTo(map);
#map {
    height: 360px;
}
<head>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
        integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
        crossorigin="" />
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
        integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
        crossorigin=""></script>
</head>
<body>
    <div id="map"></div>
</body>

Leave a Reply

Your email address will not be published. Required fields are marked *