Search code examples
javaandroidmapboxmapbox-android

Mapbox: How to get a reference of a MapView from the Mapbox defined Fragment?


I followed the Mapbox's instructions here https://docs.mapbox.com/android/maps/examples/support-map-fragment/ and I can successfully visualize the map from the MapFragment.

//Create the mapFragment
if (savedInstanceState == null) {
     // Create fragment
     final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
     // Build mapboxMap
     MapboxMapOptions options = MapboxMapOptions.createFromAttributes(this, null).doubleTapGesturesEnabled(true);
     options.camera(new CameraPosition.Builder()
             .target(new LatLng(-52.6885, -70.1395))
             .zoom(14)
             .build());
      // Create map fragment
      mapFragment = SupportMapFragment.newInstance(options);
      // Add map fragment to parent container
      transaction.add(R.id.container, mapFragment, "com.mapbox.map");
      transaction.commit();
} else {
      mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag("com.mapbox.map");        
      // Working with Fragment - getFragment by ID
}

if (mapFragment != null) {
    mapFragment.getMapAsync(this);
}

Now I want to introduce the LineManager, in order to define some lines with the help of the annotation plugin, found here https://docs.mapbox.com/android/plugins/overview/annotation/ But the thing is, that I can't initilaize it, because of this part:

LineManager lineManager = new LineManager(mapView, mapboxMap, style);

I have the mapboxMap and the style but I don't have the mapView.

So how could we grab the mapView from the Mapbox's defined MapFragment?


Solution

  • I found it. To anyone, who want to use this approach later, you need to call

    mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentByTag("com.mapbox.map");
    (MapView) mapFragment.getView();  // Might return null
    

    It is also good to check if it's null in order to prevent NullPointerExceptions.