Tuesday, 25 October 2016

How do you load a GeoJSON file in Leaflet?


I'm stumped as to how to add a GeoJSON layer to an OSM map. Through Google, I've found a bunch of different answers, none of which seem to work. Following the Leaflet documentation, the simplest way to do so is with this code:


var map = L.map('map').setView([51.505, -0.09], 15);

L.tileLayer('http://{s}.tile.openstreetmap.se/hydda/full/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMapcontributors'
}).addTo(map);

L.geoJson(data, {
style: function (feature) {

return { color: feature.properties.color };
},
onEachFeature: function (feature, layer) {
layer.bindPopup(feature.properties.description);
}
}).addTo(map);

Questions: what exactly do I enter for the "data" variable? I keep a file in the path "~/Scripts/worldmap.geojson", but a direct URL string doesn't work. I'm using jQuery, and it's $.getJSON function does not seem to work.



Answer



The GeoJSON needs to be formatted like a javascript object variable.



So rename the file extension of the geojson file to .js (ie. worldmap.js) and open it in your text editor.


Add:


var worldMap = [ 

in front of the data already in the file, and then a


]; 

at the end (thus turning it into a regular JSON object.)


Load the file like you would load a regular javascript file in HTML:





...and exchange 'data' in 'L.GeoJSON(data, {...' with worldMap (the variable you just created in the other file.)


Hopefully this should work. Make sure the GeoJSON file is in WGS84 though.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...