Skip to content

13 geopandas

image image image

Adding a GeoPandas GeoDataFrame to the map with a single line of code

Uncomment the following line to install leafmap if needed. You can also use conda to create a new environment to install geopandas and leafmap.

1
2
3
4
5
conda create geo -n python=3.8
conda activate geo
conda install geopandas
conda install mamba -c conda-forge
mamba install leafmap -c conda-forge
1
# !pip install leafmap
1
# !pip install geopandas
1
2
import leafmap
import geopandas as gpd
1
# leafmap.update_package()

Use GeoPandas to read a GeoJSON from an HTTP URL and return it as a GeoDataFrame.

Sample data: https://github.com/opengeos/datasets/releases/download/vector/cables.geojson

1
2
3
gdf = gpd.read_file(
    "https://github.com/opengeos/datasets/releases/download/vector/cables.geojson"
)

Add a GeoDataFrame to the map.

1
2
3
m = leafmap.Map()
m.add_gdf(gdf, layer_name="Cable lines")
m

The following example requires the ipyleaflet plotting backend.

1
import leafmap.leafmap as leafmap  # for ipyleaflet only

Read the GeoPandas sample dataset as a GeoDataFrame.

1
2
3
4
5
path_to_data = (
    "https://github.com/opengeos/datasets/releases/download/vector/nybb.geojson"
)
gdf = gpd.read_file(path_to_data)
gdf

Convert the GeoDataFrame to GeoJSON. Users can then use add_geojson() to add the GeoJSON to the map. Alternatively, users can directly use the add_gdf() function to add a GeoDataFrame to the map. Note you when hovering the mouse over the layer, an information box is shown at the lower right corner of the map. This feature is only available for the ipyleaflet plotting backend.

1
2
geojson = leafmap.gdf_to_geojson(gdf, epsg="4326")
# geojson

One can provide a list of colors (fill_colors) to randomly fill the polygons.

1
2
3
m = leafmap.Map()
m.add_gdf(gdf, layer_name="New York boroughs", fill_colors=["red", "green", "blue"])
m