首页 文章

如何使用Google Maps Android API v2绘制动态线(路线)

提问于
浏览
4

我'm wondering what the best practice is to draw a dynamic route on a map with the Google Maps API v2. I want to have a map that'能够在用户移动时延长路线 . 使用Polyline和PolylineOptions似乎有一个明显的解决方案 . 但我只是找不到一个简单的方法来添加点 after 我实例化了Polyline . 绘制折线是这样的:

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

但在我将该行传递给GoogleMap后,我无法添加任何新的点 . 就像是

polylineOptions.add(POINT1, POINT2, POINT3);

没有添加任何东西到我的路线 .

我可以添加完整的新Polyline . 但是,有没有办法延长现有的?我通过获取Polyline的所有点,添加新点并将它们写回到该行来找到一种方法:

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

但这对我来说似乎很麻烦 . 有任何想法吗?

2 回答

  • 3

    mainActivity 类中,定义名为 prev 的私有静态 LatLng 变量,并首先将其初始化为 (0,0) . 还要创建一个标志变量并为其赋值0 . 在Listener的 OnLocationChanged 方法中,创建一个名为 current 的局部变量 LatLng 并在此处获取当前坐标...首先检查标志的值,如果为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;                    
    }
    

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

  • 0

    查看文档,似乎 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));
    

相关问题