I'm locating the nearest point on a line segment with PostGIS and ST_ClosestPoint, I can select the point on each of these line segments which is closest to the starting point. Which looks something like this:

Find nearest point on segment

But! I cannot figure out how to get the second closest point, or the third closest point on a given segment.

What I would like is more like this:

Find multiple points on each segment

I'd like a range of nearby points on the line segments.

Any thoughts about how this might be accomplished?

  • 2
    Can you explain the criteria for nearby points on the line segment is in your second diagram? The nearest point in your first diagram is a perpendicular from each line to the point; in the second digram it's not clear what these points are. – djq Sep 19 '12 at 1:45
  • ah, I didn't mean to make it perpendicular. I've updated the original question. – Matt Sweeney Sep 19 '12 at 5:11
  • 1
    There is an unlimited amount of potential points on a line. Do you want a minimum spacing between the points? – underdark Sep 19 '12 at 7:09
  • @underdark you're correct. maybe a spacing of 1m? or something like that – Matt Sweeney Sep 19 '12 at 17:10

Using ST_DumpPoints() and ORDER BY...LIMIT 3 in your query can get what you want. It might go:

SELECT ST_AsText( (ST_DumpPoints(geom)).geom ) 
FROM  your_line
ORDER BY ST_Distance(SetSrid(MakePoint(your_X,your_Y), SRID),  (ST_DumpPoints(geom)).geom ) ASC LIMIT 3;
| improve this answer | |
  • if a line segment is defined by two points i.e. LINESTRING ( 0 3, 3 4 ) will this return just the end points? – Matt Sweeney Sep 19 '12 at 17:14
  • 1
    Try it: SELECT ST_AsText( (ST_DumpPoints(geom)).geom ) FROM LineStringFromText('LINESTRING(0 3,3 4)',4326) AS geom ORDER BY ST_Distance(SetSrid(MakePoint(2,2), 4326), (ST_DumpPoints(geom)).geom ) ASC LIMIT 3; returns: POINT(3 3) POINT(3 4) – Micha Sep 20 '12 at 5:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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