我想要的是从源到目的地获取地理点,点之间的距离可以是 1 m。我认为多段线也是通过连接源和目标之间的地理点来制作的。我不知道我们能否获得这些地理点数?
最佳答案
事实上,您可以在 Directions API 中获取构成路线的 LatLng 列表。如果您检查 documentation对于响应格式,您会看到每条 route 都有 legs[]
数组,每条腿依次有 steps[]
数组,最后每一步都有 折线
属性。根据文档
polyline contains a single points object that holds an encoded polyline representation of the step. This polyline is an approximate (smoothed) path of the step.
我们的想法是获取响应,将其解析为 JSON 对象,并通过路段和步长为路线创建循环。您应该解码步骤的每个折线属性并将生成的 LatLng 添加到您的列表中。
解码折线有多种选择:
您可以按照 encoded polyline 中描述的算法编写自己的解码函数。文档
您可以使用 Google Maps Android API Utility Library具有用于编码/解码折线的实用函数
最后,您可以使用 Java client library for Google Maps Web services还实现了编码/解码折线算法。
Google map 网络服务的 Java 客户端库可能是实现它的最简单方法。代码 fragment 可能如下所示
//Define list to get all latlng for the route
List<LatLng> path = new ArrayList();
//Execute Directions API request
GeoApiContext context = new GeoApiContext.Builder()
.apiKey("YOUR_API_KEY")
.build();
DirectionsApiRequest req = DirectionsApi.getDirections(context, "41.385064,2.173403", "40.416775,-3.70379");
try {
DirectionsResult res = req.await();
//Loop through legs and steps to get encoded polylines of each step
if (res.routes != null && res.routes.length > 0) {
DirectionsRoute route = res.routes[0];
if (route.legs !=null) {
for(int i=0; i<route.legs.length; i++) {
DirectionsLeg leg = route.legs[i];
if (leg.steps != null) {
for (int j=0; j<leg.steps.length;j++){
DirectionsStep step = leg.steps[j];
if (step.steps != null && step.steps.length >0) {
for (int k=0; k<step.steps.length;k++){
DirectionsStep step1 = step.steps[k];
EncodedPolyline points1 = step1.polyline;
if (points1 != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
for (com.google.maps.model.LatLng coord1 : coords1) {
path.add(new LatLng(coord1.lat, coord1.lng));
}
}
}
} else {
EncodedPolyline points = step.polyline;
if (points != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords = points.decodePath();
for (com.google.maps.model.LatLng coord : coords) {
path.add(new LatLng(coord.lat, coord.lng));
}
}
}
}
}
}
}
}
} catch(Exception ex) {
Log.e(TAG, ex.getLocalizedMessage());
}
//Draw the polyline
if (path.size() > 0) {
PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(5);
mMap.addPolyline(opts);
}
您可以从https://github.com/xomena-so/so47492459 下载完整的示例项目。
不要忘记用您的替换 API key 。
希望对您有所帮助!
关于android - 有没有什么方法可以在 google directions api 中获取从源到目的地的一系列地理点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47758306/