【问题标题】:Android/iOs: Decode polyline stringAndroid/iOS:解码折线字符串
【发布时间】:2017-02-12 13:22:27
【问题描述】:
我想在 Android 和 iOS 上解码折线字符串 (reference)。
例子:
_p~iF~ps|U_ulLnnqC_mqNvxq`@
我知道可以使用google-maps-utils,但由于我使用的是 Mapbox,我不希望我的项目中有任何 Google 依赖项(此外,我不允许这样做)。
Map-box 是否为移动 SDK 提供相同的功能?我看到他们为JavaScript 提供了一些东西,但我想在本地进行,以减少来自服务器的JSON 响应的大小。
或者是我实现自己的解码算法的唯一选择?
【问题讨论】:
标签:
android
ios
mapbox
polyline
【解决方案1】:
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 列表
【解决方案2】:
Mapbox 提供与Mapbox Android Services 的一部分相同的功能。例如,您可以在不依赖 Google 的情况下执行以下操作:
List<Position> path = PolylineUtils.decode(
"_p~iF~ps|U_ulLnnqC_mqNvxq`@", Constants.GOOGLE_PRECISION);
此外,由于精度是可配置的,您还可以将相同的方法应用于其他编码的折线,例如来自 OpenStreetMap 的折线。
更多示例,您可以check the tests。