geokit/polyline
Google Encoded Polyline algorithm.
Encodes a sequence of LatLng points as a compact ASCII string
using delta encoding, ZigZag transform, base-32 chunking, and a
+ 0x3F ASCII offset. Used by the Google Maps Directions API,
OSRM, Mapbox Directions, and Valhalla.
Specification: https://developers.google.com/maps/documentation/utilities/polylinealgorithmformat.
Types
Errors returned by encode_with, decode,
and decode_with.
pub type PolylineError {
TruncatedInput
InvalidCharacter(char: String, position: Int)
PrecisionOutOfRange(precision: Int)
}
Constructors
-
TruncatedInputThe input string was malformed — typically a continuation byte without a corresponding stop byte (high bit set on the last chunk).
-
InvalidCharacter(char: String, position: Int)A character outside the printable ASCII range used by the encoding appeared in the input.
-
PrecisionOutOfRange(precision: Int)precisionwas outside the supported range[1, 11]. The Google reference encoding uses 5; Valhalla and OSRM use 6. Precisions above 11 overflow the safe integer range on the JavaScript target.
Values
pub fn decode(
input input: String,
) -> Result(List(latlng.LatLng), PolylineError)
Decode a polyline string with the default precision (5).
import geokit/polyline
let assert Ok(points) = polyline.decode("_p~iF~ps|U_ulLnnqC_mqNvxq`@")
// points == [(38.5, -120.2), (40.7, -120.95), (43.252, -126.453)]
pub fn decode_with(
input input: String,
precision precision: Int,
) -> Result(List(latlng.LatLng), PolylineError)
Decode a polyline string with the given precision. Must match the
precision used at encode time. precision must be in [1, 11],
matching encode_with.
pub fn encode(points points: List(latlng.LatLng)) -> String
Encode a list of points using the default precision of 5 (1e-5 degrees, ~1 m at the equator). This matches Google’s original algorithm.
import geokit/polyline
import geokit/latlng
let assert Ok(p1) = latlng.new(lat: 38.5, lng: -120.2)
let assert Ok(p2) = latlng.new(lat: 40.7, lng: -120.95)
let assert Ok(p3) = latlng.new(lat: 43.252, lng: -126.453)
polyline.encode([p1, p2, p3])
// == "_p~iF~ps|U_ulLnnqC_mqNvxq`@"
pub fn encode_with(
points points: List(latlng.LatLng),
precision precision: Int,
) -> Result(String, PolylineError)
Encode a list of points with the given precision (number of
decimal digits to preserve). precision must be in [1, 11];
precision 6 is used by Valhalla and the Open Source Routing
Machine for higher accuracy than the Google default of 5.