I am new to PostGIS and need to ask for some help here.
I have a polyline from google maps (representing an itinerary) and need to build a polygon (buffer) around it with a specific distance in meters or kilometers.
For input, I have the list of Latitude/Longitude points and the required buffer distance.
Can anyone help me build the query so that the returned result is the polygon in Latitude/Longitude coordinates, ready to be plotted on the map ?
- Add the first vertex of your line string again at the end to be able
to create a polygon.
- Convert line string to polygon
- Create a buffer around the polygon
SELECT
ST_Buffer(ST_Polygon(ST_AddPoint(the_geom, ST_StartPoint(the_geom))),100)
FROM
mytable
- If you have your buffer in meters/kilometers and your data in latitude/longitude you might want to first transform your polygon into an appropriate projection (I don't know where you are) and then back into latitude/longitude.
SELECT
ST_Transform(ST_Buffer(ST_Transform(ST_Polygon(ST_AddPoint(the_geom,ST_StartPoint(the_geom)),4326),XXXX),100),4326)
FROM
mytable
I haven't tried the code but it should work.
For buffer in meters on lon/lat geometries you can use ST_Buffer
on geography
data type. This approach allows avoid find suitable projection. PostGIS actualy uses UTM zones for this.
For example, geometry(ST_Buffer(georgaphy(geom), 100))
returns 100 meters buffer polygon for geometry geom
.
So, for table with columns seq, lon and lat it looks like:
SELECT geometry(ST_Buffer(georgaphy(ST_MakeLine(ST_MakePoint(lon, lat))), dist))
FROM sometable
ORDER BY seq
This isn't using PostGIS, but there is a RouteBoxer utility in the Google Maps API v3 that does something like what you are asking for.
Another option: the JSTS library.
example
After testing, I found that the polygon buffer produced by postgis is unreliable. That is to say, if I want a 5 kilometre buffer around a polyline, postgis will return a polygon which is AT MOST 5 kilometres, yet at some points less than this.
Abandoning postgis