【问题标题】:How to draw a dynamic line (route) with Google Maps Android API v2如何使用 Google Maps Android API v2 绘制动态线(路线)
【发布时间】:2012-12-05 16:26:44
【问题描述】:

我想知道使用 Google Maps API v2 在地图上绘制动态路线的最佳做法是什么。我想要一张能够在用户移动时延长路线的地图。使用折线和折线选项似乎有明显的解决方案。但我只是找不到一种简单的方法来添加点之后我实例化折线。绘制折线是这样的:

PolylineOptions polylineOptions = new PolylineOptions();
polylineOptions.add(POINT1, POINT2, POINT3);
Polyline line = googleMap.addPolyline(polylineOptions);

但是在我将这条线传递给 GoogleMap 之后,我无法向它添加任何新点。类似的东西

polylineOptions.add(POINT1, POINT2, POINT3);

不会向我的路线添加任何内容。

我可以添加完整的新折线。但是没有办法延长现有的吗?我想出了一个方法,获取折线的所有点,添加新点,然后将它们写回线:

List<LatLng> points = line.getPoints();
points.add(POINT4);
line.setPoints(points);

但这对我来说似乎很麻烦。有什么想法吗?

【问题讨论】:

  • 列表 点 = line.getPoints();点.add(POINT4); line.setPoints(点);工作正常,因为你保持“线”完好无损。然后更新它。

标签: android google-maps-android-api-2


【解决方案1】:

mainActivity类中,定义一个名为prev的私有静态LatLng变量,并首先将其初始化为(0,0)。还要创建一个标志变量并为其分配 0。在 Listener 的 OnLocationChanged 方法中,创建一个名为 current 的局部变量 LatLng 并在此处获取当前坐标...首先检查 flag 的值,如果为 0 则将 current 分配给 prev。然后添加一条折线。

再次将current分配给prev(每次都会发生这种情况,第一次之后,标志将为1)

例如:

public void onLocationChanged(Location location) 
{

    LatLng current = new LatLng(location.getLatitude(), location.getLongitude());

    if(flag==0)  //when the first update comes, we have no previous points,hence this 
    {
        prev=current;
        flag=1;
    }
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(current, 16);
    map.animateCamera(update);
    map.addPolyline((new PolylineOptions())
        .add(prev, current).width(6).color(Color.BLUE)
        .visible(true));
    prev=current;
    current = null;                    
}

类似的东西。当然可以进行性能改进,这只是一个示例代码。但它应该工作。每次折线将只添加前一个点和当前点,从而逐点扩展它。

【讨论】:

    【解决方案2】:

    查看文档,polylineOptions.add(LatLng)googleMap.addPolyline(polylineOptions) 方法似乎返回了 polylineOptions 对象。第一种方法还将返回polylineOptions WITH 添加到末尾的点。

    我认为您必须再次将polylineOptions 添加到googleMap.addPolyline(polylineOptions) 或使用googleMap.clear(),然后再添加第二次。有点像这样:

    polylineOptions = googleMap.addPolyline(polylineOptions);
    // googleMap.clear();
    googleMap.addPolyline(polylineOptions.add(point));
    

    【讨论】:

    • 同意这种方式似乎是可能的。但是,将 PolylineOptions 传递给 GoogleMap 之后,难道没有更简单的方法来向折线添加一个点吗?使用 clear() 然后将旧的 PolylineOption 与新的点一起添加在性能方面似乎是个坏主意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多