This is a static archive of our old OpenStreetMap Help Site. Please post any new questions and answers at community.osm.org.

How to get the administrative region (admin_level=4) a place belongs to?

0

I'm using PyOsmium. Given a node on OpenStreetMap, for example a village or a city like Chicago, how should I derive information such as the admin_level=4 region it is located in (in this case Illinois), and the country it belongs to (the USA)? In addition to it, I would also like to derive information on the country (in this example, the USA).

This probably involves using refs and relations, but I don't quite know what strategy I should use to get this information (as efficiently as possible). Can you help?

asked 27 Jul '21, 12:40

fsaler's gravatar image

fsaler
16335
accept rate: 0%


One Answer:

1

You will save yourself a lot of trouble if you can afford to run a local "Nominatim" installation and then simply use Nominatim's reverse geocoding ability. Alternatively, try "Photon" for the same purpose; there are ready-to-go Photon data dumps available for download, obviating the need for a database and an import process.

Otherwise, the likely easiest path is to pre-filter a planet file with the command-line osmium utility (only keep stuff tagged boundary=administrative and with an admin_level of interest to you), then load the entirety of that file into Pyosmium, construct geometries, use the Pyosmium/Shapely interoperability to stuff the geometries into a Shapely R-Tree. Once that is done, you can efficiently query which administrative bounding boxes a point is in; if this yields more than one result (eg half the points in New Mexico are also in the Texas bounding box), you need to do proper (and more costly) point-in-polygon checks for the resulting polygons but that is also easy with Shapely.

A third option is to do essentially what I wrote above but employ a PostGIS database to do it, i.e. load admin boundaries into PostGIS with osm2pgsql, then run SQL queries to find which polygons a point is in.

answered 27 Jul '21, 13:09

Frederik%20Ramm's gravatar image

Frederik Ramm ♦
82.5k927201273
accept rate: 23%

edited 27 Jul '21, 17:18

alester's gravatar image

alester
6.6k266100

I'm going to try the Photon route, it sounds smartest. Where can I find the data dumps you mention? I need one for the whole planet, but I don't need data on ways or most kinds of features, only inhabited places (hamlet or bigger).

(26 Aug '21, 09:54) fsaler

Source code available on GitHub .