decode static method

List<Position> decode(
  1. String polyline, {
  2. int precision = 5,
})

Decodes a Polyline to a List<Position>. This is adapted from the implementation in Project-OSRM. See https://github.com/Project-OSRM/osrm-frontend/blob/master/WebContent/routing/OSRM.RoutingGeometry.js

Implementation

static List<Position> decode(String polyline, {int precision = 5}) {
  var index = 0,
      lat = 0,
      lng = 0,
      shift = 0,
      result = 0,
      factor = math.pow(10, precision);
  int? byte;
  late int latitudeChange;
  late int longitudeChange;
  List<Position> coordinates = [];

  // Coordinates have variable length when encoded, so just keep
  // track of whether we've hit the end of the string. In each
  // loop iteration, a single coordinate is decoded.
  while (index < polyline.length) {
    byte = null;
    shift = 0;
    result = 0;

    do {
      byte = polyline.codeUnitAt(index++) - 63;
      result |= (byte & 0x1f) << shift;
      shift += 5;
    } while (byte >= 0x20);
    latitudeChange = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
    shift = result = 0;

    do {
      byte = polyline.codeUnitAt(index++) - 63;
      result |= (byte & 0x1f) << shift;
      shift += 5;
    } while (byte >= 0x20);
    longitudeChange = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));

    lat += latitudeChange;
    lng += longitudeChange;

    coordinates.add(
      Position.named(
          lng: (lng / factor).toDouble(), lat: (lat / factor).toDouble()),
    );
  }

  return coordinates;
}