harmony 鸿蒙@ohos.geolocation (Geolocation)

2022-08-09 浏览 (872)

@ohos.geolocation (Geolocation)

The geolocation module provides a wide array of location services, including GNSS positioning, network positioning, geocoding, reverse geocoding, and geofencing.

NOTE The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. The APIs provided by this module are no longer maintained since API version 9. You are advised to use geoLocationManager.

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.LOCATIONSuccessfulLocation accurate to meters.
9 and laterohos.permission.LOCATIONFailedNo location obtained.
9 and laterohos.permission.APPROXIMATELY_LOCATIONSuccessfulLocation accurate to 5 kilometers.
9 and laterohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATIONSuccessfulLocation 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 geolocation from '@ohos.geolocation';

geolocation.on('locationChange')(deprecated)

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

Registers a listener for location changes with a location request initiated.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.on('locationChange').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

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

Example

import geolocation from '@ohos.geolocation';
let requestInfo:geolocation.LocationRequest = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
let locationChange = (location:geolocation.Location):void => {
    console.log('locationChanger: data: ' + JSON.stringify(location));
};
geolocation.on('locationChange', requestInfo, locationChange);

geolocation.off('locationChange')(deprecated)

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

Unregisters the listener for location changes with the corresponding location request deleted.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.off('locationChange').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

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

Example

import geolocation from '@ohos.geolocation';
let requestInfo:geolocation.LocationRequest = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
let locationChange = (location:geolocation.Location):void => {
    console.log('locationChanger: data: ' + JSON.stringify(location));
};
geolocation.on('locationChange', requestInfo, locationChange);
geolocation.off('locationChange', locationChange);

geolocation.on('locationServiceState')(deprecated)

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

Registers a listener for location service status change events.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.on('locationEnabledChange').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

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

Example

import geolocation from '@ohos.geolocation';
let locationServiceState = (state:boolean):void => {
    console.log('locationServiceState: ' + JSON.stringify(state));
}
geolocation.on('locationServiceState', locationServiceState);

geolocation.off('locationServiceState')(deprecated)

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

Unregisters the listener for location service status change events.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.off('locationEnabledChange').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

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

Example

import geolocation from '@ohos.geolocation';
let locationServiceState = (state:boolean):void => {
    console.log('locationServiceState: state: ' + JSON.stringify(state));
}
geolocation.on('locationServiceState', locationServiceState);
geolocation.off('locationServiceState', locationServiceState);

geolocation.on('cachedGnssLocationsReporting')(deprecated)

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

Registers a listener for cached GNSS location reports.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.on('cachedGnssLocationsChange').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value cachedGnssLocationsReporting indicates reporting of cached GNSS locations.
requestCachedGnssLocationsRequestYesRequest for reporting cached GNSS location.
callbackCallback<Array<Location>>YesCallback used to receive the cached GNSS locations.

Example

import geolocation from '@ohos.geolocation';
let cachedLocationsCb = (locations:Array<geolocation.Location>):void => {
    console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations));
}
let requestInfo:geolocation.CachedGnssLocationsRequest = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb);

geolocation.off('cachedGnssLocationsReporting')(deprecated)

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

Unregisters the listener for cached GNSS location reports.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.off('cachedGnssLocationsChange').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

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

Example

import geolocation from '@ohos.geolocation';
let cachedLocationsCb = (locations:Array<geolocation.Location>):void => {
    console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations));
}
let requestInfo:geolocation.CachedGnssLocationsRequest = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true};
geolocation.on('cachedGnssLocationsReporting', requestInfo, cachedLocationsCb);
geolocation.off('cachedGnssLocationsReporting');

geolocation.on('gnssStatusChange')(deprecated)

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

Registers a listener for GNSS satellite status change events.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.on('satelliteStatusChange').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

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

Example

