[GIS] How to show a popup in a map, using Leaflet

ajaxgeojsonleafletpopup

How can I show a popup in a map, using Leaflet, loading the markers from an GeoJSON external file?

function onEachFeature(feature, layer) {

    if (feature.properties && feature.properties.popupContent) {
        layer.bindPopup(feature.properties.popupContent);
        //console.log(feature.properties.popupContent)
    }
}

// Llamadas a los archivos .geojson con Ajax
let xhr = new XMLHttpRequest();
xhr.open('GET', './geojson-farmer.geojson');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
    if (xhr.status === 200) {
        L.geoJSON(JSON.parse(xhr.responseText)).addTo(farmer);
        console.log(L.geoJSON(JSON.parse(xhr.responseText),{onEachFeature:onEachFeature})).addTo(farmer);

    }
};
xhr.send(); 

Best Answer

Here is a working example, for points. I used JQuery to get the data from my external GeoJSON file. Note You need it running from a server or localhost if your using an external data file. In this case my GeoJSON file is in the same folder as my html file. http://www.gistechsolutions.com/leaflet/DEMO/Drink/Drink.html

My GeoJSON file:

var url = 'Drink.json';

The basic code:

    function forEachFeature(feature, layer) {
        var popupContent = "<p> <b>" + feature.properties.Misc + 
            "</b></br>"+ feature.properties.Street +
            "</br>"+ feature.properties.City +
            ",</br> "+ feature.properties.State +
            ", "+ feature.properties.Zip + "</p>";

        layer.bindPopup(popupContent);
    }

    // Get GeoJSON data and create features.
  $.getJSON(url, function(data) {

        sites = L.geoJson(data, {

            onEachFeature: forEachFeature,

            pointToLayer: function(feature, latlng) {

                return L.circleMarker(latlng, {
                radius:6,
                opacity: .5,
                color: "#000",
                fillColor:  'red',
                fillOpacity: 0.8
                });
            }


        }); 
        map.fitBounds(sites.getBounds(), {padding: [12, 12]});
        sites.addTo(map);

For a Polygon example: http://www.gistechsolutions.com/leaflet/DEMO/basic/basic_Poly.html Just right click view source to see the code.