android - 使用谷歌地图中的折线绘制两点之间的路线的问题

标签 android google-maps polyline direction

我使用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 :

map with direction

看红线。那不是走上路。如何解决这个问题。谢谢

最佳答案

根据the documentation :

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/

相关文章:

android - 如何配置实时开发人员通知以使用我的后端(https 端点)?

ios - 无法让我的位置显示在 iOS 8 的 Google map 中

用于打开 Waze 和 Google map 的 Android Intent

iphone - 通过带有纬度/经度的 URL 在 iPhone 中打开 "Maps"时关闭反向地理编码。范围

ios - Xcode 6 中的 Mapkit 仅在放大时显示日期线以西的叠加层(使用 Swift)

math - 将平行(相似)多段线分组在一起

android - 微调器宽度与微调器项目宽度不匹配

android - 第一个 Android 应用程序使用 GPS 定位和 map ,但电池没电了

java - 在Java中绘制多段线

java - 免费源代码存储库?