[GIS] How to save a google map direction into a postgresql/postgis database

google mapspostgispostgresql

I have taken a direction(route) from google map.
enter image description here
Can I save this resultant direction/path/route to my postgresql/postgis database? How?

Best Answer

If you don't consider the legal aspect of this here is the solution for your need:

Use the Google Directions API to get the route between your locations. A sample answer for such a directions api request can be seen here:

Google Directions API sample response

The interesting part for you here is the 'overview_polyline' object and its attribute called 'points'. This attribute contains the polyline itself as an encoded string, that you have to decode first in order to proceed. (there are tools and code freely available on the web for doing this) Once you have your polyline decoded, you will probably have an array of coordinate pairs that make up the polyline itself. What you have to do here, is to iterate through this array and form a WKT string from these coordinates. An example for such a string is:

LINESTRING(0 0, 1 1, 2 1, 2 2)

Where the first member of a pair is the longitude and the second is the latitude value fetched from each point of the polyline. Provided you are done with generating your WKT string, you can use ST_GeomFromText somehow like the below:

ST_GeomFromText('your-wkt-here', 4326);

Where 4326 is your EPSG number.

And there you go. If you did everything correctly you finally have the polyline in your database.

Related Question