1

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(); 
2

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.

  • Hi! i'm trying to do it with vanilla js but i'm a beginner with ajax. I can not do it.... – Antonio Sep 12 '18 at 19:42
  • I tried it that way when I first started, found it was easier to use JQuery and avoided the extra code and browser issues. I can't find an old example, sorry. – Bill Chappell Sep 12 '18 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.