Wednesday, 13 March 2019

proximity - Finding closest segment to a point using PostGIS


I am trying to find the closest road segment to a point that I have and return an attribute from the closest segment to the given points.


I know in PostGIS I need to use ST_ClosestPoint, St_distance and min functions, but I keep having syntax errors.


So far my code looks like


WITH closest_segment As
)
SELECT
ST_ClosestPoint(ST_GeogFromText('POINT(-122.206111 47.983056)')::GEOMETRY,

shape::GEOMETRY)AS segment_location --shape is the geography WKB

FROM
public.road_segments
)
RETURNING closest_segment
WITH new_segment AS
)
SELECT
MiN(ST_Distance(closest_segment::GEOM,ST_GeogFromText('POINT(-122.206111

47.983056)')::GEOMETRY)
FROM
closest_segment
)
RETURNING closest_segment

My knowledge of PostGIS and coding in it is very limited.



Answer



Assuming that road_segments table have geographies written in geog column you can try this query:


SELECT

geog,
dist
FROM
(SELECT
rs.geog,
ST_Distance(rs.geog, ST_GeogFromText('POINT(-122.206111 47.983056)'), false) AS dist
FROM
public.road_segments AS rs) AS roads_with_distances
ORDER BY
dist

LIMIT 1;

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...