0

I'm looking to construct something exactly like this person Building a graph from OSM?

That is I need to construct a graph with intersections as nodes and roads as edges for a simulation. Unlike this user I am doing this in Python and not PostgreSQL.

I assume I am going to need to use the Overpass Python API to get this data but I have never worked with this API before. I am competent enough in Python that as long as I can figure out how to request this data I will be fine.

However, I cant find any intuitive examples on how to retrieve this data in Python.

1

Retrieving data from Overpass API using Python is very simple. Although you can use the Overpass API Python Wrapper, using requests is as easy. All you have to do is create an Overpass query and use requests to get it.

The following snippet shows how to retrieve all cities in Switzerland, read them as JSON and store them in a pandas DataFrame for further processing.

from pandas.io.json import json_normalize
import requests

url = 'http://overpass-api.de/api/interpreter'  # Overpass API URL
query = f"""
[out:json];
area["ISO3166-1"="CH"][admin_level=2];
node ["place"="city"](area);
out;
"""
r = requests.get(url, params={'data': query})
data = r.json()['elements']  # read response as JSON and get the data
df = json_normalize(data)  # create a DataFrame from the data

You can customize your queries to get different type of OSM data in different areas. For example you can specify a Bounding Box and retrieve specific amenties for that area. The following query will retrieve all the fuel stations in the Honolulu area.

query = f"""
    [out:json];
    node ["amenity"="fuel"]
    (21.215460, -157.956619, 21.385951, -157.724533);
    out;
"""
r = requests.get(url, params={'data': query})

Overpass Turbo is a great place to create queries which you can then copy to a python program. Check their query assistant.

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.