import geolocation from '@ohos.geolocation';
let gnssStatusCb = (satelliteStatusInfo:geolocation.SatelliteStatusInfo):void => {
    console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo));
}
geolocation.on('gnssStatusChange', gnssStatusCb);

geolocation.off('gnssStatusChange')(deprecated)

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

Unregisters the listener for GNSS satellite status change events.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.off('satelliteStatusChange').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value gnssStatusChange 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.

Example

import geolocation from '@ohos.geolocation';
let gnssStatusCb = (satelliteStatusInfo:geolocation.SatelliteStatusInfo) => {
    console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo));
}
geolocation.on('gnssStatusChange', gnssStatusCb);
geolocation.off('gnssStatusChange', gnssStatusCb);

geolocation.on('nmeaMessageChange')(deprecated)

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

Registers a listener for GNSS NMEA message change events.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.on('nmeaMessage').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

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

Example

import geolocation from '@ohos.geolocation';
let nmeaCb = (str:string):void => {
    console.log('nmeaMessageChange: ' + JSON.stringify(str));
}
geolocation.on('nmeaMessageChange', nmeaCb );

geolocation.off('nmeaMessageChange')(deprecated)

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

Unregisters the listener for GNSS NMEA message change events.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.off('nmeaMessage').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
typestringYesEvent type. The value nmeaMessageChange 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.

Example

import geolocation from '@ohos.geolocation';
let nmeaCb = (str:string):void => {
    console.log('nmeaMessageChange: ' + JSON.stringify(str));
}
geolocation.on('nmeaMessageChange', nmeaCb);
geolocation.off('nmeaMessageChange', nmeaCb);

geolocation.on('fenceStatusChange')(deprecated)

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

Registers a listener for status change events of the specified geofence.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.on('gnssFenceStatusChange').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Geofence

Parameters

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

Example

import geolocation from '@ohos.geolocation';
import wantAgent from '@ohos.app.ability.wantAgent';

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:geolocation.GeofenceRequest = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
  geolocation.on('fenceStatusChange', requestInfo, wantAgentObj);
});

geolocation.off('fenceStatusChange')(deprecated)

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

Unregisters the listener for status change events of the specified geofence.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.off('gnssFenceStatusChange').

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Geofence

Parameters

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

Example

import geolocation from '@ohos.geolocation';
import wantAgent from '@ohos.app.ability.wantAgent';

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:geolocation.GeofenceRequest = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}};
  geolocation.on('fenceStatusChange', requestInfo, wantAgentObj);
  geolocation.off('fenceStatusChange', requestInfo, wantAgentObj);
});

geolocation.getCurrentLocation(deprecated)

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

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

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.getCurrentLocation.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

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

Example

import geolocation from '@ohos.geolocation';
import BusinessError from "@ohos.base"
let requestInfo:geolocation.CurrentLocationRequest = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
let locationChange = (err:BusinessError.BusinessError, location:geolocation.Location) => {
    if (err) {
        console.log('locationChanger: err=' + JSON.stringify(err));
    }
    if (location) {
        console.log('locationChanger: location=' + JSON.stringify(location));
    }
};
geolocation.getCurrentLocation(requestInfo, locationChange);

geolocation.getCurrentLocation(deprecated)

getCurrentLocation(callback: AsyncCallback<Location>): void

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

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.getCurrentLocation.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

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

Example

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

geolocation.getCurrentLocation(deprecated)

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

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

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.getCurrentLocation.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
requestCurrentLocationRequestNoLocation request.

Return value

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

Example

import geolocation from '@ohos.geolocation';
let requestInfo:geolocation.CurrentLocationRequest = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
geolocation.getCurrentLocation(requestInfo).then((result) => {
    console.log('current location: ' + JSON.stringify(result));
});

geolocation.getLastLocation(deprecated)

getLastLocation(callback: AsyncCallback<Location>): void

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

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.getLastLocation.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

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

Example

