Loading external GeoJSON file into Leaflet map?

Look into Leaflet-Ajax. It streamlines everything. Will give up-vote for Neogeomat for mentioning it.

Get the script here (github repo) and add it to your header:

<script src="/js/leaflet-0.7.2/leaflet.ajax.min.js"></script>

Then it's a matter of uploading with the file name.

var geojsonLayer = new L.GeoJSON.AJAX("foo.geojson");       
geojsonLayer.addTo(map);

Really straight forward fix and it works. So yay.


You can use jquery Ajax to load data and then add it.

var district_boundary = new L.geoJson();
district_boundary.addTo(map);

$.ajax({
dataType: "json",
url: "data/district.geojson",
success: function(data) {
    $(data.features).each(function(key, data) {
        district_boundary.addData(data);
    });
}
}).error(function() {});

or You can use leaflet-ajax plugin


Here is my minimum vanilla js solution. Look ma, no jquery needed for a quick ajax call to a file.

let xhr = new XMLHttpRequest();
xhr.open('GET', 'uk_outline.geojson');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'json';
xhr.onload = function() {
    if (xhr.status !== 200) return
    L.geoJSON(xhr.response).addTo(map);
};
xhr.send();