Assuming you have geom geometry columns that use the projected SRID of counters in the road (LINESTRING) and poi (POINT) tables, your query to find all the POIs within a 5 km radius (where id = 123) should be something like :
SELECT poi.*, ST_Distance(road.geom, poi.geom)/1000.0 AS distance_km FROM road, poi WHERE road.id = 123 AND ST_DWithin(road.geom, poi.geom, 5000.0) ORDER BY ST_LineLocatePoint(road.geom, poi.geom), ST_Distance(road.geom, poi.geom);
The first part of an ORDER with ST_LineLocatePoint uses a fraction between 0.0 and 1.0, depending on where the point is along LINESTRING. If the direction of the road is βwrong,β add DESC to reverse the order. The second part of ORDER is based on the distance, which can be used if the point slightly went beyond the start / end of LINESTRING (where ST_LineLocatePoint will return 0.0 or 1.0, respectively).
This query may also work if you use the geography type with long / latitude values, as it automatically calculates counters, not degrees. Check out the docs for more:
Mike t
source share