import geolocation from '@ohos.geolocation';
geolocation.getLastLocation((err, data) => {
    if (err) {
        console.log('getLastLocation: err=' + JSON.stringify(err));
    }
    if (data) {
        console.log('getLastLocation: data=' + JSON.stringify(data));
    }
});

geolocation.getLastLocation(deprecated)

getLastLocation(): Promise<Location>

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

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.getLastLocation.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Return value

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

Example

import geolocation from '@ohos.geolocation';
geolocation.getLastLocation().then((result) => {
    console.log('getLastLocation: result: ' + JSON.stringify(result));
});

geolocation.isLocationEnabled(deprecated)

isLocationEnabled(callback: AsyncCallback<boolean>): void

Checks whether the location service is enabled. This API uses an asynchronous callback to return the result.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.isLocationEnabled.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to receive the location service status.

Example

import geolocation from '@ohos.geolocation';
geolocation.isLocationEnabled((err, data) => {
    if (err) {
        console.log('isLocationEnabled: err=' + JSON.stringify(err));
    }
    if (data) {
        console.log('isLocationEnabled: data=' + JSON.stringify(data));
    }
});

geolocation.isLocationEnabled(deprecated)

isLocationEnabled(): Promise<boolean>

Checks whether the location service is enabled. This API uses a promise to return the result.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.isLocationEnabled.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Return value

NameTypeMandatoryDescription
Promise<boolean>booleanNAPromise used to return the location service status.

Example

import geolocation from '@ohos.geolocation';
geolocation.isLocationEnabled().then((result) => {
    console.log('promise, isLocationEnabled: ' + JSON.stringify(result));
});

geolocation.requestEnableLocation(deprecated)

requestEnableLocation(callback: AsyncCallback<boolean>): void

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

NOTE
This API has been discarded since API version 9. It is recommended that a dialog box be displayed in the application to request the user to go to Settings to enable the location function and specify the scenarios in which the location information will be used in the dialog box.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to receive the location service status.

Example

import geolocation from '@ohos.geolocation';
geolocation.requestEnableLocation((err, data) => {
    if (err) {
        console.log('requestEnableLocation: err=' + JSON.stringify(err));
    }
    if (data) {
        console.log('requestEnableLocation: data=' + JSON.stringify(data));
    }
});

geolocation.requestEnableLocation(deprecated)

requestEnableLocation(): Promise<boolean>

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

NOTE
This API has been discarded since API version 9. It is recommended that a dialog box be displayed in the application to request the user to go to Settings to enable the location function and specify the scenarios in which the location information will be used in the dialog box.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Return value

NameTypeMandatoryDescription
Promise<boolean>booleanNAPromise used to return the location service status.

Example

import geolocation from '@ohos.geolocation';
geolocation.requestEnableLocation().then((result) => {
    console.log('promise, requestEnableLocation: ' + JSON.stringify(result));
});

geolocation.isGeoServiceAvailable(deprecated)

isGeoServiceAvailable(callback: AsyncCallback<boolean>): void

Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.isGeocoderAvailable.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Geocoder

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to receive the (reverse) geocoding service status.

Example

import geolocation from '@ohos.geolocation';
geolocation.isGeoServiceAvailable((err, data) => {
    if (err) {
        console.log('isGeoServiceAvailable: err=' + JSON.stringify(err));
    }
    if (data) {
        console.log('isGeoServiceAvailable: data=' + JSON.stringify(data));
    }
});

geolocation.isGeoServiceAvailable(deprecated)

isGeoServiceAvailable(): Promise<boolean>

Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.isGeocoderAvailable.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Geocoder

Return value

NameTypeMandatoryDescription
Promise<boolean>booleanNAPromise used to return the (reverse) geocoding service status.

Example

import geolocation from '@ohos.geolocation';
geolocation.isGeoServiceAvailable().then((result) => {
    console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result));
});

geolocation.getAddressesFromLocation(deprecated)

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

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

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.getAddressesFromLocation.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Geocoder

Parameters

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

Example

