Skip to content

Instantly share code, notes, and snippets.

@RanKey1496
Created May 6, 2019 04:15
Show Gist options
  • Save RanKey1496/bdd651a66e8decbe81a740fd16d32c0a to your computer and use it in GitHub Desktop.
Save RanKey1496/bdd651a66e8decbe81a740fd16d32c0a to your computer and use it in GitHub Desktop.
Google polyline decoder written in Java
import org.locationtech.jts.geom.*;
public class Utils {
private static final double DEFAULT_PRECISION = 1E5;
public static LineString decodePolyline(String encoded) {
return decodePolyline(encoded, DEFAULT_PRECISION);
}
private static LineString decodePolyline(String encoded, double precision) {
List<Coordinate> coordinates = new ArrayList<>();
int index = 0;
int lat = 0, lng = 0;
while (index < encoded.length()) {
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;
coordinates.add(new Coordinate(lng / precision, lat / precision));
}
LineString lineString = new GeometryFactory(new PrecisionModel(), 4326)
.createLineString(coordinates.toArray(new Coordinate[coordinates.size()]));
return lineString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment