How to get Latitude and Longitude of the mobile device in android?

前端 未结 8 1413
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 16:09

How do I get the current Latitude and Longitude of the mobile device in android using location tools?

相关标签:
8条回答
  • 2020-11-22 16:34

    You can use FusedLocationProvider

    For using Fused Location Provider in your project you will have to add the google play services location dependency in our app level build.gradle file

    dependencies {
       implementation fileTree(dir: 'libs', include: ['*.jar'])
       ...
       ...
       ...
       implementation 'com.google.android.gms:play-services-location:17.0.0'
    }
    

    Permissions in Manifest

    Apps that use location services must request location permissions. Android offers two location permissions: ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    

    As you may know that from Android 6.0 (Marshmallow) you must request permissions for important access in the runtime. Cause it’s a security issue where while installing an application, user may not clearly understand about an important permission of their device.

    ActivityCompat.requestPermissions(
        this,
        arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION),
        PERMISSION_ID
    )
    

    Then you can use the FusedLocationProvider Client to get the updated location in your desired place.

        mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task ->
            var location: Location? = task.result
            if (location == null) {
                requestNewLocationData()
            } else {
                findViewById<TextView>(R.id.latTextView).text = location.latitude.toString()
                findViewById<TextView>(R.id.lonTextView).text = location.longitude.toString()
            }
        }
    

    You can also check certain configuration like if the device has location settings on or not. You can also check the article on Detect Current Latitude & Longitude using Kotlin in Android for more functionality. If there is no cache location then it will catch the current location using:

    private fun requestNewLocationData() {
        var mLocationRequest = LocationRequest()
        mLocationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        mLocationRequest.interval = 0
        mLocationRequest.fastestInterval = 0
        mLocationRequest.numUpdates = 1
    
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        mFusedLocationClient!!.requestLocationUpdates(
                mLocationRequest, mLocationCallback,
                Looper.myLooper()
        )
    }
    
    0 讨论(0)
  • 2020-11-22 16:38

    Above solutions is also correct, but some time if location is null then it crash the app or not working properly. The best way to get Latitude and Longitude of android is:

     Geocoder geocoder;
         String bestProvider;
         List<Address> user = null;
         double lat;
         double lng;
    
        LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
    
         Criteria criteria = new Criteria();
         bestProvider = lm.getBestProvider(criteria, false);
         Location location = lm.getLastKnownLocation(bestProvider);
    
         if (location == null){
             Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
          }else{
            geocoder = new Geocoder(activity);
            try {
                user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
            lat=(double)user.get(0).getLatitude();
            lng=(double)user.get(0).getLongitude();
            System.out.println(" DDD lat: " +lat+",  longitude: "+lng);
    
            }catch (Exception e) {
                    e.printStackTrace();
            }
        }
    
    0 讨论(0)
提交回复
热议问题