Suppose we have coordinates of locations, and we need to download closest roads to each of them. Particularly, this problem may be interesting to determine where points are on a road network, and then use graph algorithms, for example shortest path. Also, assigning a Point of Interest (POI) to the nearest road is a common query in Geographic Information Systems.
As a widespread free collaborative mapping solution, OpenStreetMap (OSM) contains various types of roads, from motorways and trunks to service and residential ways. Usually, the tag “highway” is used. All important information is given about roads and streets in OSM can be found here. OSM for the whole planet or specific geographic regions can be downloaded from here; however, it may require substantial storage space and time to process.
To solve the problem, we will use Overpass API, which allow to query OSM data from servers. To process it, we need to install Overpass wrapper which helps us to process API queries in Python.
For the simplicity, let’s just download all roads which are closer than 50 meters to each of the point. Once we have to list of roads, we can easily process them in Python: for example, filter only motorways, or find the closest one etc. We’ll find road IDs, which can be handled later.
Once we have road IDs, we can have access to them using this link. In the next post, I’ll show you how to handle OSM pages like this.
Similar query can request only railroads (key “railway”) or bicycle lanes (key “cycleway”)
from overpass import API from time import sleep from sys import exc_info api = API() locations=[(50.406029,30.619727),(27.988056, 86.925278)] for loc in locations: xx,yy=loc[0],loc[1] try: response = api.Get('way["highway"](around:50,{0},{1});'.format(loc[0],loc[1])) print "For location with coordinates {0}, {1} found way IDs:".format(loc[0],loc[1]) if len(response['elements'])>0: for way in response['elements']: print(way['id']) else: print "No ways" sleep(1) except: print "Got error: {0}".format(exc_info())[0]
[…] it was mentioned in a previous post, we can get OSM way ID’s using Overpass API. Later, we can make a direct query to OSM server […]