Interactive representation of a geospatial raster with Python, Folium and Rasterio - Tutorial
/Sometimes we want to reproduce or want to get something similar to a desktop GIS environment on a Jupyter notebook with options to show/hide layers and select background maps, but there was a missing part on our effort and it was the raster representation.
We have developed an applied case of single band raster representation on a Jupyter notebook with Rasterio and Folium. The raster has to be in WGS84 and the script can be coupled with more Folium features for the representation of vector data, background maps, menus and popups.
Tutorial
Code
#from osgeo import gdal
import matplotlib.pyplot as plt
import numpy as np
import rasterio
import folium
# representation of the generated raster
elevRaster = rasterio.open('elevationClipped.tif')
elevArray = elevRaster.read(1)
boundList = [x for x in elevRaster.bounds]
boundList
[-98.13583333333341, 32.65666666666657, -96.40250000000015, 33.967499999999845]
#get rid of the nan for color interpretation
elevArray = np.nan_to_num(elevArray)
plt.imshow(elevArray)
<matplotlib.image.AxesImage at 0x25bf90c4c10>
rasLon = (boundList[3] + boundList[1])/2
rasLat = (boundList[2] + boundList[0])/2
mapCenter = [rasLon, rasLat]
# Create a Folium map centered at a specific location
m = folium.Map(location=mapCenter, zoom_start=9)
# Add raster overlay
image = folium.raster_layers.ImageOverlay(
image=elevArray,
bounds=[[boundList[1], boundList[0]], [boundList[3], boundList[2]]],
opacity=0.6,
interactive=True,
cross_origin=False,
)
image.add_to(m)
# Add layer control
folium.LayerControl().add_to(m)
# Display the map
m
Input data
You can download the input data from this link.