Skill - Draw borders from GeoJSON paths in python folium maps
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
- Introduction to Folium for interactive maps in python
Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision
In this post we will learn how to draw GeoJSON paths in folium maps. See this post to learn about folium libary basics
Files used in this example
Place the following files in the same folder of the python file to run this code example
Create map layer with geojson data
import folium
mapObj = folium.Map(location=[22.167057857886153, 82.44140625000001], zoom_start=5)
layer1 = folium.GeoJson(
data=(open("states_india.geojson", 'r').read()),
name="India")
layer1.add_to(mapObj)
mapObj.save('output.html')
You can add multiple GeoJSON layers to a map
Control border and fill style of GeoJSON objects
- use the
style_function
input offolium.GeoJSON
function to control the styling of the paths. style_function
should be a function that returns a dictionary with styling properties specified in the documentation here- Some of the important styling properties are
- color - line stroke color
- weight - line stroke width in pixels
- opacity - line stroke opacity
- fillColor - fill Color
- fillOpacity - ranges between 0 to 1. 0 means transparent, 1 means opaque
import folium
mapObj = folium.Map(location=[22.167057857886153, 82.44140625000001], zoom_start=5)
# style options - https://leafletjs.com/reference-1.7.1.html#path
bordersStyle = {
'color': 'green',
'weight': 2,
'fillColor': 'blue',
'fillOpacity': 0.2
}
folium.GeoJson(
data=(open("states_india.geojson", 'r').read()),
name="India",
style_function=lambda x: bordersStyle).add_to(mapObj)
mapObj.save('output.html')
Complete example
import folium
# initialize a map with center and zoom
mapObj = folium.Map(location=[22.167057857886153, 82.44140625000001],
zoom_start=5)
# https://leafletjs.com/reference-1.7.1.html#path
# border styles dictionary
bordersStyle = {
'color': 'green',
'weight': 2,
'fillColor': 'blue',
'fillOpacity': 0.2
}
folium.GeoJson(
data=(open("states_india.geojson", 'r').read()),
name="India",
style_function=lambda x: bordersStyle).add_to(mapObj)
folium.GeoJson(
data=(open("srilanka.geojson", 'r').read()),
name="Srilanka",
style_function=lambda x: bordersStyle).add_to(mapObj)
# add layer control over the map
folium.LayerControl().add_to(mapObj)
# save the map as html file
mapObj.save('output.html')
Video
The video for this post can be seen here
References
- what is GeoJSON - https://en.wikipedia.org/wiki/GeoJSON
- GeoJSON styling options - https://leafletjs.com/reference-1.7.1.html#path
- official docs - https://python-visualization.github.io/folium/modules.html#folium.features.GeoJson
Comments
Post a Comment