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

前端 未结 8 1497
隐瞒了意图╮
隐瞒了意图╮ 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

    Use the LocationManager.

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    double longitude = location.getLongitude();
    double latitude = location.getLatitude();
    

    The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.

    private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            longitude = location.getLongitude();
            latitude = location.getLatitude();
        }
    }
    
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
    

    You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.

    
    

    You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.

提交回复
热议问题