HarmonyOS位置服务

257 阅读5分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第31天,点击查看活动详情

@ohos.geolocation (位置服务)

使用位置服务的话,首先要做的就是导入

import geolocation from '@ohos.geolocation';

因为位置是敏感数据,所以需要权限。

这个时候就需要在config.JSON或者module.json5中去配置

FA

"reqPermissions": [
  {
  "name": "ohos.permission.LOCATION"
  }
]

Stage

"requestPermissions": [
  {
   "name": "ohos.permission.LOCATION"
  }
]

geolocation.on('locationChange')

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

开启位置变化订阅,并发起定位请求。

然后直接给大家上代码

import geolocation from '@ohos.geolocation';
import app from '@system.app';
import prompt from '@ohos.prompt';
​
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
  
​
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(30)
          .fontWeight(FontWeight.Bold).onClick(()=>{
          var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
          var locationChange = (location) => {
            console.log('locationChanger: data: ' + JSON.stringify(location));
            this.message=JSON.stringify(location);
          };
          geolocation.on('locationChange', requestInfo, locationChange);
​
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

程序运行之后控制台打印信息如下

我们来看一下这个代码

app Log: locationChanger: data: {"accuracy":15,"altitude":0,"direction":0,"latitude":22.550977,"longitude":113.874894,"speed":0,"timeSinceBoot":1049135593650982,"timeStamp":1672198613927}

geolocation.off('locationChange')

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

关闭位置变化订阅,并删除对应的定位请求。,同样需要权限

import geolocation from '@ohos.geolocation';
import app from '@system.app';
import prompt from '@ohos.prompt';
​
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
​
​
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(30)
          .fontWeight(FontWeight.Bold).onClick(()=>{
          var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
          var locationChange = (location) => {
            console.info('位置信息 ' + JSON.stringify(location));
            this.message=JSON.stringify(location);
          };
          geolocation.on('locationChange', requestInfo, locationChange);
          geolocation.off('locationChange', locationChange);
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

geolocation.getCurrentLocation

getCurrentLocation(request?: CurrentLocationRequest) : Promise

获取当前位置,使用Promise方式异步返回结果。

需要权限:ohos.permission.LOCATION

完整代码

import geolocation from '@ohos.geolocation';
​
​
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
​
​
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(30)
          .fontWeight(FontWeight.Bold).onClick(()=>{
          var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0};
          geolocation.getCurrentLocation(requestInfo).then((result) => {
this.message=JSON.stringify(result)
            console.log('current location: ' + JSON.stringify(result));
          });
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

运行之后输出的日志为

{"accuracy":15,"altitude":0,"direction":0,"latitude":22.550977,"longitude":113.874894,"speed":0,"timeSinceBoot":1058231947334283,"timeStamp":1672207710281}

geolocation.isLocationEnabled

isLocationEnabled() : Promise

判断位置服务是否已经开启,使用Promise方式异步返回结果。

需要权限:ohos.permission.LOCATION

系统能力:SystemCapability.Location.Location.Core

import geolocation from '@ohos.geolocation';
​
​
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
​
​
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(30)
          .fontWeight(FontWeight.Bold).onClick(()=>{
          geolocation.isLocationEnabled().then((result) => {
            console.log('promise, isLocationEnabled: ' + result);
            this.message=JSON.stringify(result)
          });
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

运行之后,控制台输出true

geolocation.getAddressesFromLocation

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

调用逆地理编码服务,将坐标转换为地理描述,使用Promise方式异步返回结果。

需要权限:ohos.permission.LOCATION

系统能力:SystemCapability.Location.Location.Geocoder

完整代码

import geolocation from '@ohos.geolocation';
​
​
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
​
​
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(30)
          .fontWeight(FontWeight.Bold).onClick(()=>{
          var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
          geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => {
            console.log('getAddressesFromLocation: ' + JSON.stringify(data));
            this.message=JSON.stringify(data)
          });
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

运行之后控制台打印

4-22635/com.jianguo.myapplication D 03B00/JSApp: app Log: getAddressesFromLocation: [{"addressUrl":"","administrativeArea":"上海市","countryCode":"CN","countryName":"中国","descriptions":["上海市青浦区青昆路上海龙鼎苗木培育中心"],"descriptionsSize":0,"latitude":31.121888,"locale":"zh_CN","locality":"上海市","longitude":121.105397,"phoneNumber":"","placeName":"青昆路上海龙鼎苗木培育中心","postalCode":"","premises":"","roadName":"","subAdministrativeArea":"","subLocality":"青浦区","subRoadName":""}]

这个就可以拿出具体的字段去用于快递等业务。

geolocation.getAddressesFromLocationName

getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array>

调用地理编码服务,将地理描述转换为具体坐标,使用Promise方式异步返回结果。

需要权限:ohos.permission.LOCATION

系统能力:SystemCapability.Location.Location.Geocoder

import geolocation from '@ohos.geolocation';
​
​
@Entry
@Component
struct Index {
  @State message: string = 'Hello World'
​
​
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(30)
          .fontWeight(FontWeight.Bold).onClick(()=>{
          var geocodeRequest = {"description": "深圳市宝安区甲岸南路易尚科技大厦", "maxItems": 1};
          geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => {
            console.log('getAddressesFromLocationName: ' + JSON.stringify(result));
            this.message= JSON.stringify(result)
          });
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

输出的日志为

[{"addressUrl":"","administrativeArea":"广东省","countryCode":"CN","countryName":"中国","descriptions":["广东省深圳市宝安区甲岸南路"],"descriptionsSize":0,"latitude":22.549868,"locale":"zh_CN","locality":"深圳市","longitude":113.873627,"phoneNumber":"","placeName":"甲岸南路","postalCode":"","premises":"","roadName":"","subAdministrativeArea":"","subLocality":"宝安区","subRoadName":""}]

GeoAddress

地理编码类型。

需要权限:ohos.permission.LOCATION

系统能力:SystemCapability.Location.Location.Geocoder

名称参数类型必填说明
latitudenumber表示纬度信息,正值表示北纬,负值表示南纬。
longitudenumber表示经度信息,正值表示东经,负值表是西经。
localestring表示位置描述信息的语言,“zh”代表中文,“en”代表英文。
placeNamestring表示地区信息。
countryCodestring表示国家码信息。
countryNamestring表示国家信息。
administrativeAreastring表示省份区域信息。
subAdministrativeAreastring表示表示子区域信息。
localitystring表示城市信息。
subLocalitystring表示子城市信息。
roadNamestring表示路名信息。
subRoadNamestring表示子路名信息。
premisesstring表示门牌号信息。
postalCodestring表示邮政编码信息。
phoneNumberstring表示联系方式信息。
addressUrlstring表示位置信息附件的网址信息。
descriptionsArray表示附加的描述信息。
descriptionsSizenumber表示附加的描述信息数量。

CurrentLocationRequest

当前位置信息请求类型。

需要权限:ohos.permission.LOCATION

系统能力:SystemCapability.Location.Location.Core

名称参数类型必填说明
priorityLocationRequestPriority表示优先级信息。
scenarioLocationRequestScenario表示场景信息。
maxAccuracynumber表示精度信息,单位是米。
timeoutMsnumber表示超时时间,单位是毫秒,最小为1000毫秒。

LocationRequestPriority

位置请求中位置信息优先级设置。

名称默认值说明
UNSET0x200表示未设置优先级。
ACCURACY0x201表示精度优先。
LOW_POWER0x202表示低功耗优先。
FIRST_FIX0x203表示快速获取位置优先,如果应用希望快速拿到1个位置,可以将优先级设置为该字段。

LocationRequestScenario

位置请求中定位场景设置。

需要权限:ohos.permission.LOCATION

名称默认值说明
UNSET0x300表示未设置场景信息。
NAVIGATION0x301表示导航场景。
TRAJECTORY_TRACKING0x302表示运动轨迹记录场景。
CAR_HAILING0x303表示打车场景。
DAILY_LIFE_SERVICE0x304表示日常服务使用场景。
NO_POWER0x305表示无功耗功场景,这种场景下不会主动触发定位,会在其他应用定位时,才给当前应用返回位置。