How to get current location in MAPBOX in android
Asked Answered
D

5

8

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);
    }
});
Dittman answered 13/11, 2017 at 7:18 Comment(2)
use FusedLocationApiCircumlocution
You can use this link for current user Location, it is the full toturial : Build an Android App in Java: (2/4) Adding User Location in Mapbox SDKTrample
T
5

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()

Tablet answered 7/12, 2017 at 23:39 Comment(1)
how can we get lat & long and move camera ?Anastatius
P
4

After spending 1 day of searching I got the results Here is the Complete code of MapBox User Current Location getting. MainActivity:

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.CameraMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;

import java.util.List;

public class Main2Activity extends AppCompatActivity implements OnMapReadyCallback, LocationEngineListener, PermissionsListener {
    private MapView mapView;
    private MapboxMap map;
    LocationEngine locationEngine;
    LocationLayerPlugin locationLayerPlugin;
    PermissionsManager permissionsManager;
    Location originLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this, "YOUR_MAPBOX_KEY");
        setContentView(R.layout.activity_main2);
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(this);
    }

    @Override
    public void onMapReady(MapboxMap mapboxMap) {
       /* LocationPluginActivity.this.map = map;
        enableLocationPlugin();*/
        map = mapboxMap;
        locationEnable();
        mapboxMap.getUiSettings().setZoomControlsEnabled(true);
        mapboxMap.getUiSettings().setZoomGesturesEnabled(true);
        mapboxMap.getUiSettings().setScrollGesturesEnabled(true);
        mapboxMap.getUiSettings().setAllGesturesEnabled(true);
    }

    void locationEnable() {
        if (PermissionsManager.areLocationPermissionsGranted(this)) {
            intialLocationEngine();
            intializLocationLayer();
        } else {
            permissionsManager = new PermissionsManager(this);
            permissionsManager.requestLocationPermissions(this);
        }
    }

    void intialLocationEngine() {
        locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
        locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
        locationEngine.activate();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location lastLocation = locationEngine.getLastLocation();
        if (lastLocation != null) {
            originLayout = lastLocation;
            setCamerpostion(lastLocation);
        } else {
            locationEngine.addLocationEngineListener(this);
        }

    }

    void intializLocationLayer() {
        locationLayerPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
        locationLayerPlugin.setLocationLayerEnabled(true);
        locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
        locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
    }

    void setCamerpostion(Location camerpostion) {
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(camerpostion.getLatitude(), camerpostion.getLongitude()), 13.0));
    }

    @Override
    public void onConnected() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationEngine.requestLocationUpdates();
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            originLayout = location;
            setCamerpostion(location);
        }
    }

    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain) {

    }

    @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            locationEnable();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @SuppressWarnings("MissingPermission")
    @Override
    public void onStart() {
        super.onStart();
        if (locationEngine != null)
           locationEngine.requestLocationUpdates();
        mapView.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 onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationEngine!=null)
        {
            locationEngine.deactivate();
        }        mapView.onDestroy();
    }

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

Here is the Xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.joltatech.selfmadmap.Main2Activity">

    <com.mapbox.mapboxsdk.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:mapbox_cameraTargetLat="40.73581"
        app:mapbox_cameraTargetLng="-73.99155"
        app:mapbox_styleUrl="@string/mapbox_style_satellite_streets"
        app:mapbox_cameraZoom="11"/>
</RelativeLayout>

Here is the Gradle Files:

implementation 'com.mapbox.mapboxsdk:mapbox-android-sdk:6.3.0'
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-locationlayer:0.6.0'

and in the Project level Gradle use:

jcenter()
mavenCentral()
Part answered 21/7, 2018 at 5:41 Comment(1)
Is there any solution to use something instead of the plugin because it's deprecated by now?Ashford
S
1

mapboxMap.getLocationComponent().getLastKnownLocation().getLatitude()

Streaky answered 7/2, 2019 at 0:37 Comment(2)
I always get null for both latitude and longitude. Are there any prerequisites before accessing getLocationComponent().getLastKnownLocation()?Taima
I always get null in the emulator. But works in a cellphone. It's really tricky to develop like that.Thomasenathomasin
C
0

For getting initial location of user this is the best one code and is working for me

 protected void getLocation() {
    if (isLocationEnabled(MainActivity.this)) {
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();

        //You can still do this if you like, you might get lucky:
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            Log.e("TAG", "GPS is on");
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            originLocation=location;
            Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
            searchNearestPlace(voice2text);
        }
        else{
            //This is what you need:
            locationManager.requestLocationUpdates(bestProvider, 1000, 0, (android.location.LocationListener) MainActivity.this);
        }
    }
    else
    {
        //prompt user to enable location....
        //.................
    }
}
Clamorous answered 7/1, 2019 at 17:23 Comment(0)
D
0

As per 10.11.0 version , Mapbox have modified their classes a lot . So get location from mapview , probably we can use below mentioned code

JAVA :-

LocationConsumer locationConsumer = new LocationConsumer() {
                @Override
                public void onLocationUpdated(@NonNull Point[] points, @Nullable Function1<? super ValueAnimator, Unit> function1) {
                    ((DefaultLocationProvider)LocationComponentUtils.getLocationComponent(fragmentExploreZooBinding.mapView).getLocationProvider()).unRegisterLocationConsumer(this);
                    Point latestPoint = (points.length > 0 && points[0] != null) ? points[0] : null;
                    if (latestPoint != null) {
                       ((DefaultLocationProvider)LocationComponentUtils.getLocationComponent(fragmentExploreZooBinding.mapView).getLocationProvider()).unRegisterLocationConsumer(this);
                       //Once we got location , we can unregister if we don't want to listen location updates
                    }
                        
                }

                @Override
                public void onBearingUpdated(@NonNull double[] doubles, @Nullable Function1<? super ValueAnimator, Unit> function1) {

                }

                @Override
                public void onPuckLocationAnimatorDefaultOptionsUpdated(@NonNull Function1<? super ValueAnimator, Unit> function1) {

                }

                @Override
                public void onPuckBearingAnimatorDefaultOptionsUpdated(@NonNull Function1<? super ValueAnimator, Unit> function1) {

                }
            };
    

((DefaultLocationProvider)LocationComponentUtils.getLocationComponent(fragmentExploreZooBinding.mapView).getLocationProvider()).registerLocationConsumer(locationConsumer);

Kotlin

val locationConsumer = object: LocationConsumer{
    override fun onBearingUpdated(
        vararg bearing: Double,
        options: (ValueAnimator.() -> Unit)?
    ) {
        TODO("Not yet implemented")
    }

    override fun onLocationUpdated(
        vararg location: Point,
        options: (ValueAnimator.() -> Unit)?
    ) {
       fragmentExploreZooBinding.mapView.location.registerLocationConsumer(this)
      val latestPoint = if(location.length > 0 && location[0] != null) location[0] else null
    }

    override fun onPuckBearingAnimatorDefaultOptionsUpdated(options: ValueAnimator.() -> Unit) {
        TODO("Not yet implemented")
    }

    override fun onPuckLocationAnimatorDefaultOptionsUpdated(options: ValueAnimator.() -> Unit) {
        TODO("Not yet implemented")
    }

}
fragmentExploreZooBinding.mapView.location.registerLocationConsumer(locationConsumer)

Dawdle answered 23/2, 2023 at 11:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.