71

I would like to load a geoJSON (polygon) file into my leaflet map. I have seen examples where geoJSON is embedded into the javascript code but I can't find any examples showing how it is done with an external file.

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css" />
    <script src="usStates.geojson" type="text/javascript"></script>
    <style>
        html, body, #map {
            height: 100%;
        }
        body {
            padding: 0;
            margin: 0;
        }
    </style>
</head>

<body>
    <div id="map" style="height: 100%"</div>
    <script src="http://d3js.org/d3.v2.min.js?2.9.3"></script>
    <script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js"></script>

    <script type="text/javascript"> 

    var map = L.map('map').setView([38.57, -94.71], 4);

    L.tileLayer('http://{s}.tile.cloudmade.com/9067860284bc491e92d2342cc51d47d9/998/256/{z}/{x}/{y}.png', {attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> Imagery © <a href="http://cloudmade.com">CloudMade</a>'}).addTo(map);

    var featureStyle = {
        "color": "#ff7800",
        "weight": 5, 
        "opacity": 0.2
    };

    L.geoJson(usStates).addTo(map);

    </script>

</body>
2
  • 1
    drag and drop the geojson onto geojson.io
    – Mapperz
    Aug 12, 2013 at 20:00
  • 2
    @Mapperz the OP was not asking about how to paste the contents of their geojson contents into the script.
    – Dave-Evans
    Nov 11, 2017 at 17:59

7 Answers 7

52

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.

0
32

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

21

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();
4
  • Thanks for the example - I took out the new keyword for the geoJSON factory function, but got a CORS error with the setRequestHeader line in there, so removed it and it worked fine (must be some setting in my server). Dec 3, 2017 at 14:36
  • Gives me a XML Parsing Error: not well-formed error at Line Number 1, Column 1:. Well, since the data is a geojson, why is it trying to parse it as XML? I don't understand the problem, but I'd like to import my data without Ajax. Dec 7, 2018 at 8:32
  • @AaronBramson have another try. This was quite an old code bit which I did. I should have set the responseType and use the response not parse the responseText. Just updated the code snippet. Dec 7, 2018 at 9:53
  • Yeah, this is great! It works out of the box without requiring any extra external packages and without requiring editing the data file. This is clearly the best answer. Dec 7, 2018 at 10:49
16

In the head element, you reference your files:

    <link rel="stylesheet" type="text/css" href="leaflet/leaflet.css" />
    <!--[if lte IE 8]>
        <link rel="stylesheet" type="text/css" href="css/leaflet.ie.css" />
    <![endif]-->
    <script src="leaflet/leaflet.js"></script>
    <script src="hydro_s.geojson" type="text/javascript"></script>
    <script src="hydro_l.geojson" type="text/javascript"></script>
    <style>
        html, body, #map {
            height: 100%;
        }
        body {
            padding: 0;
            margin: 0;
        }
    </style>
    <title>Leaflet Map with GeoJson</title>
 </head>

And then in the body:

<body>
    <div id="map"></div>
    <script type="text/javascript">

        var map = L.map('map', {
            center: [45.57, -73.5648],
            zoom: 10
        });

         /* Hydro */
        var hydro = new L.LayerGroup();
        L.geoJson(hydro_s, {style: hydrosStyle}).addTo(hydro);
        L.geoJson(hydro_l, {style: hydrolStyle}).addTo(hydro);

    </script>
</body>

You don't have to "put" them in a layer group...

7
  • perfect! this is what I was looking for!
    – bailey
    Aug 12, 2013 at 20:16
  • 1
    using the Firebug web developer for firefox I am getting "ReferenceError: usStates is not defined" "(L.geoJson(usStates).addTo(map);" I referenced the file like you showed <script src="usStates.geojson" type="text/javascript"></script> and added L.geoJson(usStates).addTo(map); to the bottom of my code. any ideas?
    – bailey
    Aug 13, 2013 at 17:01
  • It must be something with src... Mine is in the head of the document (I edited my answer to add it completely)
    – fgcarto
    Aug 13, 2013 at 18:37
  • 2
    no variable is needed for the reference? does it matter that my file extension is .json instead of .geojson?
    – bailey
    Aug 13, 2013 at 18:45
  • 4
    This is a confusing answer, as it requires you to define the variables hydro_s, hydro_l in your data file, which technically would make the even invalid GeoJSON! See the other answers for more info... May 4, 2017 at 7:13
15

after adding var usStates = to the top of my geojson file the code worked.

1
6

The fetch function does the job:

fetch("filepath/filename.geojson")
.then(function(response) {
return response.json();
})
.then(function(data) {
L.geoJSON(data).addTo(map);
});
0
6

You can load external files using the Fetch API with async/await alternatively:

async function addGeoJson() {
    const response = await fetch("filepath/filename.geojson");
    const data = await response.json();
    L.geoJson(data).addTo(map);
}

addGeoJson();

Your Answer

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

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