Search code examples
androidandroid-layoutandroid-fragmentsmapboxmapbox-android

How to inflate android mapbox?


Im having trouble inflating mapbox. I tried putting the getInstance on MainActivity, the fragment loads with the mapbox logo on the lower leftmost but the map is empty. So I try to put the getInstance on the fragment then I got the error.

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_map, container, false);
        // Mapbox access token is configured here. This needs to be called either in your application
        // object or in the same activity which contains the mapview.
        Mapbox.getInstance(this, getString(R.string.access_token)); // Error in context:this
        mapView = view.findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(this);
        return view;
    }
   @Override
public void onMapReady(@NonNull final MapboxMap mapboxMap) {
    this.mapboxMap = mapboxMap;
    mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
        @Override
        public void onStyleLoaded(@NonNull Style style) {

        }
    });
}
}

Both bottom nav items are working

enter image description here


Solution

  • you forgot to mention the error but I think your code simply works.

    You have not defined a location where the map should be centered on so it presumably falls back to lat/lng of 0/0. This is right in the middle of the atlantic ocean. So the blue you see on the map is just water :)

    Try to move the map around and zoom out, you will see Africa soon!

    Edit

    I read again. Are you talking about this?

    Mapbox.getInstance(this, getString(R.string.access_token)); // Error in context:this
    

    Well, if this code is executed in a fragment, you probably need getActivity() instead of just this