我使用SupportMapFragment来显示谷歌地图。我在两个位置之间使用Direction API两条路线。我解析使用GSON库从Direction API返回的JSON数据,并提取显示每个路由的步骤标记。然后我用折线绘制它。但是我的路线在路上并不匹配,大部分是直线。
此代码是我提取的谷歌返回的JSON方向:
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数据并将其传递给片段以绘制它:
@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);
}
这是我的地图:
看看红线。那不是上路。如何解决这个问题。感谢
答案 0 :(得分:2)
legs
数组中的每个元素都指定了计算路线中从起点到目的地的单程旅程。对于不包含航路点的路线,路线将由一条腿组成,&#34;但是对于定义一个或多个航点的航线,航线将由一条或多条航线组成,对应于旅程的特定航段。
因此,您无法使用legs
数组获得路线的良好表示。
为了更好地表示路线,您可以使用字段overview_polyline
。来自the documentation:
overview_polyline
包含一个单点对象,该对象包含路由的encoded polyline表示。此折线是生成方向的近似(平滑)路径。
要对此overview_polyline
进行解码,您可以使用Google Maps Android API Utility Library中的PolyUtil.decode
方法。
答案 1 :(得分:1)
步骤是路线指示。您必须解析overview_polyline
对象并获取编码的折线字符串。然后使用android-maps-utils库解码字符串:
List<LatLng> decodedPoints = PolyUtil.decode(polylineString);
PolylineOptions options = new PolylineOptions();
options.width(3);
options.color(Color.RED);
options.addAll(decodedPoints);
map.addPolyline(options);
答案 2 :(得分:0)
Xamarin版本:
List<LatLng> coordsList = new List<LatLng>();
foreach (var step in leg.steps)
{
var points = PolyUtil.Decode(step.polyline.points);
foreach (var point in points)
{
coordsList.Add(point);
}
}
答案 3 :(得分:0)
答案正在使用Google Direction API的json响应的“ overview_polyline”。
我遇到了同样的问题,需要在Xamarin Forms中实施,经过两天的工作终于解决了这个问题。
'overview_polyline'需要被解码并获得位置列表。
List<Position>
然后使用位置列表绘制折线。
博客: https://www.xamboy.com/2019/05/17/exploring-map-tracking-ui-in-xamarin-forms/ GitHub的: https://github.com/rdelrosario/MapTrackingSample
从Github下载示例项目,然后执行以下步骤:
要解码“ overview_polyline”,请使用上述项目中的PolylineHelper.cs类,它将返回位置列表。使用位置列表在叠加层中绘制多段线。
//calling the method from helper class and pass the 'overview_polyline'
Route _route;
var positions=(Enumerable.ToList(PolylineHelper.Decode(_route.overview_polyline.points)));
//Drawing the Polylines
foreach (var _step in positions)
{
polyline.Positions.Add(new Position(_step.Latitude, _step.Longitude));
}
//Adding the drawn polylines to the overlay of the map
polyline.StrokeColor = Color.Blue;
polyline.StrokeWidth = 5f;
map.Polylines.Add(polyline);
PS:这是Xamarin Forms中上述问题的实现,应该归功于博客的作者。
快乐编码!