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) {

// 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) {


1 Answer 1


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>";


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

        sites = L.geoJson(data, {

            onEachFeature: forEachFeature,

            pointToLayer: function(feature, latlng) {

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

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

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
    Commented Sep 12, 2018 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. Commented Sep 12, 2018 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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