如何更新 MapBox 中现有的线图层

How to update existing line layer in MapBox

Here 是绘制直线几何的 mapBox 示例。

    private void onStyleLoaded(Style style) {

        initRouteCoordinates();

        style.addSource(new GeoJsonSource("line-source",
                FeatureCollection.fromFeatures(new Feature[]{
                        Feature.fromGeometry(LineString.fromLngLats(routeCoordinates))})));

        style.addLayer(new LineLayer("lineLayer", "line-source")
        .withProperties(PropertyFactory.lineDasharray(new Float[] {0.01f, 2f}),
                PropertyFactory.lineCap(Property.LINE_CAP_ROUND),
                PropertyFactory.lineJoin(Property.LINE_JOIN_ROUND),
                PropertyFactory.lineWidth(5f),
                PropertyFactory.lineColor(Color.parseColor("#e55e5e"))));

        Point point = routeCoordinates.get(0);
        mapboxMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                new LatLng(point.latitude(), point.longitude()), 17));
    }

我需要添加更多点并更新线条。正如您在示例中看到的那样,在构建时将线几何图形提供给源层。我找不到任何 api 稍后在当前行中添加一个点。
我应该删除这条线并重新绘制一条新线吗?没有更好的方法吗?

可以一次添加"line-source"源和对应的"lineLayer"层,设置源包含的数据每次要添加更多点更新线。即,每次您想更新 LineLayer:

呈现的数据时
  1. 将新获取的坐标添加到现有的 GeoJSON 源中,存储在名为 data 的变量中。 (我建议将 new GeoJsonSource("line-source", ... 存储在 data 变量中,而不是在对 style#addSource 的调用中内联创建它,以便您稍后可以访问它进行更新。
  2. 执行style.getSourceAs("line-source").setGeoJson(data)

或者,您可以使用 geoJsonSource.setGeoJson(Feature.fromGeometry(LineString.fromLngLats(updatedRouteCoordinates))) 而不是 setGeoJson(data),这可能更方便,具体取决于您的用例。

您可以根据您的具体需要修改实现,但总体思路是您只需要更新现有源的数据,而不是其对应的图层,每次您要更新行。 Android 的 Mapbox Maps SDK modify properties documentation 中描述了这个概念。引用文档:

sources and layers aren't immutable so they can be modified anytime during the map render