Home >Java >javaTutorial >How to Get an Android Device\'s Latitude and Longitude?
Obtaining Latitude and Longitude of a Mobile Device in Android
Question:
How can I access the current Latitude and Longitude of an Android device using location tools?
Answer:
Utilize the LocationManager class:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Obtain the LocationManager Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); // Get the last known GPS location double longitude = location.getLongitude(); // Extract longitude double latitude = location.getLatitude(); // Extract latitude
If no current location is available, getLastKnownLocation() may return null. To receive asynchronous location updates, consider providing a LocationListener to requestLocationUpdates():
private final LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { longitude = location.getLongitude(); latitude = location.getLatitude(); } }; lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
Ensure your application has the ACCESS_FINE_LOCATION permission for GPS usage:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
For improved accuracy, you can consider adding the ACCESS_COARSE_LOCATION permission and determining the best provider using getBestProvider().
The above is the detailed content of How to Get an Android Device's Latitude and Longitude?. For more information, please follow other related articles on the PHP Chinese website!