uni-app中如何获取定位
1、在manifest.json配置
/* 小程序特有相关 */
"mp-weixin" : {
"appid" : "wxc4c5aaf4968078f1",
"setting" : {
"urlCheck" : false
},
"usingComponents" : true,
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
},
"requiredPrivateInfos": [
"getLocation",
"onLocationChange"
]
},
以上配置缺一不可
2、所需要获取定位的页面methods方法中
// 用户授权
getAuthorizeInfo(){
uni.authorize({
scope: 'scope.userLocation',
success: () => {
// 允许授权
this.getLocationInfo();
},
fail: () => {
// 拒绝授权
this.openConfirm();
}
})
},
// 获取地理位置
getLocationInfo(){
uni.getLocation({
type: 'wgs84',
success (res) {
const { latitude, longitude} = res; // 在这里的得到的经纬度,需要将经纬度转化为中文地理,(山东省青岛市市南区),调用后端的接口做转化
getUserLocation(`${latitude},${longitude}`).then(res => {
console.log(res, 'res isisii');
})
},
fail: (err) => {
console.log(err, '获取错误')
}
});
},
// 再次获取授权。当用户第一次拒绝后再次请求授权
openConfirm(){
uni.showModal({
title: '请求授权当前位置',
content: '需要获取您的地理位置,请确认授权',
success: (res)=> {
if (res.confirm) {
uni.openSetting();// 打开地图权限设置
} else if (res.cancel) {
uni.showToast({
title: '你拒绝了授权,无法获得周边医院信息',
icon: 'none',
duration: 1000
})
}
}
});
},
粘贴复制代码,即可实现定位