harmony 鸿蒙@ohos.geoLocationManager (Geolocation Manager)

2022-12-22 浏览 (1021)

@ohos.geoLocationManager (Geolocation Manager)

The geoLocationManager module provides location services such as Global Navigation Satellite System (GNSS)-based positioning, network positioning, geofencing, as well as geocoding and reverse geocoding.

NOTE

The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Applying for Permissions

Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below.

The system provides the following location permissions:

  • ohos.permission.LOCATION

  • ohos.permission.APPROXIMATELY_LOCATION

  • ohos.permission.LOCATION_IN_BACKGROUND

If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking:

API versions earlier than 9: Apply for ohos.permission.LOCATION.

API version 9 and later: Apply for ohos.permission.APPROXIMATELY_LOCATION, or apply for ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION. Note that ohos.permission.LOCATION cannot be applied for separately.

API VersionLocation PermissionPermission Application ResultLocation Accuracy
Earlier than 9ohos.permission.LOCATIONSuccessLocation accurate to meters
9 and laterohos.permission.LOCATIONFailureNo location obtained
9 and laterohos.permission.APPROXIMATELY_LOCATIONSuccessLocation accurate to 5 kilometers
9 and laterohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATIONSuccessLocation accurate to meters

If your application needs to access the device location information when running in the background, it must be configured to be able to run in the background and be granted the ohos.permission.LOCATION_IN_BACKGROUND permission. In this way, the system continues to report device location information after your application moves to the background.

You can declare the required permission in your application's configuration file. For details, see Access Control (Permission) Development.

Modules to Import

import geoLocationManager from '@ohos.geoLocationManager';

ReverseGeoCodeRequest

Defines a reverse geocoding request.

System capability: SystemCapability.Location.Location.Geocoder

NameTypeReadableWritableDescription
localestringYesYesLanguage used for the location description. zh indicates Chinese, and en indicates English.
latitudenumberYesYesLatitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from -90 to 90.
longitudenumberYesYesLongitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from -180 to 180.
maxItemsnumberYesYesMaximum number of location records to be returned. The specified value must be greater than or equal to 0. A value smaller than 10 is recommended.

GeoCodeRequest

Defines a geocoding request.

System capability: SystemCapability.Location.Location.Geocoder

NameTypeReadableWritableDescription
localestringYesYesLanguage used for the location description. zh indicates Chinese, and en indicates English.
descriptionstringYesYesLocation description, for example, No. xx, xx Road, Pudong New District, Shanghai.
maxItemsnumberYesYesMaximum number of location records to be returned. The specified value must be greater than or equal to 0. A value smaller than 10 is recommended.
minLatitudenumberYesYesMinimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges. The value ranges from -90 to 90.
minLongitudenumberYesYesMinimum longitude. The value ranges from -180 to 180.
maxLatitudenumberYesYesMaximum latitude. The value ranges from -90 to 90.
maxLongitudenumberYesYesMaximum longitude. The value ranges from -180 to 180.

GeoAddress

Defines a geographic location.

System capability: SystemCapability.Location.Location.Geocoder

NameTypeReadableWritableDescription
latitudenumberYesNoLatitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from -90 to 90.
longitudenumberYesNoLongitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from -180 to 180.
localestringYesNoLanguage used for the location description. zh indicates Chinese, and en indicates English.
placeNamestringYesNoLandmark of the location.
countryCodestringYesNoCountry code.
countryNamestringYesNoCountry name.
administrativeAreastringYesNoAdministrative region name.
subAdministrativeAreastringYesNoSub-administrative region name.
localitystringYesNoLocality information.
subLocalitystringYesNoSub-locality information.
roadNamestringYesNoRoad name.
subRoadNamestringYesNoAuxiliary road information.
premisesstringYesNoHouse information.
postalCodestringYesNoPostal code.
phoneNumberstringYesNoPhone number.
addressUrlstringYesNoWebsite URL.
descriptionsArray<string>YesNoAdditional descriptions.
descriptionsSizenumberYesNoTotal number of additional descriptions. The specified value must be greater than or equal to 0. A value smaller than 10 is recommended.
isFromMockBooleanYesNoWhether the geographical name is from the mock reverse geocoding function.
System API: This is a system API.

LocationRequest

Defines a location request.

System capability: SystemCapability.Location.Location.Core

NameTypeReadableWritableDescription
priorityLocationRequestPriorityYesYesPriority of the location request. This parameter is effective only when scenario is set to UNSET. If this parameter and scenario are set to UNSET, the attempt to initiate a location request will fail. For details about the value range, see LocationRequestPriority.
scenarioLocationRequestScenarioYesYesScenario of the location request. The priority parameter is effective only when this parameter is set to UNSET. If this parameter and priority are set to UNSET, the attempt to initiate a location request will fail. For details about the value range, see LocationRequestScenario.
timeIntervalnumberYesYesTime interval at which location information is reported, in seconds. The specified value must be greater than or equal to 0. The default value is 1.
distanceIntervalnumberYesYesDistance interval at which location information is reported, in meters. The specified value must be greater than or equal to 0. The default value is 0.
maxAccuracynumberYesYesLocation accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The specified value must be greater than or equal to 0. The default value is 0.

CurrentLocationRequest

