Search code examples
pythongisopenstreetmaposmnx

python osmnx - How to download a city district map from OpenStreetMap based on the boundary ID?


osmnx is a Python tool that allows you to download maps from OpenStreetMap and work with them as Networkx graphs. I could, for example get the the street map of a LA using the following command:

osmnx.graph_from_place('Los Angeles, CA, USA', network_type='drive')

Now I am trying to download a district within Tehran, Iran. Using the name 'Tehran, Iran' didn't help much and the result is wrong. However, the city boundary has an OSM ID of 8775292 as found in the link below:

https://www.openstreetmap.org/relation/8775292

So, is there a way to give OSMNx the boundary ID instead of giving it the name for query?

Thanks!


Solution

  • Per the OSMnx documentation you can provide your place query as either a string or a dict. See the usage examples for demonstrations of each. Using a dict seems to work fine in returning the city boundaries you're looking for:

    import osmnx as ox
    ox.config(use_cache=True, log_console=True)
    
    # define the place query
    query = {'city': 'Tehran'}
    
    # get the boundaries of the place
    gdf = ox.geocode_to_gdf(query)
    gdf.plot()
    
    # or just get the street network within the place
    G = ox.graph_from_place(query, network_type='drive')
    fig, ax = ox.plot_graph(G, edge_linewidth=0)
    

    It also works fine if you query a more specific string in Persian or English:

    # query in persian
    gdf = ox.geocode_to_gdf('شهر تهران')
    gdf.plot()
    
    # or in english
    gdf = ox.geocode_to_gdf('Tehran City')
    gdf.plot()
    

    is there a way to give OSMNx the boundary ID instead of giving it the name for query

    No, OSMnx retrieves boundary polygons by querying the Nominatim geocoder.