decodePolyline static method

List<LatLng> decodePolyline(
  1. String polyline
)

Decodes a polyline string into a list of LatLng.

This method takes a Google Maps polyline string and decodes it into a list of LatLng coordinates. The coordinates represent the path defined by the polyline.

Implementation

static List<LatLng> decodePolyline(String polyline) {
  List<LatLng> points = []; // List to hold the decoded coordinates
  int index = 0, len = polyline.length; // Initialize index and length of the polyline
  int lat = 0, lng = 0; // Variables to hold latitude and longitude

  // While there are still characters to process in the polyline
  while (index < len) {
    int b, shift = 0, result = 0;

    // Decode latitude
    do {
      b = polyline.codeUnitAt(index++) - 63; // Get the next character
      result |= (b & 0x1F) << shift; // Update the result
      shift += 5; // Increase the shift
    } while (b >= 0x20); // Continue until a character less than 0x20 is found

    int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); // Decode the latitude delta
    lat += dlat; // Update the latitude

    shift = 0; // Reset shift for longitude decoding
    result = 0; // Reset result for longitude decoding

    // Decode longitude
    do {
      b = polyline.codeUnitAt(index++) - 63; // Get the next character
      result |= (b & 0x1F) << shift; // Update the result
      shift += 5; // Increase the shift
    } while (b >= 0x20); // Continue until a character less than 0x20 is found

    int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); // Decode the longitude delta
    lng += dlng; // Update the longitude

    // Add the new LatLng point to the list of points
    points.add(LatLng(lat / 1E5, lng / 1E5));
  }

  return points; // Return the list of decoded LatLng points
}