I have such problem and I would be nice If somebody can help me. I have points table with GIST index. Those points don\'t change in time.
I would like to fetch point
Assuming you have geometry columns geom
that use a projected SRID of meters in tables road
(LINESTRING) and poi
(POINT), your query to find all POIs within 5 km of road (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 ORDER
part with ST_LineLocatePoint
uses a fraction between 0.0 and 1.0, depending where the point is along the LINESTRING. If the direction of the road is going "the wrong way", then append DESC
to reverse the order. The second ORDER part is based on distance, which could be used if the point is slightly past the start/end of the LINESTRING (where ST_LineLocatePoint
would return 0.0 or 1.0, respectively).
This query might also work if you are using the geography
type with Long/Latitude values, since it automagically calculates metres -- not degrees. Check out docs for more:
ST_Line_Locate_Point
for older versions of PostGIS)It sounds like you could benefit from the KNN-GIST feature from last summer's PostgreSQL 9.1 release and supported by PostGIS version 2.0.
http://blog.opengeo.org/2011/09/28/indexed-nearest-neighbour-search-in-postgis/