13 geopandas
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.
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
# !pip install leafmap
# !pip install geopandas
import leafmap
import geopandas as gpd
# 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/leafmap/raw/master/examples/data/cable_geo.geojson
gdf = gpd.read_file(
"https://github.com/opengeos/leafmap/raw/master/examples/data/cable_geo.geojson"
)
Skipping field coordinates: unsupported OGR type: 3
Add a GeoDataFrame to the map.
m = leafmap.Map()
m.add_gdf(gdf, layer_name="Cable lines")
m
The following example requires the ipyleaflet plotting backend.
import leafmap.leafmap as leafmap # for ipyleaflet only
Read the GeoPandas sample dataset as a GeoDataFrame.
path_to_data = (
"https://github.com/opengeos/datasets/releases/download/vector/nybb.geojson"
)
gdf = gpd.read_file(path_to_data)
gdf
BoroCode | BoroName | Shape_Leng | Shape_Area | geometry | |
---|---|---|---|---|---|
0 | 5 | Staten Island | 330470.010332 | 1.623820e+09 | MULTIPOLYGON (((970217.022 145643.332, 970227.... |
1 | 4 | Queens | 896344.047763 | 3.045213e+09 | MULTIPOLYGON (((1029606.077 156073.814, 102957... |
2 | 3 | Brooklyn | 741080.523166 | 1.937479e+09 | MULTIPOLYGON (((1021176.479 151374.797, 102100... |
3 | 1 | Manhattan | 359299.096471 | 6.364715e+08 | MULTIPOLYGON (((981219.056 188655.316, 980940.... |
4 | 2 | Bronx | 464392.991824 | 1.186925e+09 | MULTIPOLYGON (((1012821.806 229228.265, 101278... |
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.
geojson = leafmap.gdf_to_geojson(gdf, epsg="4326")
# geojson
One can provide a list of colors (fill_colors
) to randomly fill the polygons.
m = leafmap.Map()
m.add_gdf(gdf, layer_name="New York boroughs", fill_colors=["red", "green", "blue"])
m