Android/iOs: 解码折线字符串

Android/iOs: Decode polyline string

我想解码 Android 和 iOS 上的折线字符串 (reference)。

示例:

    _p~iF~ps|U_ulLnnqC_mqNvxq`@

我知道可以使用 google-maps-utils 但是因为我使用的是 Mapbox 我不想在我的项目中有任何 Google 依赖项(此外,我不允许).

Map-box 是否为移动 SDK 提供相同的功能?我看到他们有 JavaScript 的东西,但我想在本地做,以减少来自服务器的 JSON 响应的大小。

或者是我实现自己的解码算法的唯一选择?

public static List<LatLng> decodePolyLines(String poly){
    int len = poly.length();
    int index = 0;
    List<LatLng> decoded = new ArrayList<LatLng>();
    int lat = 0;
    int lng = 0;

    while (index < len){
        int b;
        int shift = 0;
        int result = 0;
        do{
            b = poly.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = poly.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        }while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >>1));
        lng += dlng;

        decoded.add(new LatLng(
                lat / 100000d,
                lng / 100000d
        ));
    }
    return decoded;
}

您可以使用此函数解码折线并创建 LatLng 列表

Mapbox 提供与 Mapbox Android Services 的一部分相同的功能。例如,您可以在没有 Google 依赖项的情况下执行以下操作:

List<Position> path = PolylineUtils.decode(
  "_p~iF~ps|U_ulLnnqC_mqNvxq`@", Constants.GOOGLE_PRECISION);

此外,由于精度是可配置的,您还可以将相同的方法应用于其他编码折线,例如来自 OpenStreetMap 的折线。

更多示例,您可以check the tests