I'd like to :
Select OSM map from a polygon geometry defined by a .geojson file
Extract data (ex : parks area, building height,...) included in the geometry
Any idea?
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.
Sign up to join this communityI'd like to :
Select OSM map from a polygon geometry defined by a .geojson file
Extract data (ex : parks area, building height,...) included in the geometry
Any idea?
You can use Geopandas to read the geojson:
import geopandas as gpd
boundary_geojson = gpd.read_file('C:/yourfile.geojson')
print(bounding_geojson.head())
You can use OSMnx (https://github.com/gboeing/osmnx) to retrieve OSM data based on a polygon:
import osmnx as ox
ox.geometries.geometries_from_polygon(boundary_geojson, tags = {‘building’: True})
If the retrieve by polygon function of OSMnx doesn't work for you (or if OSMnx wont take a geojson geodataframe as a bounding polygon) you could instead retrieve the data based on a radius around a point within your polygon. Just give the coordinates of a point roughly in the middle of your geojson polygon and a sensible radius in metres around the point that you know will include all of the necessary data you will need (below example is for buildings data):
import osmnx as ox
import ast
point = 'point coordinates e.g 51.93802486000275, 4.361977332600682'
dist = 'distance in m e.g 2000'
buildings = ox.geometries.geometries_from_point(point, {'building': True}, dist=dist)
And convert to a geodataframe:
buildings_save = buildings.applymap(lambda x: str(x) if isinstance(x, list) else x)
Then clip the buildings data to your boundary geojson file using geopandas:
buildings_final = gpd.clip(buildings_save, boundary_geojson)
Plot the data to check if you want:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize = (15,12))
buildings_final.plot(ax = ax, color = 'red', edgecolor = 'black',)
plt.title('Buildings Data')
plt.show()
Save the files to geojson or shapefile if you want:
buildings_final.to_file("C:/output.geojson", driver="GeoJSON")
buildings_final.to_file("C:/output.shp")
This retrieve data by point method is a bit clunky but works. For more info about retrieving OSM data based on geometries check out https://osmnx.readthedocs.io/en/stable/osmnx.html#module-osmnx.geometries