import geolocation from '@ohos.geolocation';
let reverseGeocodeRequest:geolocation.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
    if (err) {
        console.log('getAddressesFromLocation: err=' + JSON.stringify(err));
    }
    if (data) {
        console.log('getAddressesFromLocation: data=' + JSON.stringify(data));
    }
});

geolocation.getAddressesFromLocation(deprecated)

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

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

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.getAddressesFromLocation.

Required permissions: ohos.permission.LOCATION

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.

Example

import geolocation from '@ohos.geolocation';
let reverseGeocodeRequest:geolocation.ReverseGeoCodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => {
    console.log('getAddressesFromLocation: ' + JSON.stringify(data));
});

geolocation.getAddressesFromLocationName(deprecated)

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

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

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.getAddressesFromLocationName.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Geocoder

Parameters

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

Example

import geolocation from '@ohos.geolocation';
let geocodeRequest:geolocation.GeoCodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
    if (err) {
        console.log('getAddressesFromLocationName: err=' + JSON.stringify(err));
    }
    if (data) {
        console.log('getAddressesFromLocationName: data=' + JSON.stringify(data));
    }
});

geolocation.getAddressesFromLocationName(deprecated)

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

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

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.getAddressesFromLocationName.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Geocoder

Parameters

NameTypeMandatoryDescription
requestGeoCodeRequestYesGeocoding request.

Return value

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

Example

import geolocation from '@ohos.geolocation';
let geocodeRequest:geolocation.GeoCodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => {
    console.log('getAddressesFromLocationName: ' + JSON.stringify(result));
});

geolocation.getCachedGnssLocationsSize(deprecated)

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

Obtains the number of cached GNSS locations.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.getCachedGnssLocationsSize.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

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

Example

import geolocation from '@ohos.geolocation';
geolocation.getCachedGnssLocationsSize((err, size) => {
    if (err) {
        console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err));
    }
    if (size) {
        console.log('getCachedGnssLocationsSize: size=' + JSON.stringify(size));
    }
});

geolocation.getCachedGnssLocationsSize(deprecated)

getCachedGnssLocationsSize(): Promise<number>;

Obtains the number of cached GNSS locations.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.getCachedGnssLocationsSize.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

Return value

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

Example

import geolocation from '@ohos.geolocation';
geolocation.getCachedGnssLocationsSize().then((result) => {
    console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result));
});

geolocation.flushCachedGnssLocations(deprecated)

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

Obtains all cached GNSS locations and clears the GNSS cache queue.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.flushCachedGnssLocations.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to receive the operation result.

Example

import geolocation from '@ohos.geolocation';
geolocation.flushCachedGnssLocations((err, result) => {
    if (err) {
        console.log('flushCachedGnssLocations: err=' + JSON.stringify(err));
    }
    if (result) {
        console.log('flushCachedGnssLocations: result=' + JSON.stringify(result));
    }
});

geolocation.flushCachedGnssLocations(deprecated)

flushCachedGnssLocations(): Promise<boolean>;

Obtains all cached GNSS locations and clears the GNSS cache queue.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.flushCachedGnssLocations.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

Return value

NameTypeMandatoryDescription
Promise<boolean>booleanNAPromise used to indicate whether the cached GNSS locations are cleared successfully.

Example

import geolocation from '@ohos.geolocation';
geolocation.flushCachedGnssLocations().then((result) => {
    console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result));
});

geolocation.sendCommand(deprecated)

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

Sends an extended command to the location subsystem.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.sendCommand.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
commandLocationCommandYesExtended command (string) to be sent.
callbackAsyncCallback<boolean>YesCallback used to receive the operation result.

Example

import geolocation from '@ohos.geolocation';
let requestInfo:geolocation.LocationCommand = {'scenario': 0x301, 'command': "command_1"};
geolocation.sendCommand(requestInfo, (err, result) => {
    if (err) {
        console.log('sendCommand: err=' + JSON.stringify(err));
    }
    if (result) {
        console.log('sendCommand: result=' + JSON.stringify(result));
    }
});

