Nearest segment on a given position

Hi all. :slight_smile:
I’m planning to use OSM in a geo-application, so I’m starting now to approach to this service. :slight_smile:
What my application need is to know the id and maybe other informations, as the name (not necessarly) of the nearest segment of road to a given gps position, that is a user position. I’ve tried watching the documentation on the wiki and as far as I understand, the only queries avalilables are with a bounding box, that after a few tries gives me some problems: first of all, the dimension of the bbox has to be not too much small, and this imply lots of results…and then it does not gives me only the street segment, and the nodes maybe, but all the representation of the streets in the bbox, including the parts outer the area.
If I have the spatial database locally, the problem could be solved with a NN query , selecting the neighbour with the lower distance from P, but actually the installation of the entire postgres DB locally with the entire planet could not be a good solution both for data updating and server needs…
So, is there any solution in order to achive my task?

Thanks all for the help! :smiley:


Howabout using Spatialite instead of PostGIS? It is only one file which contains both the data and the database. Spatialite seems to have function for calculating distance (
and therefore I suppose that this PostGIS recipe could be used with Spatialite as well (
I played a bit with Spatialite and OSM data about a year ago and I wrote also a short tutorial then. It is still online at

Thaks for the information… :slight_smile:
But as far as I understand I need the database locally in some ways, so the problem of the space occupied by the db is still needed…
But ok, from your reply I suppose there is no way using the osm apis or xapis, or… :frowning:

Database is not necessarily needed it the application can do a bbox query and find nearest neighbor from the downloaded data locally. Perhaps you can find some suitable library which can perform the search of a nearest segment and consider then how to convert the OSM xml data into something that is understood by the library on-the-fly. Many digitising tools have an option “Snap to lines” which is probably internally doing first the spatial query you are interested in.

Well, this could be an interesting solution, I will check around if I can find out something useful to use :slight_smile:

Thanks!!! :wink:

In the meantime, I’ve tried loading a small part of the osm dataset in postgis, and after a the conversion from osm to pgsql I’ve been a bit “disappointed”… I mean: I would have expected to have a table with a list of segments stored in it, and with an empty mutual intersection. Instead there is lots of repetitions of portions of roads, and roads that are few meters from various kilometers long… I’m actually not completely sure of having understand how all of this works… :slight_smile: (talking about planet_osm_line table…)