我们在做功能的时候经常会遇到获取位置的功能那么今天小编和大家详细聊一下
那么这个功能这么做呢? 话不多说 先上官方链接 文档中心 点击直达
1,我们先来获取位置图标
// 获取详细地址位置
LocationButton({
icon: LocationIconStyle.LINES, // 图标
// text: LocationDescription.CURRENT_LOCATION, // 按钮
// buttonType: ButtonType.Normal // 背景位置按钮样式
})
这三个属性我们看看官方文档是怎么说的吧
2,当我们按钮显示出来的时候 我们在给按钮注册点击事件
.onClick((event: ClickEvent, result: LocationButtonOnClickResult) => {
if (result === LocationButtonOnClickResult.SUCCESS) {
// 免去权限申请和权限请求等环节,获得临时授权,获取位置信息授权
this.getCurrentLocationInfo() // 这里封装了一个方法 直接调用就行
} else {
promptAction.showToast({ message: '获取位置信息失败!' })
}
})
下面是封装的方法
// 获取当前位置信息
getCurrentLocationInfo() {
const requestInfo: geoLocationManager.LocationRequest = {
'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
'scenario': geoLocationManager.LocationRequestScenario.UNSET,
'timeInterval': 1,
'distanceInterval': 0,
'maxAccuracy': 0
};
try {
geoLocationManager.getCurrentLocation(requestInfo)
.then((location: geoLocationManager.Location) => {
// promptAction.showToast({ message: JSON.stringify(location) });
// 把经纬度替换成我们真实的度数location.latitude, "longitude": location.longitude
let reverseGeocodeRequest: geoLocationManager.ReverseGeoCodeRequest =
// "latitude": location.latitude, 替换成自己当前的地理位置-经度
// "longitude": location.longitude, 替换成自己当前的地理位置-维度
// "maxItems": 1
{ "latitude": location.latitude, "longitude": location.longitude, "maxItems": 1 };
geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => {
// this.addForm.address 是我自己的后台数据 大家可以替换成自己的接口数据
this.addForm.address = data[0].placeName as string 这里 this.addForm.address
// console.log('getAddressesFromLocation: ' + JSON.stringify(data)); 打印的经度
// promptAction.showToast({ message: JSON.stringify(data) });
})
})
.catch((error: BusinessError) => {
console.error('promise, getAddressesFromLocation: error=' + JSON.stringify(error));
});
} catch (err) {
console.error("errCode:" + JSON.stringify(err));
}
}