Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

Displaying an encoded Polyline on Google Maps

To draw a line on Google map, we use a polyline. The Polyline class defines a linear overlay of connected line segments on the map. A Polyline object consists of an array of LatLng locations and creates a series of line segments that connect those locations in an ordered sequence.

Encoded Polylines

Polylines in Google Maps are formed as a set of latitude/longitude pairs. Polyline encoding is a lossy compression algorithm that allows you to store a series of coordinates as a single string. The encoding algorithm is described by Google in the docs, but it suffices to say, it is the best way to store and transfer polylines over an API.

This can be useful for a lot of workflows. Over the top of my head, I can think of a couple of areas where encoded polylines can be useful. The most common use case is to include static paths in a Google Map to represent a route or a shape. The encoded polylines required for this could be easily obtained using the Interactive Polyline Encoder Utility.

Another possible place where this could be useful is to store some dynamic directions on the backend or compute directions on the backend that are transmitted to a different API to multiple frontend applications. This is even encouraged by Google and the Node.js Client for Google Maps Services automatically returns an encoded polyline for any directions request made through the API.

Displaying encoded polyline on Maps

The Polyline API doesn't have any method to display an encoded polyline directly on Google Maps. Instead, we need to pass an array of latitude, longitude pairs. But, it's very easy to prepare our encoded polyline for display on Google Maps. Here's a quick function to convert a leg containing encoded polylines to the format that Polyline prefers.

function pathFromLeg(leg) {  
  if (!google) { return; }
  const segments = [];
  _.forEach(leg.steps, ({ polyline: { points } }) => {
    const path = google.maps.geometry.encoding.decodePath(points);
    _.forEach(path, segment => segments.push(segment));
  });
  return segments;
}