PostGIS - Buffer a Polygon
Needed to buffer a polygon (rectangle) that was listed in lat/lng (4326) projection to world mercator (3857) by a defined limit 10KM. Problem is that 4326 is expecting decimal degrees 3857 is expecting meters. However PostGIS understands both and has functions to convert between the two.
In this case I have the following coordinates that define the bounding box
(-179,1) (-179,65) (-103,65) (-103,1)
Remember that PostGIS expects that the coordinates are listed as (longitude, latitude) when using WKT as the input format.
select st_astext(ST_Transform(st_expand(ST_Transform(ST_MakePolygon(ST_GeomFromText('LINESTRING(-179 1,-179 65 ,-103 65 ,-103 1 , -179 1)', 4326)), 3857), 10000), 4326));
Here I add the first point again at the end to make sure the polygon is closed.
- Create the geometry from the points (as a linestring) with SRID of 4326
- Turn the geometry into a Polygon
- Transform the polygon from 4326 to 3857
- Expand the polygon by 10000 meters (using the unit of reference of the projection)
- Transform the polygon back to 4326
- Print out the polygon as WKT
The results will look like this
POLYGON((-179.089831528412 0.910180961305166,-179.089831528412 65.0379374814058,-102.910168471588 65.0379374814058,-102.910168471588 0.910180961305166,-179.089831528412 0.910180961305166))