geolocation.sendCommand(deprecated)

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

Sends an extended command to the location subsystem.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.sendCommand.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

Parameters

NameTypeMandatoryDescription
commandLocationCommandYesExtended command (string) to be sent.

Return value

NameTypeMandatoryDescription
Promise<boolean>booleanNACallback used to return the operation result.

Example

import geolocation from '@ohos.geolocation';
let requestInfo:geolocation.LocationCommand = {'scenario': 0x301, 'command': "command_1"};
geolocation.sendCommand(requestInfo).then((result) => {
    console.log('promise, sendCommand: ' + JSON.stringify(result));
});

ReverseGeoCodeRequest(deprecated)

Defines a reverse geocoding request.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.ReverseGeoCodeRequest.

Required permissions: ohos.permission.LOCATION

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 value must be greater than or equal to 0. A value smaller than 10 is recommended.

GeoCodeRequest(deprecated)

Defines a geocoding request.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.GeoCodeRequest.

Required permissions: ohos.permission.LOCATION

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 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(deprecated)

Defines a geographic location.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.GeoAddress.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Geocoder

NameTypeReadableWritableDescription
latitude7+numberYesNoLatitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from -90 to 90.
longitude7+numberYesNoLongitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from -180 to 180.
locale7+stringYesNoLanguage used for the location description. zh indicates Chinese, and en indicates English.
placeName7+stringYesNoLandmark of the location.
countryCode7+stringYesNoCountry code.
countryName7+stringYesNoCountry name.
administrativeArea7+stringYesNoAdministrative region name.
subAdministrativeArea7+stringYesNoSub-administrative region name.
locality7+stringYesNoLocality information.
subLocality7+stringYesNoSub-locality information.
roadName7+stringYesNoRoad name.
subRoadName7+stringYesNoAuxiliary road information.
premises7+stringYesNoHouse information.
postalCode7+stringYesNoPostal code.
phoneNumber7+stringYesNoPhone number.
addressUrl7+stringYesNoWebsite URL.
descriptions7+Array<string>YesNoAdditional descriptions.
descriptionsSize7+numberYesNoTotal number of additional descriptions. The value must be greater than or equal to 0. A value smaller than 10 is recommended.

LocationRequest(deprecated)

Defines a location request.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.LocationRequest.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

NameTypeReadableWritableDescription
priorityLocationRequestPriorityYesYesPriority of the location request. For details about the value range, see LocationRequestPriority.
scenarioLocationRequestScenarioYesYesScenario of the location request. For details about the value range, see LocationRequestScenario.
timeIntervalnumberYesYesTime interval at which location information is reported, in seconds. The value must be greater than 0.
distanceIntervalnumberYesYesDistance interval at which location information is reported. The value must be greater than 0, in meters.
maxAccuracynumberYesYesLocation accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled. The value must be greater than 0.

CurrentLocationRequest(deprecated)

Defines the current location request.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.CurrentLocationRequest.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

NameTypeReadableWritableDescription
priorityLocationRequestPriorityYesYesPriority of the location request. For details about the value range, see LocationRequestPriority.
scenarioLocationRequestScenarioYesYesScenario of the location request. 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 value must be greater than 0.
timeoutMsnumberYesYesTimeout duration, in milliseconds. The minimum value is 1000. The value must be greater than or equal to 1000.

SatelliteStatusInfo(deprecated)

Defines the satellite status information.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.SatelliteStatusInfo.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

NameTypeReadableWritableDescription
satellitesNumbernumberYesNoNumber of satellites. The value must be greater than or equal to 0.
satelliteIdsArray<number>YesNoArray of satellite IDs. The value must be greater than or equal to 0.
carrierToNoiseDensitysArray<number>YesNoCarrier-to-noise density ratio, that is, cn0. The 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. The value must be greater than or equal to 0, in Hz.

