Document Location SDK for Android Guides Location Get Current Location

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"/>

Get your API key

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-inNavigation, 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.

Name

Meaning

Rule Description

Required

Default

setLocationMode(AMapLocationMode locationMode)

Sets the location mode

Available since v2.0.0. Provides three enum constants: Hight_Accuracy (high accuracy), Device_Sensors (device sensors only), Battery_Saving (battery saving). Note: If the user sets the app location permission to "approximate location", Battery Saving mode is unavailable.

Yes

Hight_Accuracy

locationMode

Location mode enum

AMapLocationMode object

Yes

-

setLocationCacheEnable(boolean isLocationCacheEnable)

Enables or disables location cache

Available since v2.5.0. When enabled, the SDK returns cached results if the device position has not changed.

No

true

isLocationCacheEnable

Cache flag

true: use cache; false: do not use cache

Yes

true

setInterval(long interval)

Sets the continuous location interval

Available since v2.0.0. Value in milliseconds. For example, 1000 means location results are returned every 1 second. Note: If the user sets the app location permission to "approximate location", continuous location is unavailable.

No

2000

interval

Interval in milliseconds

Long integer

Yes

2000

setOnceLocation(boolean isOnceLocation)

Sets single location mode

Available since v2.0.0. true: single location (returns one result); false: continuous location. Note: If the user sets the app location permission to "approximate location", continuous location is unavailable.

No

false

isOnceLocation

Single location flag

true: single location; false: continuous location

Yes

false

setOnceLocationLatest(boolean isOnceLocationLatest)

Gets the most accurate result from the last 3 seconds

Available since v2.6.0. true: returns the most accurate location result from the last 3 seconds; false: uses default continuous location. Note: If the user sets the app location permission to "approximate location", continuous location is unavailable.

No

false

isOnceLocationLatest

Latest accurate result flag

true: get latest accurate result; false: continuous location

Yes

false

setNeedAddress(boolean isNeedAddress)

Sets whether to return address information

Available since v2.0.0. true: returns address information along with coordinates (only for network-based location); false: does not return address information. Note: In Device Sensors Only mode, this setting has no effect. Since v6.4.9, the default value is false.

No

false

isNeedAddress

Address flag

true: return address; false: do not return address

Yes

false

setMockEnable(boolean isMockEnable)

Sets whether to allow mock GPS locations

Available since v2.0.0. true: allows third-party apps to simulate GPS location; false: disallows mock locations. Note: In Battery Saving mode, this setting has no effect.

No

false

isMockEnable

Mock location flag

true: allow mock; false: disallow mock

Yes

false

setWifiActiveScan(boolean isWifiActiveScan)

Sets whether to actively scan Wi-Fi

Available since v2.0.0. true: actively refreshes the Wi-Fi module to get the latest Wi-Fi list (improves accuracy but consumes more battery); false: does not actively scan. Note: In Device Sensors Only mode, this setting has no effect.

No

false

isWifiActiveScan

Active Wi-Fi scan flag

true: active scan; false: passive scan

Yes

false

setHttpTimeOut(long httpTimeOut)

Sets the network location timeout

Available since v2.0.0. Value in milliseconds. For example, 20000 means a 20-second timeout for network location.

No

30000

httpTimeOut

Timeout in milliseconds

Long integer

Yes

30000

setProtocol(int Protocol)

Sets the network protocol

Available since v2.0.0. AMapLocationProtocol.HTTP for HTTP; AMapLocationProtocol.HTTPS for HTTPS.

No

AMapLocationProtocol.HTTP

Protocol

Protocol type

Integer: HTTP or HTTPS

Yes

AMapLocationProtocol.HTTP

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.

Name

type

Meaning

Rule Description

getLatitude()

double

Latitude

Available since v2.0.0. Returns the latitude of the location.

getLongitude()

double

Longitude

Available since v2.0.0. Returns the longitude of the location.

getAccuracy()

float

Accuracy (meters)

Available since v2.0.0. Returns the accuracy of the location in meters.

getAltitude()

double

Altitude

Available since v2.0.0. Returns the altitude information.

getSpeed()

float

Speed (m/s)

Available since v2.0.0. Returns the speed in meters per second.

getBearing()

float

Bearing

Available since v2.0.0. Returns the bearing information.

getBuildingId()

String

Indoor building ID

Available since v3.2.0. Returns the building ID for indoor positioning.

getFloor()

String

Indoor floor

Available since v3.2.0. Returns the floor for indoor positioning.

getAddress()

String

Address description

Available since v2.0.0. Returns the address description. Not available in Device Sensors Only mode.

getCountry()

String

Country

Available since v2.0.0. Returns the country name. Not available in Device Sensors Only mode.

getProvince()

String

Province

Available since v2.0.0. Returns the province name. Not available in Device Sensors Only mode.

getCity()

String

City

Available since v2.0.0. Returns the city name. Not available in Device Sensors Only mode.

getDistrict()

String

District

Available since v2.0.0. Returns the district name. Not available in Device Sensors Only mode.

getStreet()

String

Street

Available since v2.3.0. Returns the street name. Not available in Device Sensors Only mode.

getStreetNum()

String

Street number

Available since v2.3.0. Returns the street number. Not available in Device Sensors Only mode.

getCityCode()

String

City code

Available since v2.0.0. Returns the city code. Not available in Device Sensors Only mode.

getAdCode()

String

Area code (adcode)

Available since v2.0.0. Returns the area code. Not available in Device Sensors Only mode.

getPoiName()

String

POI name

Available since v2.0.0. Returns the name of the nearest POI. Not available in Device Sensors Only mode.

getAoiName()

String

AOI name

Available since v2.4.0. Returns the name of the nearest AOI. Not available in Device Sensors Only mode.

getGpsAccuracyStatus()

int

GPS accuracy status

Available since v3.1.0. Returns the current GPS status. Refer to the constants in the AMapLocation class.

getLocationType()

int

Location source

Available since v2.0.0. Returns the source of the location result. See the Location Type Reference.

getLocationDetail()

String

Location detail

Available since v2.0.0. Returns detailed location information for troubleshooting.

getErrorInfo()

String

Error description

Available since v2.0.0. Returns a description of the location error. See the Error Code Reference.

getErrorCode()

String

Error code

Available since v2.0.0. Returns the error code for the location failure. See the Error Code 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.