How to get current location in MAPBOX in android

kalai vani picture kalai vani · Nov 13, 2017 · Viewed 13.8k times · Source

As I am using MAPBOX in my application.I don't know how to get current lat and long.I used this way to get the current location.But its showing null object reference.Please help me to solve my problem

     mapView = (MapView)view. findViewById(R.id.mapView);
    mapView.setStyleUrl(Style.MAPBOX_STREETS);
    mapView.onCreate(savedInstanceState);

    //Add a mapBoxMap
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(MapboxMap mapboxMap) {
            mapboxMap.setMyLocationEnabled(true);
            // Set the origin waypoint to the devices location
            Position origin = Position.fromCoordinates(mapboxMap.getMyLocation().getLongitude(), mapboxMap.getMyLocation().getLatitude());

            Log.i("RR","mapboxMap.getMyLocation();"+origin);
           // Log.i("RR","mapboxMap.getMyLocation();"+mapboxMap.getMyLocation().getLongitude());
            mapboxMap.getUiSettings().setZoomControlsEnabled(true);
            mapboxMap.getUiSettings().setZoomGesturesEnabled(true);
            mapboxMap.getUiSettings().setScrollGesturesEnabled(true);
            mapboxMap.getUiSettings().setAllGesturesEnabled(true);


        }

    });

Answer

Jaganath picture Jaganath · Dec 8, 2017

mapboxMap.setMyLocationEnabled(true); has been deprecated.

You need to use locationEngine to get lat and long like this

    locationEngine = new LostLocationEngine(MainActivity.this);
    locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
    locationEngine.setInterval(5000);
    locationEngine.activate();
    Location lastLocation = locationEngine.getLastLocation();

use lastLocation.getLatitude(), lastLocation.getLongitude()