我使用SupportMapFragment来显示谷歌地图。我在两个位置之间使用 Direction API 两条路线。我使用 GSON 库解析从 Direction API 返回的 JSON 数据,并提取显示每条路线的步骤标记。然后我用折线来绘制它。但我的路线与道路不匹配,而且大多是直线。
这段代码是我从谷歌返回的 JSON Direction 中提取的:
GoogleDirectionResponse data = (GoogleDirectionResponse) response;
if (data.getStatus().matches("OK")){
List<LatLng> steps = new ArrayList<>();
RoutesData routesData = data.getRoutes().get(0);
LegData legData = routesData.getLegs().get(0);
for (StepsData item : legData.getSteps()){
LatLng start = new LatLng(item.getStart_location().getLat(), item.getStart_location().getLng());
LatLng end = new LatLng(item.getEnd_location().getLat(), item.getEnd_location().getLng());
steps.add(start);
steps.add(end);
}
onDirectionFetchedListener.onDirectionFetched(steps);
}
我将 LatLng 数据保存在数组中并将其传递给 fragment 以绘制它:
@Override
public void onDirectionFetched(List<LatLng> steps) {
PolylineOptions rectLine = new PolylineOptions().width(3).color(
Color.RED);
for (LatLng item : steps) {
rectLine.add(item);
}
Polyline polylin = map.addPolyline(rectLine);
}
这是我的 map :
看红线。那不是走上路。如何解决这个问题。谢谢
最佳答案
Each element in the
legs
array specifies a single leg of the journey from the origin to the destination in the calculated route. For routes that contain no waypoints, the route will consist of a single "leg," but for routes that define one or more waypoints, the route will consist of one or more legs, corresponding to the specific legs of the journey.
因此,使用 legs
数组无法很好地表示路线。
要获得路线的良好表示,您可以使用字段overview_polyline
。来自 the documentation :
overview_polyline
contains a single points object that holds an encoded polyline representation of the route. This polyline is an approximate (smoothed) path of the resulting directions.
要解码此overview_polyline
,您可以使用Google Maps Android API Utility Library中的PolyUtil.decode
方法。 。
关于android - 使用谷歌地图中的折线绘制两点之间的路线的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38093424/