Home > Java > javaTutorial > body text

How to Get an Android Device\'s Latitude and Longitude?

Patricia Arquette
Release: 2024-11-19 20:50:03
Original
922 people have browsed it

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
Copy after login

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);
Copy after login

Ensure your application has the ACCESS_FINE_LOCATION permission for GPS usage:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template