Skip to content

Instantly share code, notes, and snippets.

@RanKey1496
Created May 6, 2019 04:14
Show Gist options
  • Save RanKey1496/776fab5642c0f5faba26a781636a2d08 to your computer and use it in GitHub Desktop.
Save RanKey1496/776fab5642c0f5faba26a781636a2d08 to your computer and use it in GitHub Desktop.
Google Polyline encoder written in Java
public class Utils {
private static final double DEFAULT_PRECISION = 1E5;
private static String encodeDiff(int diff) {
StringBuilder str = new StringBuilder();
int shifted = diff << 1;
if (diff < 0) {
shifted = ~shifted;
}
int rem = shifted;
while (rem >= 0x20) {
str.append((char) ((0x20 | (rem & 0x1f)) + 63));
rem >>= 5;
}
str.append((char) (rem + 63));
return str.toString();
}
public static String encodePolyline(LineString encoded) {
StringBuilder str = new StringBuilder();
int lastLat = 0;
int lastLng = 0;
for (Coordinate coor : encoded.getCoordinates()) {
int lat = (int) Math.round(coor.getY() * 1E5);
int lng = (int) Math.round(coor.getX() * 1E5);
str.append(encodeDiff(lat - lastLat));
str.append(encodeDiff(lng - lastLng));
lastLat = lat;
lastLng = lng;
}
return str.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment