Wednesday 7 July 2010

PostGIS select across the +180/-180 meridian with a bounding box

Many geographical information systems, e.g. PostGIS, treat the earth as a Cartesian plane, despite data being in a geographical coordinate system with latitudes and longitudes. This is annoying when, for example, you want to select geometries that overlap, or are within, a bounding box that crosses the +180/-180 meridian. I have just implemented PostGIS cross +180/-180 meridian bounding box searches in the Entangled Bank as follows :

To select geometries that OVERLAP a box that extends from 90E over the meridian to 90W intersect (&&) the_geom with a pair of boxes either side of the meridian:

the_geom && ST_MakeBox2D(ST_Point(+90, -90), ST_Point(+180, +90))
OR the_geom && ST_MakeBox2D(ST_Point(-180, -90), ST_Point(-90, +90)

Select geometries that are WITHIN the box is slightly more complex as those that intersect the line that bounds the select box must be excluded. In PostGIS using the well-known-text format to code line the query is:

the_geom && ST_MakeBox2D(ST_Point(+90, -90), ST_Point(+180, +90))
OR the_geom && ST_MakeBox2D(ST_Point(-180, -90), ST_Point(-90, +90)
AND NOT the_geom && ST_LineFromText('LINESTRING(+180 +90, +90 +90, +90 -90, 180 -90)')
AND NOT the_geom && ST_LineFromText('LINESTRING(-180 +90, -90 +90, -90 -90, -180 -90)')"

When I have time I shall write the required function.



No comments:

Post a Comment