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.