3

I'd like to :

  1. Select OSM map from a polygon geometry defined by a .geojson file

  2. Extract data (ex : parks area, building height,...) included in the geometry

Any idea?

1
  • 1
    Welcome to GIS SE. As a new user, please take the Tour, which explains how our Focused question/Best answer model operates, and emphasizes the importance of asking One question per Question. Programming questions here are expected to contain code (an initial best effort to solve the task, with a detailed description of what error or undesired outcome is resulting). Please Edit your question.
    – Vince
    May 10, 2021 at 10:52

1 Answer 1

3

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

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