Geojson benefits the geo-data visualzing. Here we introduce two methods of loading external geojson to Leaflet.

Data Stucture

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"type": "Feature",
"id": 0,
"geometry": {
"type": "Polygon",
"coordinates":
...
...
},
"properties": {
"FID": 0,
"NAME": "district 1",
"s1980": 0,
"s1981": " ",
...
}
}

geometry saves the information of location. properties saves added information of the place, which is very friendly for feature web mapping.


Method 1: organize .geojson as .js

Organize the .geojson file as a .js file, for example named as geojson_data.js:

1
2
3
4
5
6
var geojson1 = {
"type": "FeatureCollection",
...
}

var geojson2 = {...}

Then import the .js file to the HTML file as a script:

1
2
<!-- add the file in the head -->
<script src="geojson_data.js" type="text/javascript"></script>

Then the geojson can be used in the code as an global variable, using geojson1 and geojson2 directly in the codes.


Method 2: read .geojson with AJAX

Firstly, add jQuery and .geojson to the HTML file:

1
2
3
4
5
<!-- Add jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<!-- add geojson file -->
<link rel="location" type="application/json" href="geojson_data.geojson"/>

Then read the geojson file with AJAX in script:

1
2
3
4
5
6
7
8
var geojson_file = $.ajax({
url:"geojson_data.geojson",
dataType: "json",
success: console.log("Data successfully loaded!"),
error: function (xhr) {
alert(xhr.statusText)
}
})

However, the geojson data is not the geojson_file we read in the last step. Therefore, we need to extract the geojson data out from geojson file. But, loading the geojson file might take some time, the data extraction can be done only after the file successfully loaded. Otherwise, the errors will be arised as:

1
error: Invalid GeoJSON object

Here we use when().done() to solve this problem.

1
2
3
4
5
6
7
8
9
10
// when the data is ready, draw GeoJSON
$.when(geojson_file).done(function() {
var geojson = geojson_file.responseJSON;

// Add requested external GeoJSON to map
var Layer_GDP = L.geoJSON(geojson, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
});


Method3: load with Leaflet AJAX

I tried, it does not work for now!

1
var geojsonLayer = new L.GeoJSON.AJAX("geojson.json");

Reference

Loading External GeoJSON: A(nother) Way to Do It with jQuery