1# Location 2 3## Introduction 4 5People 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. 6 7With 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. 8 9Your 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. 10 11**Basic Concepts** 12 13Location 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. 14 15- **Coordinate** 16 17 A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984. 18 19- **GNSS positioning** 20 21 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. 22 23- **Base station positioning** 24 25 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. 26 27- **WLAN or Bluetooth positioning** 28 29 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. 30 31**Figure 1** Location subsystem architecture**<a name="fig4460722185514"></a> 32 33![](figures/location_En-1.png) 34 35## Directory Structure<a name="section161941989596"></a> 36 37``` 38/base/location # Source code of the location subsystem 39├── etc # Code for the service startup configuration 40├── interfaces # APIs 41├── profile # Code for service declaration 42├── location_common # Common code 43├── location_locator # Location service management code 44├── location_gnss # GNSS positioning service code 45├── location_network # Network positioning service code 46├── location_passive # Passive positioning service code 47├── location_geocode # Geocoding service code 48├── test # Test code 49├── utils # Common utility code 50``` 51 52## Constraints<a name="section119744591305"></a> 53 54Your 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. 55 56Since 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. 57 58## Usage 59 60### Available APIs<a name="section1551164914237"></a> 61 62The following table describes APIs available for obtaining device location information. 63 64**Table 1** APIs for obtaining device location information 65| API| Description| 66| -------- | -------- | 67| on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void | Registers a listener for location changes with a location request initiated.| 68| off(type: 'locationChange', callback?: Callback<Location>) : void | Unregisters the listener for location changes with the corresponding location request deleted.| 69| on(type: 'locationServiceState', callback: Callback<boolean>) : void | Registers a listener for location service status change events.| 70| off(type: 'locationServiceState', callback: Callback<boolean>) : void | Unregisters the listener for location service status change events.| 71| on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; | Registers a listener for cached GNSS location reports.| 72| off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; | Unregisters the listener for cached GNSS location reports.| 73| on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; | Registers a listener for satellite status change events.| 74| off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; | Unregisters the listener for satellite status change events.| 75| on(type: 'nmeaMessageChange', callback: Callback<string>) : void; | Registers a listener for GNSS NMEA message change events.| 76| off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; | Unregisters the listener for GNSS NMEA message change events.| 77| on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Registers a listener for status change events of the specified geofence.| 78| off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; | Unregisters the listener for status change events of the specified geofence.| 79| getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void | Obtains the current location. This API uses an asynchronous callback to return the result. | 80| getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> | Obtains the current location. This API uses a promise to return the result. | 81| getLastLocation(callback: AsyncCallback<Location>) : void | Obtains the previous location. This API uses an asynchronous callback to return the result.| 82| getLastLocation() : Promise<Location> | Obtains the previous location. This API uses a promise to return the result. | 83| isLocationEnabled(callback: AsyncCallback<boolean>) : void | Checks whether the location service is enabled. This API uses an asynchronous callback to return the result.| 84| isLocationEnabled() : Promise<boolean> | Checks whether the location service is enabled. This API uses a promise to return the result.| 85| requestEnableLocation(callback: AsyncCallback<boolean>) : void | Requests to enable the location service. This API uses an asynchronous callback to return the result.| 86| requestEnableLocation() : Promise<boolean> | Requests to enable the location service. This API uses a promise to return the result.| 87| enableLocation(callback: AsyncCallback<boolean>) : void | Enables the location service. This API uses an asynchronous callback to return the result.| 88| enableLocation() : Promise<boolean> | Enables the location service. This API uses a promise to return the result.| 89| disableLocation(callback: AsyncCallback<boolean>) : void | Disables the location service. This API uses an asynchronous callback to return the result.| 90| disableLocation() : Promise<boolean> | Disables the location service. This API uses a promise to return the result.| 91| getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; | Obtains the number of cached GNSS locations. This API uses an asynchronous callback to return the result.| 92| getCachedGnssLocationsSize() : Promise<number>; | Obtains the number of cached GNSS locations. This API uses a promise to return the result.| 93| flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses an asynchronous callback to return the result.| 94| flushCachedGnssLocations() : Promise<boolean>; | Obtains all cached GNSS locations and clears the GNSS cache queue. This API uses a promise to return the result.| 95| sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; | Sends extended commands to the location subsystem. This API uses an asynchronous callback to return the result.| 96| sendCommand(command: LocationCommand) : Promise<boolean>; | Sends extended commands to the location subsystem. This API uses a promise to return the result.| 97| isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; | Checks whether a user agrees with the privacy statement of the location service. This API uses an asynchronous callback to return the result.| 98| isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; | Checks whether a user agrees with the privacy statement of the location service. This API uses a promise to return the result.| 99| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback<boolean>) : void; | Sets the user confirmation status for the privacy statement of the location service. This API uses an asynchronous callback to return the result.| 100| setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; | Sets the user confirmation status for the privacy statement of the location service. This API uses a promise to return the result.| 101 102 103### How to Use<a name="section129654513264"></a> 104 105**Obtaining the device location information:** 106 1071. 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. 108 109 The system provides the following location permissions: 110 - ohos.permission.LOCATION 111 112 - ohos.permission.LOCATION_IN_BACKGROUND 113 114 The **ohos.permission.LOCATION** permission is a must if your application needs to access the device location information. 115 116 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. 117 118 You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../application-dev/security/accesstoken-guidelines.md). 119 1202. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. 121 122 ``` 123 import geolocation from '@ohos.geolocation'; 124 ``` 125 1263. Instantiate the **LocationRequest** object. This object provides APIs to notify the system of the location service type and the interval of reporting location information. 127 128 **Method 1:** 129 130 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. 131 132 133 ``` 134 export enum LocationRequestScenario { 135 UNSET = 0x300, 136 NAVIGATION, 137 TRAJECTORY_TRACKING, 138 CAR_HAILING, 139 DAILY_LIFE_SERVICE, 140 NO_POWER, 141 } 142 ``` 143 144 145 **Table 2** Common use cases of the location function 146 147 | Use Case| Constant| Description| 148 | -------- | -------- | -------- | 149 | Navigation| NAVIGATION | 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, the GNSS positioning technology is mainly used to ensure the location accuracy. However, due to its limitations, the technology may be unable to provide the location service when navigation is just started or when the user moves into a shielded environment such as indoors or a garage. To resolve this issue, the system uses the network positioning technology as an alternative to provide the location service for your application until the GNSS can provide stable location results. This helps achieve a smooth navigation experience for users.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| 150 | Trajectory tracking| TRAJECTORY_TRACKING | 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.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| 151 | Ride hailing| CAR_HAILING | Applicable when your application needs to obtain the current location of a user who is hailing a taxi.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| 152 | Life service| DAILY_LIFE_SERVICE | 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.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| 153 | Power efficiency| NO_POWER | Applicable when your application does not proactively start the location service for a higher battery efficiency. 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.<br>By default, the system reports location results at a minimal interval of 1s. To adopt this use case, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| 154 155 The following example instantiates the **RequestParam** object for navigation: 156 157 ``` 158 var requestInfo = {'scenario': 0x301, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; 159 ``` 160 161 **Method 2:** 162 163 If the predefined use cases do not meet your needs, you can also use the basic location priority policies provided by the system. 164 165 166 ``` 167 export enum LocationRequestPriority { 168 UNSET = 0x200, 169 ACCURACY, 170 LOW_POWER, 171 FIRST_FIX, 172 } 173 ``` 174 175 176 **Table 3** Location priority policies 177 178 | Policy| Constant| Description| 179 | -------- | -------- | -------- | 180 | Location accuracy priority| 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.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| 181 | Fast location priority| FAST_FIRST_FIX | 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. This policy can lead to significant hardware resource consumption and power consumption.<br>To use this policy, you must declare the **ohos.permission.LOCATION** permission and obtain users' authorization.| 182 | Power efficiency priority| LOW_POWER | 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.<br>To use this policy, you must declare at least the **ohos.permission.LOCATION** permission and obtain users' authorization.| 183 184 The following example instantiates the **RequestParam** object for the location accuracy priority policy: 185 186 ``` 187 var requestInfo = {'priority': 0x201, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; 188 ``` 189 1904. Instantiate the **Callback** object for the system to report location results. 191 192 Your application needs to implement the callback defined by the system. When the system successfully obtains the real-time location of a device, it will report the location result to your application through the callback interface. Your application can implement the callback interface in such a way to complete your own service logic. 193 194 ``` 195 var locationChange = (location) => { 196 console.log('locationChanger: data: ' + JSON.stringify(location)); 197 }; 198 ``` 199 2005. Start device location. 201 202 ``` 203 geolocation.on('locationChange', requestInfo, locationChange); 204 ``` 205 2066. (Optional) Stop device location. 207 208 ``` 209 geolocation.off('locationChange', locationChange); 210 ``` 211 212 If your application does not need the real-time device location, it can use the last known device location cached in the system instead. 213 214 ``` 215 geolocation.getLastLocation((data) => { 216 console.log('getLastLocation: data: ' + JSON.stringify(data)); 217 }); 218 ``` 219 220 To call this method, your application needs to request the **ohos.permission.LOCATION** permission from the user. 221 222 223 224**Converting the coordinates and geocoding information:** 225 226> **NOTE** 227> 228> The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network. 229 2301. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities. 231 232 ``` 233 import geolocation from '@ohos.geolocation'; 234 ``` 235 2362. Obtain the conversion result. 237 238 - Call **getAddressesFromLocation** to convert coordinates into geographical location information. 239 240 ``` 241 var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; 242 geolocation.getAddressesFromLocation(reverseGeocodeRequest, (data) => { 243 console.log('getAddressesFromLocation: ' + JSON.stringify(data)); 244 }); 245 ``` 246 247 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*. 248 249 - Call **getAddressesFromLocationName** to convert geographic description into coordinates. 250 251 ``` 252 var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; 253 geolocation.getAddressesFromLocationName(geocodeRequest, (data) => { 254 console.log('getAddressesFromLocationName: ' + JSON.stringify(data)); 255 }); 256 ``` 257 258 Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see the *API Reference*. 259 260 To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**. 261 262 263 264## Repositories Involved 265 266Location subsystem 267 268[base_location](https://gitee.com/openharmony/base_location/blob/master/README.en.md) 269