uniapp中如果我们想要获取用户当前的地理位置(经纬度),我们可以使用uni.getLocation(OBJECT)。
官方文档 : uni.getLocation(OBJECT)
配置
在使用该方法之前我们需要在manifest.json中配置,不然请求数据时会报错,错误原因是在app .json或ext.json中声明没有声明requiredPrivateInfos 字段,即没有添加需要获取地理位置的权限。
mainfest.json添加如下代码进行配置
/* 小程序特有相关 */
"mp-weixin" : {
"appid" : "自己的appid",
"requiredPrivateInfos" : [ "getLocation" ]
},
页面中使用
uni.getLocation({
type: 'wgs84',
success: function (res) {
console.log('当前位置的经度:' + res.longitude);
console.log('当前位置的纬度:' + res.latitude);
}
});
返回结果
用户授权
如果想要通过用户授权来判断用户是否给应用授予定位权限,可以使用
uni.authorize(OBJECT)
官方文档 : uni.authorize(OBJECT)
用户授权配置
"mp-weixin" : {
"appid" : "自己的appid",
"permission" : {
"scope.userLocation" : {
"desc" : "你的位置信息将用于小程序定位"
}
},
"requiredPrivateInfos" : [ "getLocation" ]
},
用户授权页面中使用
uni.authorize({
scope: 'scope.userLocation',
success() {
uni.getLocation({
type: 'wgs84',
success: function (res) {
console.log(res);
console.log('当前位置的经度:' + res.longitude);
console.log('当前位置的纬度:' + res.latitude);
},
fail: function (err) {
console.log(err);
},
});
}
})