CachedGnssLocationsRequest(deprecated)

Represents a request for reporting cached GNSS locations.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.CachedGnssLocationsRequest.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Gnss

NameTypeReadableWritableDescription
reportingPeriodSecnumberYesYesInterval for reporting the cached GNSS locations, in milliseconds. The 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(deprecated)

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

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.Geofence.

Required permissions: ohos.permission.LOCATION

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. The value must be greater than 0, in meters.
expirationnumberYesYesExpiration period of a geofence, in milliseconds. The value must be greater than 0.

GeofenceRequest(deprecated)

Represents a GNSS geofencing request.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.GeofenceRequest.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Geofence

NameTypeReadableWritableDescription
priorityLocationRequestPriorityYesYesPriority of the location information.
scenarioLocationRequestScenarioYesYesLocation scenario.
geofenceGeofenceYesYesGeofence information.

LocationCommand(deprecated)

Defines an extended command.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.LocationCommand.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

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

Location(deprecated)

Defines a location.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.Location.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

NameTypeReadableWritableDescription
latitude7+numberYesNoLatitude information. A positive value indicates north latitude, and a negative value indicates south latitude. The value ranges from -90 to 90.
longitude7+numberYesNoLongitude information. A positive value indicates east longitude , and a negative value indicates west longitude . The value ranges from -180 to 180.
altitude7+numberYesNoLocation altitude, in meters.
accuracy7+numberYesNoLocation accuracy, in meters.
speed7+numberYesNoSpeed, in m/s.
timeStamp7+numberYesNoLocation timestamp in the UTC format.
direction7+numberYesNoDirection information. The value ranges from 0 to 360, in degrees.
timeSinceBoot7+numberYesNoLocation timestamp since boot.
additions7+Array<string>YesNoAdditional description.
additionSize7+numberYesNoNumber of additional descriptions. The value must be greater than or equal to 0.

LocationPrivacyType(deprecated)

Defines the privacy statement type.

NOTE
This API is supported since API version 8. This API is deprecated since API version 9. You are advised to use geoLocationManager.LocationPrivacyType.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

NameValueDescription
OTHERS0Other scenarios. Reserved field.
STARTUP1Privacy statement displayed in the startup wizard.
CORE_LOCATION2Privacy statement displayed when enabling the location service.

LocationRequestPriority(deprecated)

Sets the priority of the location request.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.LocationRequestPriority.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

NameValueDescription
UNSET0x200Priority unspecified.
If this option is used, LocationRequestPriority is invalid.
ACCURACY0x201Location accuracy preferred.
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 preferred.
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(deprecated)

Sets the scenario of the location request.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.LocationRequestScenario.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

NameValueDescription
UNSET0x300Scenario unspecified.
If this option is used, LocationRequestScenario is invalid.
NAVIGATION0x301Navigation scenario.
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 scenario.
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 scenario.
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 service scenario.
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 scenario.
This option is applicable when 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.

GeoLocationErrorCode(deprecated)

Enumerates error codes of the location service.

NOTE
This API is deprecated since API version 9. You are advised to use geoLocationManager.

Required permissions: ohos.permission.LOCATION

System capability: SystemCapability.Location.Location.Core

NameValueDescription
INPUT_PARAMS_ERROR7+101Incorrect input parameters.
REVERSE_GEOCODE_ERROR7+102Failed to call the reverse geocoding API.
GEOCODE_ERROR7+103Failed to call the geocoding API.
LOCATOR_ERROR7+104Failed to obtain the location.
LOCATION_SWITCH_ERROR7+105Failed to change the location service switch.
LAST_KNOWN_LOCATION_ERROR7+106Failed to obtain the previous location.
LOCATION_REQUEST_TIMEOUT_ERROR7+107Failed to obtain the location within the specified time.

你可能感兴趣的鸿蒙文章

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/4c70b79e6e824cb5a4275f5047bcc020