# Find nearest vector to point

Is there any better way how to find vector nearest to point then this:

``````select gid,ST_Distance(ST_GeomFromText('POINT(\$x \$y)',4326),cr_2po_4pgr.the_geom)
as d from cr_2po_4pgr order by d limit 1
``````

Sometime i have feeling that this is looking for nearest start/end point and not vector itself.

• I suppose it depends on what your requirements are. I suspect that ST_Distance does determine distance by finding the nearest point (see illustrations in ST_ClosestPoint). If you'd rather define the "nearest" feature as that for which all points on the feature are closer than the closest point of any other feature, your situation is complicated. You could try using ST_DWithin or defining a tolerance, buffering your features, and checking for containment. – Arthur Sep 13 '13 at 15:01
• It is simple, i have a gps point and i want to find road nearest to that point. – Matus Sep 13 '13 at 15:17

With PostGIS 2.0+, assuming you have built a spatial index and are using the geometry type:

``````WITH roads_maybe AS (
SELECT * FROM roads
ORDER BY geom <-> ST_SetSRID(ST_MakePoint(\$x, \$y), \$srid)
LIMIT 50
)
SELECT * FROM roads_maybe
ORDER BY ST_Distance(geom, ST_SetSRID(ST_MakePoint(\$x, \$y), \$srid))
LIMIT 1;
``````

The first clause does an index-assisted ordering to get a set of candidate nearest segments, and the second pulls the actually nearest segment from that collection.

Use select by location that can be helpful for you to specify distances, unless you really wanna do it using python.