yet another blog about computer, technology, programming, and internet

Tuesday, December 21, 2010

Decoding Polylines from Google Maps Direction API

Tuesday, December 21, 2010 Posted by Ismail Habib , , 63 comments
The Google Maps Directions API provides a way to retrieve directions data from the back-end as opposed to the original JavaScript version when one should retrieve the data from browser. Google provides the routing results as an encoded polylines format. as explained in the Encoded Polyline Algorithm Format. The JavaScript version contains a library for both Encoding and Decoding, which is not the case for a back-end solution written in another language.

Since I'm more interested in the decoding part for Java, here is a code that can be used:

import java.util.ArrayList;

public class PolylineDecoder {
 public static ArrayList decodePoly(String encoded) {
  ArrayList poly = new ArrayList();
  int index = 0, len = encoded.length();
  int lat = 0, lng = 0;
  while (index < len) {
   int b, shift = 0, result = 0;
   do {
    b = encoded.charAt(index++) - 63;
    result |= (b & 0x1f) << shift;
    shift += 5;
   } while (b >= 0x20);
   int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
   lat += dlat;
   shift = 0;
   result = 0;
   do {
    b = encoded.charAt(index++) - 63;
    result |= (b & 0x1f) << shift;
    shift += 5;
   } while (b >= 0x20);
   int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
   lng += dlng;
   Location p = new Location((((double) lat / 1E5)),
     (((double) lng / 1E5)));
   poly.add(p);
  }
  return poly;
 }
}

"Location" is a self-defined, simple class that I use to store coordinate (Latitude and Longitude). Google Map's LatLng is not used because this is for backend.

public class Location implements IsSerializable {

 private double latitude;

 private double longitude;

 public Location() {

 }

 public Location(Double latitude, Double longitude) {
  this.latitude = latitude;
  this.longitude = longitude;
 }
 
 /**
  * @return the latitude
  */
 public double getLatitude() {
  return latitude;
 }

 /**
  * @return the longitude
  */
 public double getLongitude() {
  return longitude;
 }
}

This PolylineEncoder class code is taken from JeffreySambels.com with several modifications.