Load markers first and then data for each popup when clicked in Leaflet Map

Viewed 1177

I am trying to load 300 markers at a time from an API and since I'm trying to load the data also for pop-up which contains image, it takes too much time to load the markers as well. I want to know if I can load the markers as soon the map opens and then load the image for each marker pop-up when clicked on that particular marker.

This is my piece of code:

fetch('http://www.example.com/data.php?qty=250')
        .then((response) => response.json())
        .then((response) => {
            let datapoint = response.datapoint;
            for (let i=0; i<datapoint.length; i++) {

                let lat = parseFloat(datapoint[i]["lat"]);
                let lon = parseFloat(datapoint[i]["long"]);
                let popup = L.popup().setContent("<img src=\""+datapoint[i].img+"\" width='32%' height='135px'/>" + '<h3>');
                let markerLocation = new L.LatLng(lat, lon);
                let marker = new L.marker(markerLocation,{icon: greenIcon});
                marker.addTo(map).bindPopup(popup,customOptions);

                marker.setOpacity(1.0);
            }

            document.getElementById('loader').style.display='none';
        })

I tried to add this code but not sure what to do:

marker.bindPopup(function() {
    var el = $('<div/>');

    $.get("DYNAMIC_CONTENT_URL").done(function(data) {
        el.setContent(data);
        popup.update();
    });

    return el;
});

Here is my sample data:

{"datapoint":[{"img":"abc.jpeg","latitud":"18.52","longitud":"82.4767"},{"img":"bbc.jpeg","latitud":"17.7375","longitud":"82.8347"}]}

Any help is appreciated! Thanks.

1 Answers

This is how you could do it. Bind an onclick event to the marker as it is created, then have a function that creates an independant popup on click.

Example:

var data = {
    "datapoint":[
            {"img":"abc.jpeg","latitud":"18.52","longitud":"82.4767"},
            {"img":"bbc.jpeg","latitud":"17.7375","longitud":"82.8347"}
        ]
}

function markerOnClick(e){
    L.popup()
    .setLatLng(e.latlng)
    .setContent('<img src="'+e.target.img+'">')
    .openOn(map);
}

for(i in data.datapoint){
    var marker = L.marker([data.datapoint[i].latitud, data.datapoint[i].longitud]);
    marker.img = data.datapoint[i].img;
    marker.on('click', markerOnClick);
    map.addLayer(marker);
}

You probably want to look into layerGroups, so you can group all these markers and do things like turn them on and off or update all of them as markers are added and remove, but this is a bare bones example.

There is no need for ajax in this example, as the image will not be downloaded until the popup is created. You would need to use ajax if you wanted to add other content.

I have added a JSFiddle with the leaflet example to show how it works. you will want to play around with the size of the popup to suit your needs

Related