I have a shapefile that has many polygons, here is an example: enter image description here

Now, what I want to do is show the polygons that are around one particular location. So I don't have to show all the polygons.

So I began to try something, like creating a circle (we can also do with a rectangle), and try to limit/cut the polygons, or at least, find the only polygons in the circle.

import folium
import geopandas as gpd
from shapely.geometry import Point
center_location = (48.8566, 2.3522)
m = folium.Map(location=center_location, zoom_start=12)
circle_radius = 5000
center_point = Point(center_location)
circle = center_point.buffer(circle_radius)
polygons_in_circle = gdf[gdf.geometry.intersects(circle)]

Could you please help me?

  • Depending on what you need, you can also filter already when reading the file using the bbox parameter: df = geopandas.read_file("nybb.shp", bbox=(0, 0, 10, 20)). If your file has a spatial index this will also be relatively fast.
    – Pieter
    Commented Aug 24, 2023 at 18:15
  • What should I do when someone answers my question?
    – Bera
    Commented Sep 3, 2023 at 15:44

1 Answer 1

import geopandas as gpd

df = gpd.read_file(r"C:\GIS\data\testdata\zy_riks_4326.shp")
center = (64.77626, 14.51378)

#Reproject the df to a projected crs with units in meters, so the units make sense. Or the radius will be in degrees
df = df.to_crs(3006) #Im in Sweden so I pick 3006. You should choose another local one.

#Select by a rectangle
xmin, xmax, ymin, ymax = 465000,490000,7170000,7200000
rectframe = df.cx[xmin:xmax, ymin:ymax]

#Select by a circle
radius = 10000
circle = gpd.GeoDataFrame(geometry=gpd.points_from_xy(x=[center[1]], y=center[0]), crs=4326).to_crs(3006)
circle.geometry= circle.geometry.buffer(radius)
circleframe = gpd.sjoin(df, circle, how="inner") #If you want to clip by the circle you can use gpd.overlay

base = df.plot(color="gray")
rectframe.plot(ax=base, color="red")
circleframe.plot(ax=base, color="blue")

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.