public final class PolylineCodec
- Object
- PolylineCodec
Reads and writes the encoded polyline format – the compact ASCII representation of a coordinate sequence that virtually every directions and routing service uses for route geometry (Google Directions, OSRM, Mapbox Directions, GraphHopper, Valhalla, OpenRouteService).
Use it to turn a route geometry straight into something drawable:
map.addPolyline(Polyline.fromEncoded(geometryFromMyDirectionsApi));
The encoding stores each coordinate as a zig-zag, base-64-ish delta from
the previous one at a fixed decimal precision. Precision 5 is the
original Google format and the OSRM/Google/GraphHopper default; precision
6 (polyline6) is what Valhalla and OSRM’s geometries=polyline6 emit.
Decoding with the wrong precision yields coordinates off by a factor of
ten, so pass the precision your service documents.
Methods
public static List decode(String encoded) | Decodes an encoded polyline at the default precision of 5. |
public static List decode(String encoded, int precision) | Decodes an encoded polyline at an explicit decimal precision (5 for the classic format, 6 for polyline6). |
public static String encode(List points) | Encodes LatLng vertices at the default precision of 5. |
public static String encode(List points, int precision) | Encodes LatLng vertices at an explicit decimal precision. |
Inherited methods
Method details
decode
public static List decode(String encoded)Parameters
encodedString- the encoded geometry, may be
null
Returns
decode
public static List decode(String encoded, int precision)Decodes an encoded polyline at an explicit decimal precision (5 for the
classic format, 6 for polyline6).
Trailing bytes that do not form a complete coordinate pair – the usual symptom of a truncated response – are dropped rather than throwing, so a partial geometry still draws the coordinates it did carry. A value cut in half is discarded too: half a delta is not a coordinate, and emitting it would put a spurious vertex on the map and skew the route bounds. Decoding likewise stops at the first character outside the encoding’s alphabet instead of folding it into a coordinate.
Parameters
encodedString- the encoded geometry, may be
null precisionint- the number of decimal digits the encoder scaled by, between 1 and 10
Returns
LatLng vertices, never nullThrows
IllegalArgumentException- when
precisionis outside 1 to 10, which would scale every coordinate into nonsense rather than fail
encode
public static String encode(List points)LatLng vertices at the default precision of 5.Parameters
pointsList- the vertices to encode, may be
null
Returns
null or empty listencode
public static String encode(List points, int precision)LatLng vertices at an explicit decimal precision.Parameters
pointsList- the vertices to encode, may be
null precisionint- the number of decimal digits to scale by, between 1 and 10
Returns
nullThrows
IllegalArgumentException- when
precisionis outside 1 to 10