72

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>
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
bailey
  • 1,281
  • 1
  • 13
  • 20

7 Answers7

53

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.

FredFury
  • 1,097
  • 2
  • 10
  • 19
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

neogeomat
  • 8,380
  • 3
  • 52
  • 91
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();
Dennis Bauszus
  • 2,289
  • 3
  • 21
  • 31
  • 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). – Brian Burns Dec 03 '17 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. – Aaron Bramson Dec 07 '18 at 08: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. – Dennis Bauszus Dec 07 '18 at 09: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. – Aaron Bramson Dec 07 '18 at 10:49
  • How to style stroke and fill of a polygon? – Kevin A Aug 07 '23 at 19:40
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...

SteveC
  • 547
  • 1
  • 5
  • 24
fgcarto
  • 1,524
  • 3
  • 17
  • 27
  • perfect! this is what I was looking for! – bailey Aug 12 '13 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 '13 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 '13 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 '13 at 18:45
  • The file can be .json or even .js. I have a variable in my example because I create a layergroup. Technically, your "L.geoJson(usStates).addTo(map);" should work. I'm not an advance Leaflet user though. – fgcarto Aug 13 '13 at 18:57
  • 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... – Florian Ledermann May 04 '17 at 07:13
  • @fgcartographix, will the function hydrolStyle be similar to https://gis.stackexchange.com/a/330965/139465? The function will simply read style in the Geojson file? – Cloud Cho Nov 02 '19 at 04:47
16

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

bailey
  • 1,281
  • 1
  • 13
  • 20
9

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

F1refly
  • 241
  • 2
  • 3
8

The fetch function does the job:

fetch("filepath/filename.geojson")
.then(function(response) {
return response.json();
})
.then(function(data) {
L.geoJSON(data).addTo(map);
});
CaD
  • 417
  • 4
  • 14