# How do I get the points where a line crosses a polygon?

I have a line and need to get a list of coordinates where the line crosses a polygon. A line could cross multiple polygons. A line could also only cross one edge of polygon, if the line starts inside the polygon.

`ST_CROSSES` returns a bool indicating if the line crosses but I need the actual coordinates where the line intersects the polygon edge.

The basic SQL I have doesn't get me points:

``````SELECT trails.oid
FROM trails, areas
WHERE ST_Crosses(trails.geom, areas.geom);
``````
• use ST_AsText postgis.net/docs/manual-1.4/ST_AsText.html (or ST_GeomFromEWKT) gis.stackexchange.com/questions/27349/…
– Mapperz
Nov 25 '15 at 21:09
• I think you want ST_Intersection, but convert the polygon to a line first. Nov 25 '15 at 21:17
• @Mapperz I freely admit that I know almost nothing about postGIS and not much about SQL, but how does ST_GeomFromText help the OP? Nov 25 '15 at 21:19
• corrected postgis.net/docs/manual-1.4/ST_AsText.html example SELECT ST_AsText ('010600000001000000010...'); will return the coordinates "MULTIPOLYGON(((-124.0603704 48.8215791,-124.0599195 48.8218334)"
– Mapperz
Nov 25 '15 at 21:35
• You want ST_Intersection in conjunction with ST_Crosses Nov 26 '15 at 6:26

You need to use ST_Intersection to get the geometries intersection.

But if you intersect a line with a polygon the most probable result will be another line (the piece inside the polygon). So, before using it, you need to transform your polygon geometries in lines. You can use the ST_Boundary() for that.

For lines that intersect the same polygon more than once the intersection will return a Multi-point geometry, you probably want it separated, so you need to use ST_Dump() in the end.

That said, try something like this:

``````SELECT
trails.oid,
(ST_Dump(st_intersection(ST_Boundary(areas.geom),trails.geom))).geom AS points
FROM
areas, trails
WHERE
ST_Intersects(areas.geom,trails.geom);
``````

The final ST_Intersects in the WHERE clause makes sure that you don't try to get the intersection of two geometries that don't even touch, and will avoid you getting empty geometries in the end.

One way this could be achieved would be by running the following script:

``````SELECT (st_dumppoints(st_intersection(areas.geom,trails.geom))).geom AS points
FROM areas, trails
WHERE st_intersects(areas.geom,trails.geom) = true;
``````