DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Adam Rogers
Adam Rogers

Posted on

GeoJSON, PostGIS and the Right-Hand Rule

GeoJSON expects Polygon and MultiPolygon features are required to be "right-hand wound". I understand this to mean that the order of the coordinates that make up the polygon should move in a specific direction.

Unsurprisingly, exactly which specific direction is somewhat ambiguous. The GeoJSON spec says:

Polygon rings MUST follow the right-hand rule for orientation (counterclockwise external rings, clockwise internal rings).

So, obviously, a simple 12-point Polygon in the shape of a circle and following the right-hand rule starts at, say, noon and the next point will be at, say, position 11 on the clock face.

In my book the primary direction of travel in that case above is, well, left. So "right-hand rule" means "goes left".

So why are my polygons failing on GeoJSONlint.com? I produce my polygons by exporting them from my Postgres database using PostGIS.

PostGIS has a function to force polygons to follow the right-hand rule. The documentation for ST_ForceRHR states:

Forces the orientation of the vertices in a polygon to follow a Right-Hand-Rule, in which the area that is bounded by the polygon is to the right of the boundary. In particular, the exterior ring is orientated in a clockwise direction and the interior rings in a counter-clockwise direction.

So "right-hand rule" in PostGIS-land means... exactly the opposite of the same rule in GeoJSON land. And also matches my intuitive interpretation of "right-hand rule" as applied to polygons.

To create correctly "wound" polygons in GeoJSON when exported from PostGIS, the solution is (obviously) to apply ST_ForcePolygonCCW when exporting polygons as JSON from PostGIS.

References

Top comments (0)

Find what you were looking for? Sign up so you can:

Β 
🌚 Enable dark mode
πŸ”  Change your default font
πŸ“š Adjust your experience level to see more relevant content