Get Current Location
Before you can retrieve location data, you must configure the required permissions in your AndroidManifest.xml file to ensure the location feature works correctly.
Step 1: Configure AndroidManifest.xml
Declare the Service Component
Declare the service component inside the <application> tag. Each app must have its own dedicated location service.
<service android:name="com.amap.api.location.APSService"></service>Declare Permissions
For Android 6.0 (API level 23) and higher, see the Android 6.0 Permissions guide.
<!-- Required for network-based location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<!-- Required for GPS-based location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<!-- Required to access carrier information for carrier-related APIs -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<!-- Required to access Wi-Fi network information for network-based location -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<!-- Required to obtain Wi-Fi scan permissions for network-based location -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<!-- Required for network access (network-based location requires internet) -->
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<!-- Required to invoke the A-GPS module -->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
<!-- Required for foreground service if targetSdkVersion >= 28 and background location is needed -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<!-- Required for background location on Android Q (API level 29) and higher if targetSdkVersion > 28 -->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>Set the AMAP API Key
Add the following <meta-data> element inside the <application> tag:
<meta-data android:name="com.amap.api.v2.apikey" android:value="your_api_key_here"/>Step 2: Initialize the Location Client
Create an AMapLocationClient object on the main thread. Pass a Context parameter — it is recommended to use getApplicationContext() to obtain a process-wide context.
// Declare the AMapLocationClient object
public AMapLocationClient mLocationClient = null;
// Declare the location callback listener
public AMapLocationListener mLocationListener = new AMapLocationListener();
// Initialize the location client
mLocationClient = new AMapLocationClient(getApplicationContext());
// Set the location callback listener
mLocationClient.setLocationListener(mLocationListener);
// Since SDK v6.4.9: set the reverse geocoding callback
locationClient.setReGeoLocationCallback(new IReGeoLocationCallback() {
@Override
public void onReGeoLocation(AMapLocation reGeoLocation) {
Log.i(TAG, reGeoLocation.toStr());
}
});Note: Since SDK v6.4.9, you can proactively request reverse geocoding in the onLocationChanged callback:
if (!locationOption.isNeedAddress()) {
// Reverse geocoding is disabled; proactively call the reverse geocoding API
// The result is returned via the onReGeoLocation callback
locationClient.getReGeoLocation(location);
}Step 3: Configure Parameters and Start Location
Configure single or continuous location settings here. Read the full documentation carefully.
Create an AMapLocationClientOption Object
The AMapLocationClientOption object is used to set the location mode and related parameters.
// Declare the AMapLocationClientOption object
public AMapLocationClientOption mLocationOption = null;
// Initialize the AMapLocationClientOption object
mLocationOption = new AMapLocationClientOption();Select a Location Scenario
This feature is available from SDK v3.7.0. If you select a predefined scenario, you do not need to manually configure other parameters in AMapLocationClientOption — the SDK automatically sets the appropriate values based on the scenario. You can still override individual parameters if needed; the last value set takes effect.
Three scenarios are supported: Sign-in, Navigation, and Sports. The default is no scenario.
AMapLocationClientOption option = new AMapLocationClientOption();
/**
* Set the location scenario. Currently supports three scenarios:
* SignIn, Navigation, and Sports. Default is no scenario.
*/
option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
if (null != locationClient) {
locationClient.setLocationOption(option);
// After setting the scenario, call stopLocation() then startLocation()
// to ensure the scenario takes effect.
locationClient.stopLocation();
locationClient.startLocation();
}Select a Location Mode
The AMAP Location SDK provides both GPS and network-based (Wi-Fi and cellular) location capabilities. These are encapsulated into three location modes. The default mode is High Accuracy.
High Accuracy Mode: Uses both network and GPS location, returning the highest accuracy result along with address information.
// Set location mode to High Accuracy
mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);Battery Saving Mode: Does not use GPS or other sensors. Only uses network location (Wi-Fi and cellular).
// Set location mode to Battery Saving
mLocationOption.setLocationMode(AMapLocationMode.Battery_Saving);Device Sensors Only Mode: Does not require a network connection. Uses only GPS for location. This mode does not support indoor positioning and requires an outdoor environment.
Note: Since SDK v2.9.0, Device Sensors Only mode supports returning address information.
// Set location mode to Device Sensors Only
mLocationOption.setLocationMode(AMapLocationMode.Device_Sensors);Configure Single Location
To use single location, configure the following:
// Get a single location result:
// This method defaults to false.
mLocationOption.setOnceLocation(true);
// Get the most accurate location result within the last 3 seconds:
// When setOnceLocationLatest(boolean b) is set to true, the SDK will return the most accurate
// location result within the last 3 seconds upon starting location updates.
// If set to true, setOnceLocation(boolean b) will also be set to true, but not vice versa. Default is false.
mLocationOption.setOnceLocationLatest(true);Configure Continuous Location
The SDK uses continuous location by default with a 2000 ms interval. To customize the interval:
// Sets the location update interval in milliseconds. Default is 2000ms, minimum is 1000ms.
mLocationOption.setInterval(1000);Other Parameters
Return Address Information
Set whether to return address information along with the location result.
// Enable address information
mLocationOption.setNeedAddress(true);Allow Mock Locations
Set whether to allow mock (simulated) GPS locations. Default is true (allowed).
// Sets whether to allow mock locations. Default is true, which allows mock locations.
mLocationOption.setMockEnable(true);Set Location Timeout
Set the timeout for location requests. Default is 30 seconds.
Note: Since SDK v3.1.0, setHttpTimeOut(long httpTimeOut) applies to both Battery Saving and High Accuracy modes, as well as Device Sensors Only mode. If a single location request times out, it is terminated. In continuous mode, the current request times out, but subsequent requests continue at the scheduled interval.
// Set timeout to 20 seconds (20000 ms)
mLocationOption.setHttpTimeOut(20000);Enable Location Cache
The location cache is enabled by default. You can disable it using the following API.
When caching is enabled, network-based location results (in High Accuracy and Battery Saving modes) are cached locally. This applies to both single and continuous location. GPS location results are never cached.
// Disable location cache
mLocationOption.setLocationCacheEnable(false);Start Location
// Set location parameters
mLocationClient.setLocationOption(mLocationOption);
// Start location
mLocationClient.startLocation();AMapLocationClientOption Core Methods
The following table describes the core methods for configuring location parameters. These are detailed explanations of the methods used in the previous section. For additional methods, refer to the AMapLocationClientOption class in the API reference.
Step 4: Get Location Results
The AMapLocationListener interface provides the onLocationChanged method for receiving asynchronous location results. The callback parameter is an AMapLocation object.
Implement the Listener
public AMapLocationListener mLocationListener = new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation amapLocation) {
// Handle location result
}
};Parse the AMapLocation Object
First, verify that the AMapLocation object is not null. Location is successful when the error code is 0.
if (amapLocation != null) {
if (amapLocation.getErrorCode() == 0) {
// Location successful
} else {
// Location failed
Log.e("AmapError", "location Error, ErrCode:"
+ amapLocation.getErrorCode() + ", errInfo:"
+ amapLocation.getErrorInfo());
}
}When location is successful, parse the fields of the amapLocation object as shown below:
amapLocation.getLocationType(); // Get the source of the current location result (e.g. network location). See location type table for details.
amapLocation.getLatitude(); // Get latitude
amapLocation.getLongitude(); // Get longitude
amapLocation.getAccuracy(); // Get accuracy information
amapLocation.getAddress(); // Get address. If isNeedAddress is set to false in the option, this result will not be available. Address information is available in network location results, but not in GPS location results.
amapLocation.getCountry(); // Get country information
amapLocation.getProvince(); // Get province information
amapLocation.getCity(); // Get city information
amapLocation.getDistrict(); // Get district information
amapLocation.getStreet(); // Get street information
amapLocation.getStreetNum(); // Get street number information
amapLocation.getCityCode(); // Get city code
amapLocation.getAdCode(); // Get area code
amapLocation.getAoiName(); // Get the AOI information of the current location point
amapLocation.getBuildingId(); // Get the building ID of the current indoor location
amapLocation.getFloor(); // Get the floor of the current indoor location
amapLocation.getGpsAccuracyStatus(); // Get the current GPS status
// Get the location timestamp
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(amapLocation.getTime());
df.format(date);AMapLocation Core Methods
The following table describes the core methods of the AMapLocation class. These are detailed explanations of the methods used in the previous section. For additional methods, refer to the AMapLocation class in the API reference.
Step 5: Stop Location
Stop Location
mLocationClient.stopLocation();Destroy the Location Client
After destroying the location client, you must create a new AMapLocationClient object to restart location.
mLocationClient.onDestroy();Important Notes
- When the device screen is off or locked for an extended period, the CPU may enter sleep mode, preventing the location SDK from updating the position. If you need to obtain location while the screen is locked, use AlarmManager to create a timer that wakes the CPU and periodically requests location.
- Always register the GPS and network permissions when using the location SDK.
- Ensure the device has a stable network connection when using network-based location or retrieving address information.
- The location SDK returns AMAP coordinates within China and GPS coordinates outside of China.