Load External Geojson to Leaflet
Geojson benefits the geo-data visualzing. Here we introduce two methods of loading external geojson
to Leaflet
.
Data Stucture
1 | { |
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 | var geojson1 = { |
Then import the .js
file to the HTML
file as a script:
1 | <!-- add the file in the head --> |
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 | <!-- Add jQuery --> |
Then read the geojson
file with AJAX
in script:1
2
3
4
5
6
7
8var 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