Search code examples
mapbox-android

My class is extent by fragment. I can't get a location


Why can't I get location information? When I extend my class with AppCompatActivity, I can get a location. But when I extent with fragment, I cannot get a location.

public class Fragment_Ucuncu extends Fragment implements OnMapReadyCallback, PermissionsListener {
    private MapView mapView;
    private PermissionsManager permissionsManager;

    private MapboxMap mapboxMap;

    private final String MAPKIT_API_KEY = "delete";
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Mapbox.getInstance(getActivity() , "delete");
        View rootView = inflater.inflate(R.layout.fragment_ucuncu_layout, container, false);

        mapView = rootView.findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);

        mapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(@NonNull MapboxMap mapboxMap) {
                mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
                    @Override
                    public void onStyleLoaded(@NonNull Style style) {

                    }
                });
            }
        });




        return rootView;

    }
    @Override
    public void onMapReady(@NonNull final MapboxMap mapboxMap) {
        Fragment_Ucuncu.this.mapboxMap = mapboxMap;

        mapboxMap.setStyle(new Style.Builder().fromUri("mapbox://styles/mapbox/cjerxnqt3cgvp2rmyuxbeqme7"),
                new Style.OnStyleLoaded() {
                    @Override
                    public void onStyleLoaded(@NonNull Style style) {
                        enableLocationComponent(style);
                    }
                });
    }
    private void enableLocationComponent(@NonNull Style loadedMapStyle) {
// Check if permissions are enabled and if not request
        if (PermissionsManager.areLocationPermissionsGranted(getActivity())) {

// Get an instance of the component
            LocationComponent locationComponent = mapboxMap.getLocationComponent();

// Activate with options
            locationComponent.activateLocationComponent(
                    LocationComponentActivationOptions.builder(getActivity(), loadedMapStyle).build());

// Enable to make component visible
            locationComponent.setLocationComponentEnabled(true);

// Set the component's camera mode
            locationComponent.setCameraMode(CameraMode.TRACKING);

// Set the component's render mode
            locationComponent.setRenderMode(RenderMode.COMPASS);
        } else {
            permissionsManager = new PermissionsManager(this);
            permissionsManager.requestLocationPermissions(getActivity());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain) {
        Toast.makeText(getActivity(), "one", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            mapboxMap.getStyle(new Style.OnStyleLoaded() {
                @Override
                public void onStyleLoaded(@NonNull Style style) {
                    enableLocationComponent(style);
                }
            });
        } else {
            Toast.makeText(getActivity(), "two", Toast.LENGTH_LONG).show();
            getActivity().finish();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

}

I need to show a "mapbox" map in my fragment in the navigation drawer. I couldn't find a sample code for this. I did this with google map. I can't do with Mapbox. Can you tell me where the problem is? Do you have any suggestions?


Solution

  • I solved the problem. It works for me.

    package com.one.qaroco;
    
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    
    import androidx.fragment.app.Fragment;
    
    import com.mapbox.android.core.permissions.PermissionsListener;
    import com.mapbox.android.core.permissions.PermissionsManager;
    
    import com.mapbox.mapboxsdk.maps.MapboxMap;
    import android.widget.Toast;
    
    import com.mapbox.android.core.permissions.PermissionsListener;
    import com.mapbox.android.core.permissions.PermissionsManager;
    import com.mapbox.mapboxsdk.Mapbox;
    import com.mapbox.mapboxsdk.camera.CameraPosition;
    import com.mapbox.mapboxsdk.geometry.LatLng;
    import com.mapbox.mapboxsdk.location.LocationComponent;
    import com.mapbox.mapboxsdk.location.LocationComponentActivationOptions;
    import com.mapbox.mapboxsdk.location.modes.CameraMode;
    import com.mapbox.mapboxsdk.location.modes.RenderMode;
    import com.mapbox.mapboxsdk.maps.MapboxMap;
    import com.mapbox.mapboxsdk.maps.MapboxMapOptions;
    import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
    import com.mapbox.mapboxsdk.maps.Style;
    import com.mapbox.mapboxsdk.maps.SupportMapFragment;
    
    import java.util.List;
    
    import androidx.annotation.NonNull;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.fragment.app.FragmentTransaction;
    
    public class FragmentBirinci extends Fragment implements PermissionsListener {
        private MapboxMap mapboxMap;
        private PermissionsManager permissionsManager;
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_birinci_layout, 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(getActivity(), getString(R.string.access_token));
    
            // Create supportMapFragment
            SupportMapFragment mapFragment;
            if (savedInstanceState == null) {
    
                // Create fragment
                final FragmentTransaction transaction = getFragmentManager().beginTransaction();
    
                // Build a Mapbox map
                MapboxMapOptions options = MapboxMapOptions.createFromAttributes(getActivity(), null);
                options.camera(new CameraPosition.Builder()
                        .target(new LatLng(38.899895, -77.03401))
                        .zoom(9)
                        .build());
    
                // Create map fragment
                mapFragment = SupportMapFragment.newInstance(options);
    
                // Add map fragment to parent container
                transaction.add(R.id.location_frag_container, mapFragment, "com.mapbox.map");
                transaction.commit();
            } else {
                mapFragment = (SupportMapFragment) getFragmentManager().findFragmentByTag("com.mapbox.map");
            }
    
            if (mapFragment != null) {
                mapFragment.getMapAsync(new OnMapReadyCallback() {
                    @Override
                    public void onMapReady(@NonNull MapboxMap mapboxMap) {
                        FragmentBirinci.this.mapboxMap = mapboxMap;
                        mapboxMap.setStyle(Style.OUTDOORS, new Style.OnStyleLoaded() {
                            @Override
                            public void onStyleLoaded(@NonNull Style style) {
                                enableLocationComponent(style);
                            }
                        });
                    }
                });
            }
    
            return rootView;
    
    
        }
    
        @SuppressWarnings( {"MissingPermission"})
        private void enableLocationComponent(@NonNull Style loadedMapStyle) {
            // Check if permissions are enabled and if not request
            if (PermissionsManager.areLocationPermissionsGranted(getActivity())) {
    
                // Get an instance of the LocationComponent.
                LocationComponent locationComponent = mapboxMap.getLocationComponent();
    
                // Activate the LocationComponent
                locationComponent.activateLocationComponent(
                        LocationComponentActivationOptions.builder(getActivity(), loadedMapStyle).build());
    
                // Enable the LocationComponent so that it's actually visible on the map
                locationComponent.setLocationComponentEnabled(true);
    
                // Set the LocationComponent's camera mode
                locationComponent.setCameraMode(CameraMode.TRACKING);
    
                // Set the LocationComponent's render mode
                locationComponent.setRenderMode(RenderMode.NORMAL);
            } else {
                permissionsManager = new PermissionsManager(this);
                permissionsManager.requestLocationPermissions(getActivity());
            }
        }
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    
        @Override
        public void onExplanationNeeded(List<String> permissionsToExplain) {
            Toast.makeText(getActivity(), R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
        }
    
        @Override
        public void onPermissionResult(boolean granted) {
            if (granted) {
                mapboxMap.getStyle(new Style.OnStyleLoaded() {
                    @Override
                    public void onStyleLoaded(@NonNull Style style) {
                        enableLocationComponent(style);
                    }
                });
            } else {
                Toast.makeText(getActivity(), R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
                getActivity().finish();
            }
        }
    }
    

    If you want to use the mapbox with a fragment structure in the navigation drawer, there are things to consider.

    1. Make sure that the imported libraries are "mapbox". Sometimes google libraries can be imported and this causes errors.

      1. Use "getActivity" instead of "this".

    mapbox.com

    github mapbox

    github issues