Defines the current location request.

System capability: SystemCapability.Location.Location.Core

NameTypeReadableWritableDescription
priorityLocationRequestPriorityYesYesPriority of the location request. This parameter is effective only when scenario is set to UNSET. If this parameter and scenario are set to UNSET, the attempt to initiate a location request will fail. For details about the value range, see LocationRequestPriority.
scenarioLocationRequestScenarioYesYesScenario of the location request. The priority parameter is effective only when this parameter is set to UNSET. If this parameter and priority are set to UNSET, the attempt to initiate a location request will fail. For details about the value range, see LocationRequestScenario.
maxAccuracynumberYesYesLocation accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The specified value must be greater than or equal to 0. The default value is 0.
timeoutMsnumberYesYesTimeout duration, in milliseconds. The minimum value is 1000. The specified value must be greater than or equal to 1000.

SatelliteStatusInfo

Defines the satellite status information.

System capability: SystemCapability.Location.Location.Gnss

NameTypeReadableWritableDescription
satellitesNumbernumberYesNoNumber of satellites. The specified value must be greater than or equal to 0.
satelliteIdsArray<number>YesNoArray of satellite IDs. The specified value must be greater than or equal to 0.
carrierToNoiseDensitysArray<number>YesNoCarrier-to-noise density ratio, that is, cn0. The specified value must be greater than 0.
altitudesArray<number>YesNoSatellite altitude angle information. The value ranges from -90 to 90, in degrees.
azimuthsArray<number>YesNoAzimuth information. The value ranges from 0 to 360, in degrees.
carrierFrequenciesArray<number>YesNoCarrier frequency, in Hz. The specified value must be greater than or equal to 0.

CachedGnssLocationsRequest

Defines a request for reporting cached GNSS locations.

System capability: SystemCapability.Location.Location.Gnss

NameTypeReadableWritableDescription
reportingPeriodSecnumberYesYesInterval for reporting the cached GNSS locations, in milliseconds. The specified value must be greater than 0.
wakeUpCacheQueueFullbooleanYesYestrue: reports the cached GNSS locations to the application when the cache queue is full.
false: discards the cached GNSS locations when the cache queue is full.

Geofence

Defines a GNSS geofence. Currently, only circular geofences are supported.

System capability: SystemCapability.Location.Location.Geofence

NameTypeReadableWritableDescription
latitudenumberYesYesLatitude information. The value ranges from -90 to 90.
longitudenumberYesYesLongitude information. The value ranges from -180 to 180.
radiusnumberYesYesRadius of a circular geofence, in meters. The specified value must be greater than 0.
expirationnumberYesYesExpiration period of a geofence, in milliseconds. The specified value must be greater than 0.

GeofenceRequest

Defines a GNSS geofencing request.

System capability: SystemCapability.Location.Location.Geofence

NameTypeReadableWritableDescription
scenarioLocationRequestScenarioYesYesLocation scenario.
geofenceGeofenceYesYesGeofence information.

LocationCommand

Defines an extended command.

System capability: SystemCapability.Location.Location.Core

NameTypeReadableWritableDescription
scenarioLocationRequestScenarioYesYesLocation scenario.
commandstringYesYesExtended command, in the string format.

Location

Defines a location.

System capability: SystemCapability.Location.Location.Core

NameTypeReadableWritableDescription
latitudenumberYesNoLatitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from -90 to 90.
longitudenumberYesNoLongitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from -180 to 180.
altitudenumberYesNoLocation altitude, in meters.
accuracynumberYesNoLocation accuracy, in meters.
speednumberYesNoSpeed, in m/s.
timeStampnumberYesNoLocation timestamp in the UTC format.
directionnumberYesNoDirection information. The value ranges from 0 to 360, in degrees.
timeSinceBootnumberYesNoLocation timestamp since boot.
additionsArray<string>YesNoAdditional description.
additionSizenumberYesNoNumber of additional descriptions. The specified value must be greater than or equal to 0.
isFromMockBooleanYesNoWhether the location information is from the mock location function.
System API: This is a system API.

ReverseGeocodingMockInfo

Defines the configuration of the mock reverse geocoding function.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

NameTypeReadableWritableDescription
locationReverseGeoCodeRequestYesYesLatitude and longitude information.
geoAddressGeoAddressYesYesGeographical name.

LocationMockConfig

Defines the configuration of the mock location function.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

NameTypeReadableWritableDescription
timeIntervalnumberYesYesTime interval at which mock locations are reported, in seconds.
locationsArray<Location>YesYesArray of mocked locations.

CountryCode

Defines the country code information.

System capability: SystemCapability.Location.Location.Core

NameTypeReadableWritableDescription
countrystringYesNoCountry code.
typeCountryCodeTypeYesNoCountry code source.

LocatingRequiredDataConfig10+

Defines the configuration for obtaining the required data of the location service.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

NameTypeReadableWritableDescription
typeLocatingRequiredDataTypeYesYesType of the required data.
needStartScanbooleanYesYesWhether to initiate scanning.
scanIntervalnumberYesYesScanning interval, in milliseconds. The specified value must be greater than 0. The default value is 10000.
scanTimeoutnumberYesYesScanning timeout interval, in milliseconds. The value ranges from 0 to 600000. The default value is 10000.

