1 Star 0 Fork 258

Caoruihong / base_location

forked from OpenHarmony / base_location 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

位置服务组件

简介

移动终端设备已经深入人们日常生活的方方面面,如查看所在城市的天气、新闻轶事、出行打车、旅行导航、运动记录。这些习以为常的活动,都离不开定位用户终端设备的位置。

当用户处于这些丰富的使用场景中时,系统的位置定位能力可以提供实时准确的位置数据。对于开发者,设计基于位置体验的服务,也可以更好的满足用户的需求。

当应用在实现基于设备位置的功能时,如:驾车导航,记录运动轨迹等,可以调用该模块的API接口,完成位置信息的获取

基本概念

位置能力用于确定用户设备在哪里,系统使用位置坐标标示用户设备的位置,并使用多种定位技术提供位置服务,如GNSS定位、基站定位、WLAN/蓝牙定位(基站定位、WLAN/蓝牙定位后续统称“网络定位技术”)。通过这些定位技术,无论用户设备在室内或是户外,都可以准确地确定用户设备的位置。

  • 坐标

    系统以1984年世界大地坐标系统为参考,使用经度、纬度数据描述地球上的一个位置。

  • GNSS定位

    基于全球导航卫星系统,包含:GPS、GLONASS、北斗、Galileo等,通过导航卫星,设备芯片提供的定位算法,来确定设备准确位置。定位过程具体使用哪些定位系统,取决于用户设备的硬件能力。

  • 基站定位

    根据设备当前驻网基站和相邻基站的位置,估算设备当前位置。此定位方式的定位结果精度相对较低,并且需要设备可以访问蜂窝网络。

  • WLAN、蓝牙定位

    根据设备可搜索到的周围WLAN、蓝牙设备位置,估算设备当前位置。此定位方式的定位结果精度依赖设备周围可见的固定WLAN、蓝牙设备的分布,密度较高时,精度也相较与基站定位方式更高,同时也需要设备可以访问网络。

图 1 子系统架构图

目录

/base/location               # 源代码目录结构:
  ├── etc                   # 服务启动配置代码目录
  ├── interfaces            # 接口相关代码目录
  ├── profile               # 服务声明代码目录
  ├── location_common       # 公共代码目录
  ├── location_locator      # 定位服务管理代码目录
  ├── location_gnss         # gnss定位服务代码目录
  ├── location_network      # 网络定位服务代码目录
  ├── location_passive      # 被动定位服务代码目录
  ├── location_geocode      # 地理编码服务代码目录
  ├── test                  # 测试代码目录
  ├── utils                 # 公共工具代码目录

约束

  • 使用设备的位置能力,需要用户进行确认并主动开启位置开关。如果位置开关没有开启,系统不会向任何应用提供位置服务。

  • 设备位置信息属于用户敏感数据,所以即使用户已经开启位置开关,应用在获取设备位置前仍需向用户申请位置访问权限。在用户确认允许后,系统才会向应用提供位置服务。

说明

接口说明

1.获取设备的位置信息,所使用的接口说明如下。

表 1 获取位置信息API功能介绍

接口名 功能描述
on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void 开启位置变化订阅,并发起定位请求。
off(type: 'locationChange', callback?: Callback<Location>) : void 关闭位置变化订阅,并删除对应的定位请求。
on(type: 'locationServiceState', callback: Callback<boolean>) : void 订阅位置服务状态变化。
off(type: 'locationServiceState', callback: Callback<boolean>) : void 取消订阅位置服务状态变化。
on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; 订阅缓存GNSS位置上报。
off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; 取消订阅缓存GNSS位置上报。
on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; 订阅卫星状态信息更新事件。
off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; 取消订阅卫星状态信息更新事件。
on(type: 'nmeaMessageChange', callback: Callback<string>) : void; 订阅GNSS NMEA信息变更上报。
off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; 取消订阅GNSS NMEA信息变更上报。
on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; 添加围栏,并订阅该围栏事件上报。
off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; 删除围栏,并取消订阅该围栏事件。
getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void 获取当前位置,使用callback回调异步返回结果。
getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> 获取当前位置,使用Promise方式异步返回结果。
getLastLocation(callback: AsyncCallback<Location>) : void 获取上一次位置,使用callback回调异步返回结果。
getLastLocation() : Promise<Location> 获取上一次位置,使用Promise方式异步返回结果。
isLocationEnabled(callback: AsyncCallback<boolean>) : void 判断位置服务是否已经打开,使用callback回调异步返回结果。
isLocationEnabled() : Promise<boolean> 判断位置服务是否已经开启,使用Promise方式异步返回结果。
requestEnableLocation(callback: AsyncCallback<boolean>) : void 请求打开位置服务,使用callback回调异步返回结果。
requestEnableLocation() : Promise<boolean> 请求打开位置服务,使用Promise方式异步返回结果。
enableLocation(callback: AsyncCallback<boolean>) : void 打开位置服务,使用callback回调异步返回结果。
enableLocation() : Promise<boolean> 打开位置服务,使用Promise方式异步返回结果。
disableLocation(callback: AsyncCallback<boolean>) : void 关闭位置服务,使用callback回调异步返回结果。
disableLocation() : Promise<boolean> 关闭位置服务,使用Promise方式异步返回结果。
getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; 获取缓存GNSS位置的个数,使用callback回调异步返回结果。
getCachedGnssLocationsSize() : Promise<number>; 获取缓存GNSS位置的个数,使用Promise方式异步返回结果。
flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; 获取所有的GNSS缓存位置,并清空GNSS缓存队列,使用callback回调异步返回结果。
flushCachedGnssLocations() : Promise<boolean>; 获取所有的GNSS缓存位置,并清空GNSS缓存队列,使用Promise方式异步返回结果。
sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; 给位置服务子系统发送扩展命令,使用callback回调异步返回结果。
sendCommand(command: LocationCommand) : Promise<boolean>; 给位置服务子系统发送扩展命令,使用Promise方式异步返回结果。
isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; 查询用户是否同意定位服务的隐私申明,使用callback回调异步返回结果。
isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; 查询用户是否同意定位服务的隐私申明,使用Promise方式异步返回结果。
setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean, callback: AsyncCallback<boolean>) : void; 设置并记录用户是否同意定位服务的隐私申明,使用callback回调异步返回结果。
setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; 设置并记录用户是否同意定位服务的隐私申明,使用Promise方式异步返回结果。

