51

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>
  • drag and drop the geojson onto geojson.io – Mapperz Aug 12 '13 at 20:00
  • @Mapperz the OP was not asking about how to paste the contents of their geojson contents into the script. – Dave-Evans Nov 11 '17 at 17:59
34

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.

25

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

11

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...

  • 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) – fgcartographix Aug 13 '13 at 18:37
  • 1
    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
  • 2
    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 4 '17 at 7:13
11

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();
  • 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 3 '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 7 '18 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. – Dennis Bauszus Dec 7 '18 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. – Aaron Bramson Dec 7 '18 at 10:49
10

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

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.