LocatingRequiredData10+

Defines the required data of the location service, including the Wi-Fi or Bluetooth scanning result. After obtaining the data, an application can use the data for services such as network positioning.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

NameTypeReadableWritableDescription
wifiDataWifiScanInfoYesNoWi-Fi scanning result.
bluetoothDataBluetoothScanInfoYesNoBluetooth scanning result.

WifiScanInfo10+

Defines the Wi-Fi scanning information, including the SSID, BSSID, and RSSI of the scanned Wi-Fi hotspot.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

NameTypeReadableWritableDescription
ssidstringYesNoService set identifier (SSID) of a Wi-Fi hotspot, in UTF-8 format.
bssidstringYesNoBase station subsystem identifier (BSSID) of a Wi-Fi hotspot.
rssinumberYesNoReceived signal strength indicator (RSSI) of a Wi-Fi hotspot, in dBm.
frequencynumberYesNoFrequency of a Wi-Fi hotspot.
timestampnumberYesNoScanning timestamp.

BluetoothScanInfo10+

Defines the Bluetooth scanning information.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

NameTypeReadableWritableDescription
deviceNamestringYesNoName of a Bluetooth device.
macAddressstringYesNoMAC address of a Bluetooth device.
rssinumberYesNoSignal strength of a Bluetooth device, in dBm.
timestampnumberYesNoScanning timestamp.

LocationRequestPriority

Sets the priority of the location request.

System capability: SystemCapability.Location.Location.Core

NameValueDescription
UNSET0x200Priority unspecified.
If this option is used, LocationRequestPriority is invalid.
ACCURACY0x201Location accuracy.
This policy mainly uses the GNSS positioning technology. In an open area, the technology can achieve the meter-level location accuracy, depending on the hardware performance of the device. However, in a shielded environment, the location accuracy may significantly decrease.
LOW_POWER0x202Power efficiency.
This policy mainly uses the base station positioning, WLAN positioning, and Bluetooth positioning technologies to obtain device location in both indoor and outdoor scenarios. The location accuracy depends on the distribution of surrounding base stations, visible WLANs, and Bluetooth devices and therefore may fluctuate greatly. This policy is recommended and can reduce power consumption when your application does not require high location accuracy or when base stations, visible WLANs, and Bluetooth devices are densely distributed.
FIRST_FIX0x203Fast location preferred. Use this option if you want to obtain a location as fast as possible.
This policy uses the GNSS positioning, base station positioning, WLAN positioning, and Bluetooth positioning technologies simultaneously to obtain the device location in both the indoor and outdoor scenarios. When all positioning technologies provide a location result, the system provides the most accurate location result for your application. It can lead to significant hardware resource consumption and power consumption.

LocationRequestScenario

Sets the scenario of the location request.

System capability: SystemCapability.Location.Location.Core

NameValueDescription
UNSET0x300Scenario unspecified.
If this option is used, LocationRequestScenario is invalid.
NAVIGATION0x301Navigation.
This option is applicable when your application needs to obtain the real-time location of a mobile device outdoors, such as navigation for driving or walking.
In this scenario, GNSS positioning is used to provide location services to ensure the optimal location accuracy of the system.
The location result is reported at a minimum interval of 1 second by default.
TRAJECTORY_TRACKING0x302Trajectory tracking.
This option is applicable when your application needs to record user trajectories, for example, the track recording function of sports applications. In this scenario, the GNSS positioning technology is mainly used to ensure the location accuracy.
The location result is reported at a minimum interval of 1 second by default.
CAR_HAILING0x303Ride hailing.
This option is applicable when your application needs to obtain the current location of a user who is hailing a taxi.
The location result is reported at a minimum interval of 1 second by default.
DAILY_LIFE_SERVICE0x304Daily life services.
This option is applicable when your application only needs the approximate user location for recommendations and push notifications in scenarios such as when the user is browsing news, shopping online, and ordering food.
The location result is reported at a minimum interval of 1 second by default.
NO_POWER0x305Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.

LocationPrivacyType

Defines the privacy statement type.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

NameValueDescription
OTHERS0Other scenarios. Reserved field.
STARTUP1Privacy statement displayed in the startup wizard. The user needs to choose whether to agree with the statement.
CORE_LOCATION2Privacy statement displayed when enabling the location service.

CountryCodeType

Defines the country code source type.

System capability: SystemCapability.Location.Location.Core

NameValueDescription
COUNTRY_CODE_FROM_LOCALE1Country code obtained from the language configuration of the globalization module.
COUNTRY_CODE_FROM_SIM2Country code obtained from the SIM card.
COUNTRY_CODE_FROM_LOCATION3Country code obtained using the reverse geocoding function based on the user's location information.
COUNTRY_CODE_FROM_NETWORK4Country code obtained from the cellular network registration information.

LocatingRequiredDataType10+

Defines the type of the required data of the location service.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

NameValueDescription
WIFI1Wi-Fi scanning information.
BLUETOOTH2Bluetooth scanning information.

geoLocationManager.on('locationChange')

on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void

