How do I decode an "encoded polyline" from Mapbox on iOS
Asked Answered
D

1

1

I have an encoded polyline created by the Mapbox javascript API (https://github.com/mapbox/polyline) and I would like to decode this polyline into a list of coordinates (or even just an MGLShape) on the iOS app.

I attempted to decode directly to an MGLShape (note: this is totally wrong as I got mixed up with the encoded polyline and GeoJSON, which is what the MGLShape(data:) is looking for.)

if let shapeData = "_nwfFteckVd@rIvEhEaB~Ht@lIxD~EvE~DfB|HdCeHrBwHnGT|ExDbGzAjGAyC{GjG[fGbA~@iICuIjG@lFqCrBpHj@lIaClHmGOiEbFVvIkCdHgEdFkGImGQoFbDgGgAmGl@iG_@}F_CmCgHZuI`@wIy@oIk@oI|BkH}EgE}BmH".data(using: .utf8) {
  MGLPolyline
  let shape = try? MGLShape(data: shapeData, encoding: String.Encoding.utf8.rawValue)
  let shapeSource = MGLShapeSource(identifier: "polyLineSource", shape: shape, options: nil)
}

But shape comes out nil.

I didn't see any way with the Mapbox API to decode this polyline in coordinates easily.

Drupe answered 23/9, 2021 at 0:58 Comment(0)
D
0

It turns out the encoded polyline from the Mapbox SDK is actually encoded via a Google algorithm, which fortunately you can access an Interactive Encoder Utility website and see if an encoded polyline looks right.

Once I found out it was the same kind of encoded polyline (and nothing to do with GeoJSON), I found this Swift polyline encoder/decoder library that worked great for my needs.

// Using the swift polyline library, I can get the coordinates from the polyline and continue making my overlay normally
let coordinates = Polyline(encodedPolyline: encodedPolyline).coordinates
Drupe answered 23/9, 2021 at 0:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.