Reputation: 2420
Here is mapBox sample to draw a line geometry.
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));
}
I need to add more points and update the line. As you can see in the example line geometry is given to the source layer at the construction time. I couldn't find any api to add a point to the current line later.
Should I remove this line and redraw a new one ? Isn't there a better approach ?
Upvotes: 2
Views: 2122
Reputation: 1299
You can add the "line-source"
source and corresponding "lineLayer"
layer once, and set the data contained by the source each time you want to add more points to update the line. Namely, each time you want to update the data rendered by the LineLayer
:
data
. (I'd recommend storing new GeoJsonSource("line-source", ...
in a data
variable rather than creating it inline within the call to style#addSource
, so that you can access it later to update).style.getSourceAs("line-source").setGeoJson(data)
. Alternatively, you could use geoJsonSource.setGeoJson(Feature.fromGeometry(LineString.fromLngLats(updatedRouteCoordinates)))
rather than setGeoJson(data)
, which might be more convenient depending on your use case.
You can modify the implementation according to your specific needs, but the general idea is that you only need to update the existing source's data, and not its corresponding layer, each time you want to update the line. This concept is described in the modify properties documentation for the Mapbox Maps SDK for Android. To quote the documentation:
sources and layers aren't immutable so they can be modified anytime during the map render
Upvotes: 4