546a63e14a
Signed-off-by: liu-binjun <liubinjun@huawei.com> |
||
---|---|---|
etc | ||
figures | ||
interfaces/innerkits | ||
location_common | ||
location_geocode | ||
location_gnss | ||
location_locator | ||
location_network | ||
location_passive | ||
profile | ||
utils | ||
bundle.json | ||
LICENSE | ||
OAT.xml | ||
README.en.md | ||
README.md |
Location
Introduction
People take their mobile devices wherever they go. Mobile devices have become a necessity in people's daily routines, whether it be for looking at the weather forecast, browsing news, hailing a taxi, navigating, or recording data from a workout. All these activities are so much associated with the location services on mobile devices.
With the location awareness capability offered by OpenHarmony, mobile devices will be able to obtain real-time, accurate location data. Building location awareness into your application can also lead to a better contextual experience for application users.
Your application can call location-specific APIs to obtain the location information of a mobile device for offering location-based services such as drive navigation and motion track recording.
Basic Concepts
Location awareness helps determine where a mobile device locates. The system identifies the location of a mobile device with its coordinates, and uses location technologies such as Global Navigation Satellite System GNSS
and network positioning for example, base station positioning or WLAN/Bluetooth positioning
to provide diverse location-based services. These advanced location technologies make it possible to obtain the accurate location of the mobile device, regardless of whether it is indoors or outdoors.
-
Coordinate
A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984.
-
GNSS positioning
GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device.
-
Base station positioning
Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network.
-
WLAN or Bluetooth positioning
WLAN or Bluetooth positioning estimates the current location of a mobile device based on the locations of WLANs and Bluetooth devices that can be discovered by the device. The location accuracy of this technology depends on the distribution of fixed WLAN access points
APs
and Bluetooth devices around the device. A high density of WLAN APs and Bluetooth devices can produce a more accurate location result than base station positioning. This technology also requires access to the network.
Figure 1 Location subsystem architecture
Directory Structure
/base/location # Source code
├── etc # Code for the service startup configuration
├── interfaces # APIs
├── profile # Code for service declaration
├── location_common # Common code
├── location_locator # Location service management code
├── location_gnss # GNSS positioning service code
├── location_network # Network positioning service code
├── location_passive # Passive positioning service code
├── location_geocode # Geocoding service code
├── test # Test code
├── utils # Common utility code
Constraints
Your application can use the location function only after the user has granted the permission and turned on the function. If the location function is off, the system will not provide the location service for any application.
Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information.
Usage
Available APIs
- The following table describes APIs available for obtaining device location information.
Table 1 APIs for obtaining device location information
Interface Name | function description |
---|---|
on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void | Enable location change subscription and initiate a location request. |
off(type: 'locationChange', callback?: Callback<Location>) : void | Disable the location change subscription and delete the corresponding location request. |
on(type: 'locationServiceState', callback: Callback<boolean>) : void | The subscription location service status changes. |
off(type: 'locationServiceState', callback: Callback<boolean>) : void | Unsubscribe from location service status changes. |
on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; | Subscribe to cache GNSS location reporting. |
off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; | Unsubscribe from cached GNSS location reporting. |
on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; | Subscribe to satellite status update events. |
off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; | Unsubscribe from satellite status update events. |
on(type: 'nmeaMessageChange', callback: Callback<string>) : void; | Subscribe to GNSS NMEA information reporting. |
off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; | Unsubscribe to GNSS NMEA information reporting. |
on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Add a fence and subscribe to the event reporting of the fence. |
off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Delete the fence and unsubscribe from the fence event. |
getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void | Obtain the current location and use the callback callback to return the result asynchronously. |
getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> | Obtains the current location and returns the result asynchronously in Promise mode. |
getLastLocation(callback: AsyncCallback<Location>) : void | Obtain the last location and use the callback callback to return the result asynchronously. |
getLastLocation() : Promise<Location> | Obtains the last location and returns the result asynchronously in Promise mode. |
isLocationEnabled(callback: AsyncCallback<boolean>) : void | Check whether the location service is enabled and callback is used to return the result asynchronously. |
isLocationEnabled() : Promise<boolean> | Check whether the location service is enabled and return the result asynchronously in Promise mode. |
requestEnableLocation(callback: AsyncCallback<boolean>) : void | Request to enable the location service and use the callback callback to return the result asynchronously. |
requestEnableLocation() : Promise<boolean> | Request to enable the location service and return the result asynchronously in Promise mode. |
enableLocation(callback: AsyncCallback<boolean>) : void | Enable the location service and use the callback callback to return the result asynchronously. |
enableLocation() : Promise<boolean> | Start the location service and return the result asynchronously in Promise mode. |
disableLocation(callback: AsyncCallback<boolean>) : void | Disable the location service and use the callback callback to return the result asynchronously. |
disableLocation() : Promise<boolean> | Stop the location service and return the result asynchronously in Promise mode. |
getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; | Obtains the number of cached GNSS locations and uses the callback callback to return the result asynchronously. |
getCachedGnssLocationsSize() : Promise<number>; | Obtains the number of cached GNSS locations and returns the result asynchronously in Promise mode. |
flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; | Obtains all GNSS cache locations, clears the GNSS cache queue, and invokes callback to return results asynchronously. |
flushCachedGnssLocations() : Promise<boolean>; | Obtains all GNSS cache locations, clears the GNSS cache queue, and returns results asynchronously in Promise mode. |
sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; | Send an extended command to the location service subsystem and use the callback callback to return the result asynchronously. |
sendCommand(command: LocationCommand) : Promise<boolean>; | Sends extended commands to the location service subsystem and returns results asynchronously in Promise mode. |
isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; | This interface is used to query whether a user agrees with the privacy statement of the LCS service. The callback callback interface is used to return the result asynchronously. |
isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; | This interface is used to query whether a user agrees with the privacy statement of the LCS service. The result is returned asynchronously in Promise mode. |
setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback<boolean>) : void; | Set and record whether the user agrees to the privacy statement of the LCS service and use the callback callback to return the result asynchronously. |
setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; | Set and record whether the user agrees to the privacy statement of the LCS. The result is returned asynchronously in Promise mode. |
Usage Guidelines
Obtaining the device location information:
-
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.
The system provides the following location permissions:
- ohos.permission.LOCATION
- ohos.permission.LOCATION_IN_BACKGROUND
The ohos.permission.LOCATION permission is a must if your application needs to access the device location information.
If your application needs to access the device location information when running on the background, it must be allowed to run on the background in the configuration file and also granted the ohos.permission.LOCATION_IN_BACKGROUND permission. In this way, the system continues to report device location information even when your application moves to the background.
To allow your application to access device location information, you can declare the required permissions in the config.json file of your application. The sample code is as follows:
{ "reqPermissions": [{ "name": "ohos.permission.LOCATION", "reason": "$string:reason_description", "usedScene": { "ability": ["com.myapplication.LocationAbility"], "when": "inuse" }, { ... } ] }
-
Import the geolocation module. All function APIs related to basic location capabilities are provided through this module.
import geolocation from '@ohos.geolocation';
-
Instantiates the LocationRequest object to notify the system of the type of location service to be provided to the application and the frequency of reporting location results.
Method 1:
To better serve your needs for using APIs, the system has categorized APIs into different packages to match your common use cases of the location function. In this way, you can directly use the APIs specific to a certain use case, making application development much easier. The following table lists the use cases currently supported.
Table 3 Common use cases of the location function
The following example instantiates the RequestParam object for navigation:
RequestParam requestParam = new RequestParam(RequestParam.SCENE_NAVIGATION);
Method 2:
If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system.
export enum LocationRequestPriority { UNSET = 0x200, ACCURACY, LOW_POWER, FIRST_FIX, }
Table 4 Location priority policies
The positioning accuracy priority policy is used as an example. The instantiation method is as follows:
var requestInfo = {'priority': 0x201, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
-
Instantiate the Callback object, which is used to provide the system with a location report method. The application needs to implement the callback interface defined by the system and instantiate the interface. The system reports the real-time location result of a device to the application through this interface. An application can complete its own business logic in the implementation of the interface.
var locationChange = (location) => {
console.log('locationChanger: data: ' + JSON.stringify(location));
};
-
Start device location.
geolocation.on('locationChange', requestInfo, locationChange);
-
Optional
Stop device location.geolocation.off('locationChange', locationChange);
If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
geolocation.getLastLocation((data) => { console.log('getLastLocation: data: ' + JSON.stringify(data)); });
To call this method, your application needs to request the ohos.permission.LOCATION permission from the user.
Converting the coordinates and geocoding information:
-
Import the geolocation module. All functional APIs related to the (inverse) geocoding conversion capability are provided through this module.
import geolocation from '@ohos.geolocation';
You can use GeoConvert(Locale locale) to create a GeoConvert instance based on specified parameters, such as the language and region.
-
Obtain the conversion result.
-
Convert coordinates to location information.
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); });
Your application can obtain the GeoAddress list that matches the specified coordinates and then read location information from it. For details, see the API Reference.
-
Convert location information to coordinates.
var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (data) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(data)); });
Your application can obtain the GeoAddress list that matches the specified location information and read coordinates from it. For details, see the API Reference.
-
Repositories Involved
base_location