Subscribes to location change events with a location request initiated.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value locationChange indicates a location change.
requestLocationRequestYesLocation request.
callbackCallback<Location>YesCallback used to receive location change events.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301200Failed to obtain the geographical location.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let requestInfo:geoLocationManager.LocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET, 'timeInterval': 1, 'distanceInterval': 0, 'maxAccuracy': 0};
let locationChange = (location:geoLocationManager.Location):void => {
    console.log('locationChanger: data: ' + JSON.stringify(location));
};
try {
    geoLocationManager.on('locationChange', requestInfo, locationChange);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.off('locationChange')

off(type: 'locationChange', callback?: Callback<Location>): void

Unsubscribes from location change events with the corresponding location request deleted.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value locationChange indicates a location change.
callbackCallback<Location>NoCallback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301200Failed to obtain the geographical location.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let requestInfo:geoLocationManager.LocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET, 'timeInterval': 1, 'distanceInterval': 0, 'maxAccuracy': 0};
let locationChange = (location:geoLocationManager.Location):void => {
  console.log('locationChanger: data: ' + JSON.stringify(location));
};
try {
    geoLocationManager.on('locationChange', requestInfo, locationChange);
    geoLocationManager.off('locationChange', locationChange);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.on('locationEnabledChange')

on(type: 'locationEnabledChange', callback: Callback<boolean>): void

Subscribes to location service status change events.

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value locationEnabledChange indicates a location service status change.
callbackCallback<boolean>YesCallback used to receive location service status change events.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let locationEnabledChange = (state:boolean):void => {
    console.log('locationEnabledChange: ' + JSON.stringify(state));
}
try {
    geoLocationManager.on('locationEnabledChange', locationEnabledChange);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.off('locationEnabledChange')

off(type: 'locationEnabledChange', callback?: Callback<boolean>): void;

Unsubscribes from location service status change events.

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value locationEnabledChange indicates a location service status change.
callbackCallback<boolean>NoCallback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let locationEnabledChange = (state:boolean):void => {
    console.log('locationEnabledChange: state: ' + JSON.stringify(state));
}
try {
    geoLocationManager.on('locationEnabledChange', locationEnabledChange);
    geoLocationManager.off('locationEnabledChange', locationEnabledChange);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.on('cachedGnssLocationsChange')

on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void;

Subscribes to cached GNSS location reports. This API is supported only by certain GNSS chip models. If the required chip model is not available, error code 801 (Capability not supported) will be reported.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value cachedGnssLocationsChange indicates reporting of cached GNSS locations.
requestCachedGnssLocationsRequestYesRequest for reporting cached GNSS location.
callbackCallback<boolean>YesCallback used to receive cached GNSS locations.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301200Failed to obtain the geographical location.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let cachedLocationsCb = (locations:Array<geoLocationManager.Location>):void => {
    console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations));
}
let requestInfo:geoLocationManager.CachedGnssLocationsRequest = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
try {
    geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.off('cachedGnssLocationsChange')

off(type: 'cachedGnssLocationsChange', callback?: Callback<Array<Location>>): void;

Unsubscribes from cached GNSS location reports. This API is supported only by certain GNSS chip models. If the required chip model is not available, error code 801 (Capability not supported) will be reported.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value cachedGnssLocationsChange indicates reporting of cached GNSS locations.
callbackCallback<boolean>NoCallback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301200Failed to obtain the geographical location.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let cachedLocationsCb = (locations:Array<geoLocationManager.Location>):void => {
    console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations));
}
let requestInfo:geoLocationManager.CachedGnssLocationsRequest = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
try {
    geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb);
    geoLocationManager.off('cachedGnssLocationsChange');
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.on('satelliteStatusChange')

on(type: 'satelliteStatusChange', callback: Callback<SatelliteStatusInfo>): void;

Subscribes to GNSS satellite status change events.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value satelliteStatusChange indicates a GNSS satellite status change.
callbackCallback<SatelliteStatusInfo>YesCallback used to receive GNSS satellite status change events.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let gnssStatusCb = (satelliteStatusInfo:geoLocationManager.SatelliteStatusInfo):void => {
    console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo));
}

