Search code examples
javascriptleafletlazy-loadingmarker

Leaflet bindpop() using lazyload of images


I'm using leaflet to put some markers on a map. I have set that, clicking on a marker, a popup will be opened showing an image. Here's a brief example:

var map = L.map('map')
   .addLayer(tile)
   .setView([initLat, initLon], initZoom);

var m = L.marker([lat, lon])
   .bindPopup('<img src="1.jpg"/>')
   .addTo(map);

My objective is to load those images ("1.jpg" in the example above) using lazy load, so it's only loaded when I click on the marker.

Does anyone knows how to do this?

Thanks!


Solution

  • You could set the content of the popup when the popup is opened.

    Let's create a custom popup with a lazyload option and without content :

    var m = L.marker([0, 0])
        .bindPopup(L.popup({
            lazyload: '<img src="1.jpg"/>'
        }))
        .addTo(map);
    

    You can then set a global handler to fill your popup when needed:

    map.on('popupopen', function(e) {
        var popen = e.popup;
        if (popen.options.lazyload) {
            popen.setContent(popen.options.lazyload);
        }
    });
    

    And a demo:

    var map = L.map('map', {
        center: [0, 0],
        zoom: 1
    });
    
    var m = L.marker([-30, 0])
        .bindPopup(L.popup({
            lazyload: '<img src="https://i.sstatic.net/shfxy.jpg?s=32&g=1" />'
        }))
        .addTo(map);
    
    map.on('popupopen', function(e) {
        var popen = e.popup;
        if (popen.options.lazyload) {
            popen.setContent(popen.options.lazyload);
        }
    });
    html, body {
      height: 100%;
      margin: 0;
    }
    #map {
      width: 100%;
      height: 150px;
    }
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.js"></script>
    
    <div id='map'></div>