Name

ST_AsEncodedPolyline — Returns an Encoded Polyline from a LineString geometry.

Synopsis

text ST_AsEncodedPolyline(geometry geom, integer precision=5);

Description

Returns the geometry in the Encoded Polyline Algorithm Format. The format stores latitude and longitude deltas as integers after multiplying coordinates by 10 raised to the requested precision.

The informal names polyline5 and polyline6 refer to the same encoding with precision 5 and 6. The precision must match when encoding and decoding; otherwise the coordinates are scaled incorrectly.

The input geometry must use SRID 4326, with longitude as X and latitude as Y. Use ST_Transform to transform geometries in other coordinate systems before encoding.

The OSRM API returns precision 5 for geometries=polyline and precision 6 for geometries=polyline6. Decode the resulting route.geometry with ST_LineFromEncodedPolyline using the matching precision.

Availability: 2.2.0

Examples

Encode the same WGS 84 LineString using precision 5 and 6.

Code
WITH route AS (
  SELECT ST_GeomFromEWKT(
    'SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)'
  ) AS geom
)
SELECT ST_AsEncodedPolyline(geom, 5) AS polyline5,
       ST_AsEncodedPolyline(geom, 6) AS polyline6
FROM route;
Output
          polyline5          |            polyline6
-----------------------------+----------------------------------
 _p~iF~ps|U_ulLnnqC_mqNvxq`@ | _izlhA~rlgdF_{geC~ywl@_kwzCn`{nI

Decode an OSRM route.geometry returned with geometries=polyline6.

Code
SELECT ST_AsEWKT(ST_LineFromEncodedPolyline(
  '_izlhA~rlgdF_{geC~ywl@_kwzCn`{nI',
  6
)) AS route;
Output
SRID=4326;LINESTRING(-120.2 38.5,-120.95 40.7,-126.453 43.252)
Figure
Geometry figure for visual-st-asencodedpolyline-02

The Google Maps JavaScript Geometry library decodes precision-5 strings. This browser example assumes that map is an initialized Google map.

Code
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry"></script>
<script>
  const encodedPath = "_p~iF~ps|U_ulLnnqC_mqNvxq`@";
  const flightPath = new google.maps.Polyline({
    path: google.maps.geometry.encoding.decodePath(encodedPath),
    map: map,
    strokeColor: "#0000CC",
    strokeOpacity: 1.0,
    strokeWeight: 4
  });
</script>