try {
    geoLocationManager.on('satelliteStatusChange', gnssStatusCb);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.off('satelliteStatusChange')

off(type: 'satelliteStatusChange', callback?: Callback<SatelliteStatusInfo>): void;

Unsubscribes from GNSS satellite status change events.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value satelliteStatusChange indicates a GNSS satellite status change.
callbackCallback<SatelliteStatusInfo>NoCallback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let gnssStatusCb = (satelliteStatusInfo:geoLocationManager.SatelliteStatusInfo):void => {
    console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo));
}
try {
    geoLocationManager.on('satelliteStatusChange', gnssStatusCb);
    geoLocationManager.off('satelliteStatusChange', gnssStatusCb);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.on('nmeaMessage')

on(type: 'nmeaMessage', callback: Callback<string>): void;

Subscribes to GNSS NMEA message change events.

Required permissions: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value nmeaMessage indicates a GNSS NMEA message change.
callbackCallback<string>YesCallback used to receive GNSS NMEA message change events.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let nmeaCb = (str:string):void => {
    console.log('nmeaMessage: ' + JSON.stringify(str));
}

try {
    geoLocationManager.on('nmeaMessage', nmeaCb );
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.off('nmeaMessage')

off(type: 'nmeaMessage', callback?: Callback<string>): void;

Unsubscribes from GNSS NMEA message change events.

Required permissions: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value nmeaMessage indicates a GNSS NMEA message change.
callbackCallback<string>NoCallback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let nmeaCb = (str:string):void => {
    console.log('nmeaMessage: ' + JSON.stringify(str));
}

try {
    geoLocationManager.on('nmeaMessage', nmeaCb);
    geoLocationManager.off('nmeaMessage', nmeaCb);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.on('gnssFenceStatusChange')

on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void;

Subscribes to status change events of the specified geofence. This API is supported only by certain GNSS chip models. If the required chip model is not available, error code 801 (Capability not supported) will be reported.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Geofence

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value gnssFenceStatusChange indicates a geofence status change.
requestGeofenceRequestYesGeofencing request.
wantWantAgentYesWantAgent used to receive geofence (entrance or exit) events.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301600Failed to operate the geofence.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
import BusinessError from "@ohos.base";

let wantAgentInfo:wantAgent.WantAgentInfo = {
    wants: [
        {
            bundleName: "com.example.myapplication",
            abilityName: "EntryAbility",
            action: "action1"
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};

wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
  let requestInfo:geoLocationManager.GeofenceRequest = {'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
  try {
      geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj);
  } catch (err) {
      console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
  }
});

geoLocationManager.off('gnssFenceStatusChange')

off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void;

Unsubscribes from status change events of the specified geofence. This API is supported only by certain GNSS chip models. If the required chip model is not available, error code 801 (Capability not supported) will be reported.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Geofence

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value gnssFenceStatusChange indicates a geofence status change.
requestGeofenceRequestYesGeofencing request.
wantWantAgentYesWantAgent used to receive geofence (entrance or exit) events.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301600Failed to operate the geofence.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import wantAgent from '@ohos.app.ability.wantAgent';
import BusinessError from "@ohos.base";

let wantAgentInfo:wantAgent.WantAgentInfo = {
    wants: [
        {
            bundleName: "com.example.myapplication",
            abilityName: "EntryAbility",
            action: "action1",
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};

wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
  let requestInfo:geoLocationManager.GeofenceRequest = {'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};;
  try {
      geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj);
      geoLocationManager.off('gnssFenceStatusChange', requestInfo, wantAgentObj);
  } catch (err) {
      console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
  }
});

geoLocationManager.on('countryCodeChange')

on(type: 'countryCodeChange', callback: Callback<CountryCode>): void;

Subscribes to country code change events.

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value countryCodeChange indicates a country code change.
callbackCallback<CountryCode>YesCallback used to receive country code change events.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301500Failed to query the area information.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let callback = (code:geoLocationManager.CountryCode):void => {
    console.log('countryCodeChange: ' + JSON.stringify(code));
}

try {
    geoLocationManager.on('countryCodeChange', callback);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.off('countryCodeChange')

off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void;

Unsubscribes from country code change events.

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value countryCodeChange indicates a country code change.
callbackCallback<CountryCode>NoCallback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301500Failed to query the area information.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let callback = (code:geoLocationManager.CountryCode):void => {
    console.log('countryCodeChange: ' + JSON.stringify(code));
}

try {
    geoLocationManager.on('countryCodeChange', callback);
    geoLocationManager.off('countryCodeChange', callback);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.on('locatingRequiredDataChange')10+

on(type: 'locatingRequiredDataChange', config: LocatingRequiredDataConfig, callback: Callback<Array<LocatingRequiredData>>): void;

Subscribes to changes in the required data of the location service, including Wi-Fi and Bluetooth scanning information. An application can then determine whether to enable Wi-Fi and Bluetooth scanning based on the return result.

Required permissions: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value locatingRequiredDataChange indicates a change in the required data of the location service.
configLocatingRequiredDataConfigYesConfiguration for obtaining the required data of the location service.
callbackCallback<Array<LocatingRequiredData>>YesCallback used to receive the required data of the location service.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301800Failed to start WiFi or Bluetooth scanning.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let callback = (code:Array<geoLocationManager.LocatingRequiredData>):void => {
    console.log('locatingRequiredDataChange: ' + JSON.stringify(code));
}
let config:geoLocationManager.LocatingRequiredDataConfig = {'type': 1, 'needStartScan': true, 'scanInterval': 10000};
try {
    geoLocationManager.on('locatingRequiredDataChange', config, callback);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.off('locatingRequiredDataChange')10+

off(type: 'locatingRequiredDataChange', callback?: Callback<Array<LocatingRequiredData>>): void;

Unsubscribes from changes in the required data of the location service and stops Wi-Fi and Bluetooth scanning.

Required permissions: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value locatingRequiredDataChange indicates a change in the required data of the location service.
callbackCallback<Array<LocatingRequiredData>>NoCallback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.

Error codes

For details about the error codes, see Location Error Codes.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let callback = (code:Array<geoLocationManager.LocatingRequiredData>):void => {
    console.log('locatingRequiredDataChange: ' + JSON.stringify(code));
}
let config:geoLocationManager.LocatingRequiredDataConfig = {'type': 1, 'needStartScan': true, 'scanInterval': 10000};
try {
    geoLocationManager.on('locatingRequiredDataChange', config, callback);
    geoLocationManager.off('locatingRequiredDataChange', callback);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getCurrentLocation

getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void

Obtains the current location. This API uses an asynchronous callback to return the result.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
requestCurrentLocationRequestYesLocation request.
callbackAsyncCallback<Location>YesCallback used to receive the current location.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301200Failed to obtain the geographical location.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let requestInfo:geoLocationManager.CurrentLocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0};
let locationChange = (err:BusinessError.BusinessError, location:geoLocationManager.Location):void => {
    if (err) {
        console.log('locationChanger: err=' + JSON.stringify(err));
    }
    if (location) {
        console.log('locationChanger: location=' + JSON.stringify(location));
    }
};

try {
    geoLocationManager.getCurrentLocation(requestInfo, locationChange);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getCurrentLocation

getCurrentLocation(callback: AsyncCallback<Location>): void;

Obtains the current location. This API uses an asynchronous callback to return the result.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<Location>YesCallback used to receive the current location.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301200Failed to obtain the geographical location.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let locationChange = (err:BusinessError.BusinessError, location:geoLocationManager.Location) => {
    if (err) {
        console.log('locationChanger: err=' + JSON.stringify(err));
    }
    if (location) {
        console.log('locationChanger: location=' + JSON.stringify(location));
    }
};

try {
    geoLocationManager.getCurrentLocation(locationChange);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getCurrentLocation

getCurrentLocation(request?: CurrentLocationRequest): Promise<Location>

Obtains the current location. This API uses a promise to return the result.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
requestCurrentLocationRequestNoLocation request.

Return value

NameTypeMandatoryDescription
Promise<Location>LocationNAPromise used to return the current location.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301200Failed to obtain the geographical location.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let requestInfo:geoLocationManager.CurrentLocationRequest = {'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX, 'scenario': geoLocationManager.LocationRequestScenario.UNSET,'maxAccuracy': 0};
try {
    geoLocationManager.getCurrentLocation(requestInfo).then((result) => {
        console.log('current location: ' + JSON.stringify(result));
    })  
    .catch((error:number) => {
        console.log('promise, getCurrentLocation: error=' + JSON.stringify(error));
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getLastLocation

getLastLocation(): Location

Obtains the last location.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Core

Return value

NameTypeMandatoryDescription
LocationLocationNALocation information.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301200Failed to obtain the geographical location.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    let location = geoLocationManager.getLastLocation();
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.isLocationEnabled

isLocationEnabled(): boolean

Checks whether the location service is enabled.

System capability: SystemCapability.Location.Location.Core

Return value

NameTypeMandatoryDescription
booleanbooleanNAResult indicating whether the location service is enabled.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    let locationEnabled = geoLocationManager.isLocationEnabled();
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.enableLocation

enableLocation(callback: AsyncCallback<void>): void;

Enables the location service. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_SECURE_SETTINGS

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to receive the error message.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.enableLocation((err, data) => {
        if (err) {
            console.log('enableLocation: err=' + JSON.stringify(err));
        }
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.enableLocation

enableLocation(): Promise<void>

Enables the location service. This API uses a promise to return the result.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_SECURE_SETTINGS

System capability: SystemCapability.Location.Location.Core

Return value

NameTypeMandatoryDescription
Promise<void>voidNAPromise used to return the error message.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.enableLocation().then((result) => {
        console.log('promise, enableLocation succeed');
    })
    .catch((error:number) => {
        console.log('promise, enableLocation: error=' + JSON.stringify(error));
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.disableLocation

disableLocation(): void;

Disables the location service.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_SECURE_SETTINGS

System capability: SystemCapability.Location.Location.Core

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.disableLocation();
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getAddressesFromLocation

getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void

Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Location.Location.Geocoder

Parameters

NameTypeMandatoryDescription
requestReverseGeoCodeRequestYesReverse geocoding request.
callbackAsyncCallback<Array<GeoAddress>>YesCallback used to receive the reverse geocoding result.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301300Reverse geocoding query failed.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let reverseGeocodeRequest:geoLocationManager.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
try {
    geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
        if (err) {
            console.log('getAddressesFromLocation: err=' + JSON.stringify(err));
        }
        if (data) {
            console.log('getAddressesFromLocation: data=' + JSON.stringify(data));
        }
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getAddressesFromLocation

getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>;

Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result.

System capability: SystemCapability.Location.Location.Geocoder

Parameters

NameTypeMandatoryDescription
requestReverseGeoCodeRequestYesReverse geocoding request.

Return value

NameTypeMandatoryDescription
Promise<Array<GeoAddress>>Array<GeoAddress>NAPromise used to return the reverse geocoding result.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301300Reverse geocoding query failed.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let reverseGeocodeRequest:geoLocationManager.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
try {
    geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => {
        console.log('getAddressesFromLocation: ' + JSON.stringify(data));
    })
    .catch((error:number) => {
        console.log('promise, getAddressesFromLocation: error=' + JSON.stringify(error));
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getAddressesFromLocationName

getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void

Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.Location.Location.Geocoder

Parameters

NameTypeMandatoryDescription
requestGeoCodeRequestYesGeocoding request.
callbackAsyncCallback<Array<GeoAddress>>YesCallback used to receive the geocoding result.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301400Geocoding query failed.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let geocodeRequest:geoLocationManager.GeoCodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
try {
    geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => {
        if (err) {
            console.log('getAddressesFromLocationName: err=' + JSON.stringify(err));
        }
        if (data) {
            console.log('getAddressesFromLocationName: data=' + JSON.stringify(data));
        }
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getAddressesFromLocationName

getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>>

Converts geographic description into coordinates through geocoding. This API uses a promise to return the result.

System capability: SystemCapability.Location.Location.Geocoder

Parameters

NameTypeMandatoryDescription
requestGeoCodeRequestYesGeocoding request.

Return value

NameTypeMandatoryDescription
Promise<Array<GeoAddress>>Array<GeoAddress>NAPromise used to return the geocoding result.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301400Geocoding query failed.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let geocodeRequest:geoLocationManager.GeoCodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
try {
    geoLocationManager.getAddressesFromLocationName(geocodeRequest).then((result) => {
        console.log('getAddressesFromLocationName: ' + JSON.stringify(result));
    })
    .catch((error:number) => {
        console.log('promise, getAddressesFromLocationName: error=' + JSON.stringify(error));
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.isGeocoderAvailable

isGeocoderAvailable(): boolean;

Obtains the (reverse) geocoding service status.

System capability: SystemCapability.Location.Location.Geocoder

Return value

NameTypeMandatoryDescription
booleanbooleanNAResult indicating whether the (reverse) geocoding service is available.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    let isAvailable = geoLocationManager.isGeocoderAvailable();
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getCachedGnssLocationsSize

getCachedGnssLocationsSize(callback: AsyncCallback<number>): void;

Obtains the number of cached GNSS locations. This API is supported only by certain GNSS chip models. If the required chip model is not available, error code 801 (Capability not supported) will be reported.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback used to receive the number of cached GNSS locations.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.getCachedGnssLocationsSize((err, size) => {
        if (err) {
            console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err));
        }
        if (size) {
            console.log('getCachedGnssLocationsSize: size=' + JSON.stringify(size));
        }
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getCachedGnssLocationsSize

getCachedGnssLocationsSize(): Promise<number>;

Obtains the number of cached GNSS locations. This API is supported only by certain GNSS chip models. If the required chip model is not available, error code 801 (Capability not supported) will be reported.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Gnss

Return value

NameTypeMandatoryDescription
Promise<number>numberNAPromise used to return the number of cached GNSS locations.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.getCachedGnssLocationsSize().then((result) => {
        console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result));
    }) 
    .catch((error:number) => {
        console.log('promise, getCachedGnssLocationsSize: error=' + JSON.stringify(error));
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.flushCachedGnssLocations

flushCachedGnssLocations(callback: AsyncCallback<void>): void;

Obtains all cached GNSS locations and clears the GNSS cache queue. This API is supported only by certain GNSS chip models. If the required chip model is not available, error code 801 (Capability not supported) will be reported.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to receive the error message.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301200Failed to obtain the geographical location.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.flushCachedGnssLocations((err, result) => {
        if (err) {
            console.log('flushCachedGnssLocations: err=' + JSON.stringify(err));
        }
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.flushCachedGnssLocations

flushCachedGnssLocations(): Promise<void>;

Obtains all cached GNSS locations and clears the GNSS cache queue. This API is supported only by certain GNSS chip models. If the required chip model is not available, error code 801 (Capability not supported) will be reported.

Permission required: ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Gnss

Return value

NameTypeMandatoryDescription
Promise<void>voidNAPromise used to receive the error code.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.
3301200Failed to obtain the geographical location.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.flushCachedGnssLocations().then((result) => {
        console.log('promise, flushCachedGnssLocations success');
    })
    .catch((error:number) => {
        console.log('promise, flushCachedGnssLocations: error=' + JSON.stringify(error));
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.sendCommand

sendCommand(command: LocationCommand, callback: AsyncCallback<void>): void;

Sends an extended command to the location subsystem.

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
commandLocationCommandYesExtended command (string) to be sent.
callbackAsyncCallback<void>YesCallback used to receive the error code.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let requestInfo:geoLocationManager.LocationCommand = {'scenario': 0x301, 'command': "command_1"};
try {
    geoLocationManager.sendCommand(requestInfo, (err, result) => {
        if (err) {
            console.log('sendCommand: err=' + JSON.stringify(err));
        }
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.sendCommand

sendCommand(command: LocationCommand): Promise<void>;

Sends an extended command to the location subsystem.

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
commandLocationCommandYesExtended command (string) to be sent.

Return value

NameTypeMandatoryDescription
Promise<void>voidNAPromise used to receive the error code.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let requestInfo:geoLocationManager.LocationCommand = {'scenario': 0x301, 'command': "command_1"};
try {
    geoLocationManager.sendCommand(requestInfo).then((result) => {
        console.log('promise, sendCommand success');
    })  
    .catch((error:number) => {
        console.log('promise, sendCommand: error=' + JSON.stringify(error));
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getCountryCode

getCountryCode(callback: AsyncCallback<CountryCode>): void;

Obtains the current country code.

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<CountryCode>YesCallback used to receive the country code.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301500Failed to query the area information.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.getCountryCode((err, result) => {
        if (err) {
            console.log('getCountryCode: err=' + JSON.stringify(err));
        }
        if (result) {
            console.log('getCountryCode: result=' + JSON.stringify(result));
        }
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getCountryCode

getCountryCode(): Promise<CountryCode>;

Obtains the current country code.

System capability: SystemCapability.Location.Location.Core

Return value

NameTypeMandatoryDescription
Promise<CountryCode>CountryCodeNAPromise used to receive the country code.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301500Failed to query the area information.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.getCountryCode()
    .then((result) => {
        console.log('promise, getCountryCode: result=' + JSON.stringify(result));
    })
    .catch((error:number) => {
        console.log('promise, getCountryCode: error=' + JSON.stringify(error));
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.enableLocationMock

enableLocationMock(): void;

Enables the mock location function.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.enableLocationMock();
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.disableLocationMock

disableLocationMock(): void;

Disables the mock location function.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.disableLocationMock();
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.setMockedLocations

setMockedLocations(config: LocationMockConfig): void;

Sets the mock location information. The mock locations will be reported at the interval specified in this API.

This API can be invoked only after geoLocationManager.enableLocationMock is called.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
configLocationMockConfigYesMock location information, including the interval for reporting the mock locations and the array of the mock locations.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.
3301100The location switch is off.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let locations:Array<geoLocationManager.Location> = [
    {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true},
    {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true},
    {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true},
    {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true},
    {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true}
];
let config:geoLocationManager.LocationMockConfig = {"timeInterval": 5, "locations": locations};
try {
    geoLocationManager.enableLocationMock();
    geoLocationManager.setMockedLocations(config);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.enableReverseGeocodingMock

enableReverseGeocodingMock(): void;

Enables the mock reverse geocoding function.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.enableReverseGeocodingMock();
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.disableReverseGeocodingMock

disableReverseGeocodingMock(): void;

Disables the mock geocoding function.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.disableReverseGeocodingMock();
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.setReverseGeocodingMockInfo

setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>): void;

Sets information of the mock reverse geocoding function, including the mapping between a location and geographical name. If the location is contained in the configurations during reverse geocoding query, the corresponding geographical name will be returned.

This API can be invoked only after geoLocationManager.enableReverseGeocodingMock is called.

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
mockInfosArray<ReverseGeocodingMockInfo>YesArray of information of the mock reverse geocoding function, including a location and a geographical name.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let mockInfos:Array<geoLocationManager.ReverseGeocodingMockInfo> = [
    {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "isFromMock": true}},
    {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "isFromMock": true}},
    {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "isFromMock": true}},
    {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "isFromMock": true}},
    {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "isFromMock": true}},
];
try {
    geoLocationManager.enableReverseGeocodingMock();
    geoLocationManager.setReverseGeocodingMockInfo(mockInfos);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.isLocationPrivacyConfirmed

isLocationPrivacyConfirmed(type: LocationPrivacyType): boolean;

Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications.

System API: This is a system API.

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
typeLocationPrivacyTypeYesPrivacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.

Return value

NameTypeMandatoryDescription
booleanbooleanNAWhether the user agrees with the privacy statement.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    let isConfirmed = geoLocationManager.isLocationPrivacyConfirmed(1);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.setLocationPrivacyConfirmStatus

setLocationPrivacyConfirmStatus(type: LocationPrivacyType, isConfirmed: boolean): void;

Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications.

System API: This is a system API.

Required permissions: ohos.permission.MANAGE_SECURE_SETTINGS

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
typeLocationPrivacyTypeYesPrivacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.
isConfirmedbooleanYesWhether the user agrees with the privacy statement.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301000Location service is unavailable.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
try {
    geoLocationManager.setLocationPrivacyConfirmStatus(1, true);
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

geoLocationManager.getLocatingRequiredData10+

getLocatingRequiredData(config: LocatingRequiredDataConfig): Promise<Array<LocatingRequiredData>>;

Obtains the required data of the location service. This API uses a promise to return the result.

Required permissions: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION

System capability: SystemCapability.Location.Location.Core

System API: This is a system API.

Parameters

NameTypeMandatoryDescription
configLocatingRequiredDataConfigYesConfiguration for obtaining the required data of the location service.

Return value

NameTypeMandatoryDescription
Promise<Array<LocatingRequiredData>>LocatingRequiredDataNAPromise used to receive the required data of the location service, such as the Wi-Fi and Bluetooth scanning information.

Error codes

For details about the error codes, see Location Error Codes.

IDError Message
3301800Failed to start WiFi or Bluetooth scanning.

Example

import geoLocationManager from '@ohos.geoLocationManager';
import BusinessError from "@ohos.base";
let config:geoLocationManager.LocatingRequiredDataConfig = {'type': 1, 'needStartScan': true, 'scanInterval': 10000};
try {
    geoLocationManager.getLocatingRequiredData(config).then((result) => {
        console.log('getLocatingRequiredData return: ' + JSON.stringify(result));
    })  
    .catch((error:number) => {
        console.log('promise, getLocatingRequiredData: error=' + JSON.stringify(error));
    });
} catch (err) {
    console.error("errCode:" + (err as BusinessError.BusinessError).code + ",errMessage:" + (err as BusinessError.BusinessError).message);
}

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/9ef6514d31454e6287bce229fb362174