Created
May 6, 2019 04:15
-
-
Save RanKey1496/bdd651a66e8decbe81a740fd16d32c0a to your computer and use it in GitHub Desktop.
Google polyline decoder written in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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