Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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.

share|improve this question
1  
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
add comment

2 Answers

up vote 0 down vote accepted

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.