Are you looking to create a map interactive application to locate markers with points, or to highlight an area by polygon or to draw or show a river or roads line with polyline? With Leafletjs library and GeoJSON as GIS data, we can easily create a map which we are looking for and render the output in browser. Leaflet js is an opensource small library to create interactive map. GeoJSON is one of the GIS data structure which stores geographic data in JSON format. GeoJSON supports point, line, polygon, multipolyline, multipolygon and Geometry collection which can represent a geometry, feature or a collection of features. A detailed structure of GeoJSON would be written in separate article.
Add or Load GeoJSON file
This Article would let you know how to render and load geoJSON file with the help of leaflet js library. Also you would also get an idea by this article to implement a click event over a GeoJSON file and fetch information associated with the feature of GeoJOSN data loaded as map.
If you are not familiar with Leaflet, I would recommend you to read first the Getting Started tutorial with Leaflet js Library to create map application.
Lets setup a Base Map First i.e loading openstreetmap or osm in leaflet, in a html file:
<!DOCTYPE html>
<html>
<head>
<title>Getting Started - Leaflet js Map interactive library</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
</head>
<body>
<div id="map" style="width: 1000px; height: 600px;"></div>
<script>
var newMap = L.map('map').setView([38.9188702,-77.0708398], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href=”http://osm.org/copyright”>OpenStreetMap</a> contributors'
}).addTo(newMap);
</script>
</body>
</html>
Above script would output and render an osm base map. Now lets start adding different features on map one by one with GeoJSON file.
Add or Load GeoJSON file – Load Polygon with leaflet on Map:
Add following script, and replace the ‘usa_adm.geojson’ to the file you are want to render.
// loading GeoJSON file - Here my html and usa_adm.geojson file resides in same folder
$.getJSON("usa_adm.geojson",function(data){
// L.geoJson function is used to parse geojson file and load on to map
L.geoJson(data).addTo(newMap);
});
After adding the polygon layer you may want to view or load the map area covered or extended by the polygon GeoJSON file. i.e On Map load you want to zoom and pan according to the extent or to fit layer bounds. For this, Leafletjs provided a function to calculate the bounding box of the geojson file or layer i.e layer.getBounds(). And also with leaflet map fitBounds function i.e map.fitBounds(“bounding coordinates”). Here is the line which you needs to add to script:
newMap.fitBounds(datalayer.getBounds());
Finally, we are left only adding a click event to get the features data. With the help of Leaflet L.geoJson optional object parameter with key “onEachFeature“, we can add and define click event on every feature of the layer.
Here we would be fetching the attribute data of the feature clicked on Polygon GeoJOSN file. So before writing any script, we need to list out the feature properties list. You can get those properties key name easily if you are familiar with JSON files and structure.
So lets define a function named as onEachFeature and replace the ‘key’ keyword with your actual feature properties key of GeoJSON file:
onEachFeature: function(feature, featureLayer) {
featureLayer.bindPopup(feature.properties.key);
}
So your final leaflet geojson code combines as i.e For adding polygon GeoJSON file on map, with click event and fit to extent functionality.
$.getJSON("usa_adm.geojson",function(data){
// add GeoJSON layer to the map once the file is loaded
var datalayer = L.geoJson(data ,{
onEachFeature: function(feature, featureLayer) {
featureLayer.bindPopup(feature.properties.NAME_1);
}
}).addTo(newMap);
newMap.fitBounds(datalayer.getBounds());
});
As I have loaded a US administrative polygon GeoJSON here, we can see following output as :
Add or Load GeoJSON file – polyline on Leaflet Map:
Adding polyline Geojson with leaflet library is same as adding polygon file. So the above code would work for loading polyline GeoJSON file. Just you need to replace the file name with your polyline GeoJSON file and features properties key have to replaced by the actual key name, of which you want to retrive information.
Add or Load GeoJSON file – point with Leaflet js on Map:
Adding Point GeoJSON file is same as loading Polygon GeoJSON file. Here is the output you can see for the famous world Cities.
If you find any difficulty in adding or loading GeoJSON file on map with leaflet library, do comment below with your queries.
Tanks for the tutorial , the jquery library is missing in the first html file . add it
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
Thanks Ahmed
can you show me final coding pf this program
How do you apply the fill color that was defined in geojson?
how can remove the polygon
I saved data in mysql using leaflet/angular6 with geojson format.
How to dshow polygon with saved coordinates.Can u plz guide me.
Not working at all,
My code looks like this:
Getting Started – Leaflet js Map interactive library
https://unpkg.com/leaflet@1.0.3/dist/leaflet.js
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
var newMap = L.map(‘map’).setView([52.3188702,0.0108398], 13);
L.tileLayer(‘https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png’, {
maxZoom: 17,
attribution: ‘Map data: © OpenStreetMap contributors, SRTM | Map style: © OpenTopoMap (CC-BY-SA)’
}).addTo(newMap);
$.getJSON(“gavin.geojson”,function(data){
// add GeoJSON layer to the map once the file is loaded
var datalayer = L.geoJson(data ,{
onEachFeature: function(feature, featureLayer) {
featureLayer.bindPopup(feature.properties.NAME_1);
}
}).addTo(newMap);
newMap.fitBounds(datalayer.getBounds());
});
I posted a fix for this issue at the end of the comments.
After adding an external geojson file, how can I add it to a list of layers?
Hi,
I have followed the same steps as shown by you for loading my Geojson file into leaflet ,but unable to do so. It is just showing the basemap (OSM), do i need to add anything in my geojson file.
Below is my code :
Getting Started – Leaflet js Map interactive library
/home/raj.j/Desktop/sony/states/leaflet/leaflet.js
var newMap = L.map(‘map’).setView([23.376535,81.3526765], 5);
L.tileLayer(‘http://{s}.tile.osm.org/{z}/{x}/{y}.png’, {
attribution: ‘© OpenStreetMap contributors’
}).addTo(newMap);
$.getJSON(“states.geojson”,function(data){
// add GeoJSON layer to the map once the file is loaded
var datalayer = L.geoJson(data ,{
onEachFeature: function(feature, featureLayer) {
featureLayer.bindPopup(feature.properties.name);
}
}).addTo(newMap);
newMap.fitBounds(datalayer.getBounds());
});
Any help would be much appreciated please..
Very nice to-the-point tutorial. Thanks.
* IF YOUR BASEMAP IS LOADING BUT YOUR POINTS/POLYGONS/POLYLINES AREN’T *
When using a variable to create an Object from an external GeoJSON file you might have an issue where your basemap loads and your point/line/polygon layer doesn’t. The issue is the use of the variable and there is an easy fix. Here is my code below based on the tutorial:
$.getJSON(“Locations.geojson”,function(data){
// add GeoJSON layer to the map once the file is loaded
var datalayer = L.geoJson(data ,{
onEachFeature: function(feature, featureLayer) {
featureLayer.bindPopup(feature.properties.Name);
}
}).addTo(map);
});
This code will not display my geoJSON layer (Locations.geojson) unless I also include it’s location in the script source section in the HTLM header. Here is an example:
“http://Locations.geojson”
Below is my full, working code:
Map Title
https://unpkg.com/leaflet@1.7.1/dist/leaflet.js
https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
http://Locations.geojson
#map{ height: 100% }
// Set map center and zoom level
var map = L.map(‘map’).setView([39.768, -86.158], 10);
// Define basemap
L.tileLayer(‘https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png’,
{
attribution: ‘© OpenStreetMap contributors © CARTO‘,
subdomains: ‘abcd’,
maxZoom: 17,
minZoom: 11
}).addTo(map);
$.getJSON(“Locations.geojson”,function(data){
// add GeoJSON layer to the map once the file is loaded
var datalayer = L.geoJson(data ,{
onEachFeature: function(feature, featureLayer) {
featureLayer.bindPopup(feature.properties.Name);
}
}).addTo(map);
});
Thanks for the help! I was struggling how to figure how to load the geo file in via a string.