GeoJSON in Leaflet.js
The latest version of Leaflet.js makes it easy to add data in GeoJSON format! Here's everything you need to know:
What is GeoJSON?
GeoJSON is a standard way to share points, lines, and polygon shapes in the JavaScript object format known as JSON. A page at http://geojson.org/ defines the standard.
You can see example GeoJSON files for countries and US states at https://github.com/johan/world.geo.json/tree/master/countries
In addition to Leaflet.js, GeoJSON is supported by the Google Maps API, QGIS, and many other mapping programs.
How do I get my data into GeoJSON?
In QGIS, you can right-click any layer and save it as a GeoJSON file.
How do I load a GeoJSON file into Leaflet?
First, make sure you are using the latest version of Leaflet.js and Leaflet.css. In jsFiddle, you can add them by clicking Add Resources, pasting a URL into a text field, and then clicking plus.
http://cdn.leafletjs.com/leaflet-0.4.4/leaflet.css
http://cdn.leafletjs.com/leaflet-0.4.4/leaflet.js
You can put a GeoJSON file directly into your page's code as a JSON file, include it as a string, or load it from your server. Here are examples of the first two:
// including a GeoJSON file directly in the page var haiti = {"type":"FeatureCollection","features":[
// loading a GeoJSON file from a string var haiti = '{"type":"FeatureCollection","features":[
How do I style my GeoJSON shapes?
The previous example made shapes with a blue outline and semi-transparent center. Why not make more interesting shapes?
You can control this by adding properties inside a style function. For example, this has a solid red outline and no fill color.
L.geoJson( haiti, {
style: function (feature) {
return { color: "#f00", opacity: 1, fillOpacity: 0 };
}
}).addTo(map);
This one has semi-transparent green fill and no outline.
L.geoJson( haiti, {
style: function (feature) {
return { opacity: 0, fillOpacity: 0.5, fillColor: "#0f0" };
}
}).addTo(map);
http://jsfiddle.net/8QHFe/127/
How do I add popups to my GeoJSON shapes?
No problem! You can add a popup in an onEachFeature function, similar to how you added a style:
L.geoJson( haiti, {
style: function (feature) {
return { opacity: 0, fillOpacity: 0.5, fillColor: "#0f0" };
},
onEachFeature: function(feature, layer){
layer.bindPopup("Hello GeoJSON!");
}
}).addTo(map);
http://jsfiddle.net/8QHFe/128/
How can i use GeoJSON properties in my Leaflet map?
Some GeoJSON files have properties for each shape, which you might use to set the features' style or popup content. In the Haiti file, the shape has a properties object of { "name": "Haiti" }
You can retrieve the name inside the style and onEachFeature functions using feature.properties.name
L.geoJson( haiti, {
style: function (feature) {
return { opacity: 0, fillOpacity: 0.5, fillColor: "#0f0" };
},
onEachFeature: function(feature, layer){
layer.bindPopup("Hello " + feature.properties.name);
}
}).addTo(map);