Reputation: 2447
I'm trying to display a custom vector layer on a map using Mapbox in my Android application. Using the latest mapbox version.
When I include the layer the following way :
//DOES NOT WORK
binding.mapView.getMapAsync(mapboxMap -> {
map = mapboxMap;
VectorSource source = new VectorSource("source-id", new TileSet("2.1.0", baseUrl + "/{z}/{x}/{y}.mvt"));
mapboxMap.addSource(source);
LineLayer layer = new LineLayer("zones-outline", "source-id");
layer.setSourceLayer("zones");
layer.setProperties(
PropertyFactory.lineWidth(2f),
PropertyFactory.lineColor(getResources().getColor(R.color.md_blue_500))
);
mapboxMap.addLayer(layer);
})
It show nothing (no log in android nor in my server, it is like the layer is not even known to mapbox).
But if I put the addsource and addlayer code in a runnable, lets say with a 100 milliseconds delay, it does show my layers properly. Obviously this looks like its related to some kind of concurrency or "order of initialization", and the delay works, but it is not a nice and proper solution (I imagine on old device it could take more than 100 ms to load the map, maybe it wont work).
//WORKS
binding.mapView.getMapAsync(mapboxMap -> {
final Handler handler = new Handler();
handler.postDelayed(() -> {
map = mapboxMap;
VectorSource source = new VectorSource("source-id", new TileSet("2.1.0", baseUrl + "/{z}/{x}/{y}.mvt"));
mapboxMap.addSource(source);
LineLayer layer = new LineLayer("zones-outline", "source-id");
layer.setSourceLayer("zones");
layer.setProperties(
PropertyFactory.lineWidth(2f),
PropertyFactory.lineColor(getResources().getColor(R.color.md_blue_500))
);
mapboxMap.addLayer(layer);
}, 100)
})
Is there another method / callback where I should put this initialization ? How to be sure my layers will be drawn ?
Upvotes: 1
Views: 850
Reputation: 2447
The problem came from the fact that I was setting, also in the onMapReady callback, a new style url (loaded dynamically depending on the content displayed).
I move the mapView.setStyleUrl(mapboxStyle)
before the map initialization :
mapView.setStyleUrl(mapboxStyle);
binding.contestMapView.onCreate(savedInstanceState);
binding.contestMapView.getMapAsync(mapboxMap -> {
// vector source and layer initialization
});
Upvotes: 3