使用说明

获取设备位置信息开发步骤如下:

  1. 应用在使用系统能力前,需要检查是否已经获取用户授权访问设备位置信息。如未获得授权,可以向用户申请需要的位置权限,申请方式请参考。 系统提供的定位权限有:

    • ohos.permission.LOCATION

    • ohos.permission.LOCATION_IN_BACKGROUND

    访问设备的位置信息,必须申请ohos.permission.LOCATION权限,并且获得用户授权。

    如果应用在后台运行时也需要访问设备位置,除了需要将应用声明为允许后台运行外,还必须申请ohos.permission.LOCATION_IN_BACKGROUND权限,这样应用在切入后台之后,系统可以继续上报位置信息。

    开发者可以在应用config.json文件中声明所需要的权限,示例代码如下:

    {
        "module": {
            "reqPermissions": [{
                "name": "ohos.permission.LOCATION",
                "reason": "$string:reason_description",
                "usedScene": {
                    "ability": ["com.myapplication.LocationAbility"],
                    "when": "inuse"
                }, {
                ...
                }
            ]
        }
    }
  2. 导入geolocation模块,所有与基础定位能力相关的功能API,都是通过该模块提供的。

    import geolocation from '@ohos.geolocation';
  3. 实例化LocationRequest对象,用于告知系统该向应用提供何种类型的位置服务,以及位置结果上报的频率。

    方式一:

    为了面向开发者提供贴近其使用场景的API使用方式,系统定义了几种常见的位置能力使用场景,并针对使用场景做了适当的优化处理,应用可以直接匹配使用,简化开发复杂度。系统当前支持场景如下表所示。

        export enum LocationRequestScenario {
             UNSET = 0x300,
             NAVIGATION,
             TRAJECTORY_TRACKING,
             CAR_HAILING,
             DAILY_LIFE_SERVICE,
             NO_POWER,
         }

    表2 定位场景类型说明

    场景名称 常量定义 说明
    导航场景 NAVIGATION 适用于在户外定位设备实时位置的场景,如车载、步行导航。在此场景下,为保证系统提供位置结果精度最优,主要使用GNSS定位技术提供定位服务,结合场景特点,在导航启动之初,用户很可能在室内、车库等遮蔽环境,GNSS技术很难提供位置服务。为解决此问题,我们会在GNSS提供稳定位置结果之前,使用系统网络定位技术,向应用提供位置服务,以在导航初始阶段提升用户体验。
    此场景默认以最小1秒间隔上报定位结果,使用此场景的应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。
    轨迹跟踪场景 TRAJECTORY_TRACKING 适用于记录用户位置轨迹的场景,如运动类应用记录轨迹功能。主要使用GNSS定位技术提供定位服务。
    此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。
    出行约车场景 CAR_HAILING 适用于用户出行打车时定位当前位置的场景,如网约车类应用。
    此场景默认以最小1秒间隔上报定位结果,并且应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。
    生活服务场景 DAILY_LIFE_SERVICE 生活服务场景,适用于不需要定位用户精确位置的使用场景,如新闻资讯、网购、点餐类应用,做推荐、推送时定位用户大致位置即可。
    此场景默认以最小1秒间隔上报定位结果,并且应用至少申请ohos.permission.LOCATION权限,同时获得用户授权。
    无功耗场景 NO_POWER 无功耗场景,适用于不需要主动启动定位业务。系统在响应其他应用启动定位业务并上报位置结果时,会同时向请求此场景的应用程序上报定位结果,当前的应用程序不产生定位功耗。
    此场景默认以最小1秒间隔上报定位结果,并且应用需要申请ohos.permission.LOCATION权限,同时获得用户授权。

    以导航场景为例,实例化方式如下:

    var requestInfo = {'scenario': 0x301, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};

    方式二:

    如果定义的现有场景类型不能满足所需的开发场景,系统提供了基本的定位优先级策略类型。

        export enum LocationRequestPriority {
             UNSET = 0x200,
             ACCURACY,
             LOW_POWER,
             FIRST_FIX,
         }

    表3 定位优先级策略类型说明:

    策略类型 常量定义 说明
    定位精度优先策略 ACCURACY 定位精度优先策略主要以GNSS定位技术为主,在开阔场景下可以提供米级的定位精度,具体性能指标依赖用户设备的定位硬件能力,但在室内等强遮蔽定位场景下,无法提供准确的位置服务。
    应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。
    快速定位优先策略 FIRST_FIX 快速定位优先策略会同时使用GNSS定位、基站定位和WLAN、蓝牙定位技术,以便室内和户外场景下,通过此策略都可以获得位置结果,当各种定位技术都有提供位置结果时,系统会选择其中精度较好的结果返回给应用。因为对各种定位技术同时使用,对设备的硬件资源消耗较大,功耗也较大。
    应用必须申请ohos.permission.LOCATION权限,同时获得用户授权。
    低功耗定位优先策略 LOW_POWER 低功耗定位优先策略主要使用基站定位和WLAN、蓝牙定位技术,也可以同时提供室内和户外场景下的位置服务,因为其依赖周边基站、可见WLAN、蓝牙设备的分布情况,定位结果的精度波动范围较大,如果对定位结果精度要求不高,或者使用场景多在有基站、可见WLAN、蓝牙设备高密度分布的情况下,推荐使用,可以有效节省设备功耗。
    应用至少申请ohos.permission.LOCATION权限,同时获得用户授权。

    以定位精度优先策略为例,实例化方式如下:

    var requestInfo = {'priority': 0x201, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
  4. 实例化Callback对象,用于向系统提供位置上报的途径。应用需要自行实现系统定义好的回调接口,并将其实例化。系统在定位成功确定设备的实时位置结果时,会通过该接口上报给应用。应用程序可以在接口的实现中完成自己的业务逻辑。

    var locationChange = (location) => {
      console.log('locationChanger: data: ' + JSON.stringify(location));
    };
  5. 启动定位。

    geolocation.on('locationChange', requestInfo, locationChange);
  6. (可选)结束定位。

    geolocation.off('locationChange', locationChange);

    如果应用使用场景不需要实时的设备位置,可以获取系统缓存的最近一次历史定位结果。

    geolocation.getLastLocation((data) => {
        console.log('getLastLocation: data: ' + JSON.stringify(data));
    });

    此接口的使用需要应用向用户申请ohos.permission.LOCATION权限。

进行坐标和地理编码信息的相互转化开发步骤如下:

说明: GeoConvert需要访问后端服务,请确保设备联网,以进行信息获取。

  1. 导入geolocation模块,所有与(逆)地理编码转化能力相关的功能API,都是通过该模块提供的。

    import geolocation from '@ohos.geolocation';
  2. 获取转化结果。

    • 调用getAddressesFromLocation,坐标转化地理位置信息。

      var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
      geolocation.getAddressesFromLocation(reverseGeocodeRequest, (data) => {
          console.log('getAddressesFromLocation: ' + JSON.stringify(data));
      });

      参考接口API说明,应用可以获得与此坐标匹配的GeoAddress列表,应用可以根据实际使用需求,读取相应的参数数据。

    • 调用getAddressesFromLocationName位置描述转化坐标。

      var geocodeRequest = {"description": "上海市浦东新区xx路xx号", "maxItems": 1};
      geolocation.getAddressesFromLocationName(geocodeRequest, (data) => {
          console.log('getAddressesFromLocationName: ' + JSON.stringify(data));
      });

      参考接口API说明,应用可以获得与位置描述相匹配的GeoAddress列表,其中包含对应的坐标数据,请参考API使用。

      如果需要查询的位置描述可能出现多地重名的请求,可以设置GeoCodeRequest,通过设置一个经纬度范围,以高效地获取期望的准确结果。

相关仓

位置服务子系统

base_location

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS

简介

位置服务子系统提供GNSS定位、网络定位、地理编码、逆地理编码、地理围栏等功能。 展开 收起
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/caoruihong/base_location.git
git@gitee.com:caoruihong/base_location.git
caoruihong
base_location
base_location
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891