0

Sorry if this there is a really obvious solution to this question. I did not have any luck googling and looking at different books.

I have an OSM vector layer that I want to clip with another vector layer for the boundary of a city. Now I can do this easy enough in QGIS, but I wanted to do this in python since I have a collection of images to process and clip.

I imagined that clipping is such a common operation, that there must be clip functions in the major geospatial packages, but I have not been able to find anything like that so far. I was kinda surprised, or was wondering if I was looking under the wrong headings, terminology?

There are a few posts on this topic listed below.

Clipping raster with vector layer using GDAL

Clipping shapefile with Python?

"Clip" hole into Shapefile

Now the first post is about 7 years old, and the later ones are a couple of years old.

Is the best way to do this to use something like geopandas and to then keep all geometries that intersect with the city polygon? But then how do I crop OSM polygons that are not completely contained within the city polygon boundary. I would like to keep partial polygons.

Is the code in the links above still valid, or are there better ways to do this now?

1

it is indeed weird that there is nothing like that implemented in Geopandas or shapely. I got the same problem that I wanted to crop images that overlap with the boundary polygon.

This code does what you are looking for:

os.system("ogr2ogr -f GeoJSON -clipsrc boundary.geojson datatobeclipped.geojson")
  • 1
    Oh thanks for the insight. Yeah, seems like there would be a smoother way to do this than resorting to passing to the shell, but this is great for now. Thanks again for your help. – krishnab Jul 17 at 7:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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