uni-app 获取当前的地理位置【uni.getLocation(OBJECT)】
uni-app获取当前的地理位置【uni.getLocation(OBJECT)】在 manifest.json中配置 permission"permission": {"scope.userLocation": {"desc": "你的位置信息将用于小程序位置接口的效果展示"}},在需要的页面写// 获取经纬度uni.authorize({scope: 'scope.userLocation',
·
uni-app获取当前的地理位置【uni.getLocation(OBJECT)】
- 在 manifest.json中配置 permission
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
},
- 在需要的页面写
// 判断地理位置是否授权
function authorizedPositioning( callBack = ()=>{} ){
uni.getSystemInfo({ // 获取系统信息
success(res) {
let locationEnabled = res.locationEnabled; //判断手机定位服务是否开启
let locationAuthorized = res.locationAuthorized; //判断定位服务是否允许微信授权
if (locationEnabled == false || locationAuthorized == false) {
// GPS 未授权
callBack("GPSunauthorized");
} else {
// GPS 已授权 判断微信定位是否授权
uni.authorize({
scope: 'scope.userLocation',
success() {
// GPS已授权 微信定位已授权
uni.getLocation({
type: 'gcj02',
success({
latitude,
longitude
}) {
// latitude; 纬度
// longitude; 经度
callBack("Authorized", {
latitude,
longitude
});
}
});
},
fail() {
// GPS已授权 微信定位未授权
callBack("WENXINunauthorized");
uni.showModal({
title: '未打开小程序定位',
content: '找不到您的位置,请开启定位',
confirmText: '开启定位',
showCancel: false,
success: (res) => {
if (res.confirm) {
uni.openSetting(); // 打开地图权限设置
}
}
});
}
});
}
}
})
}
// 使用promise 判断地理位置是否授权
function authorizedPositioningPromise() {
return new Promise((resolve, reject) => {
uni.getSystemInfo({
success({
locationEnabled,
locationAuthorized
}) {
// locationEnabled 判断手机定位服务是否开启
// locationAuthorized 判断定位服务是否允许微信授权
if (!locationEnabled && !locationAuthorized) {
// GPS未开启 与 GPS未给微信授权定位服务
reject("GPSnotOpen");
} else if (locationEnabled && !locationAuthorized) {
// GPS已开启 与 GPS未给微信授权定位服务
reject("GPSauthorization");
} else if (locationEnabled && locationAuthorized) {
/*
GPS已开启 与 GPS已给微信授权定位服务
判断微信小程序位置信息是否开启
*/
uni.authorize({
scope: "scope.userLocation",
success() {
// 微信小程序位置信息已开启
uni.getLocation({
success({
latitude,
longitude
}) {
// latitude; 纬度
// longitude; 经度
resolve({
latitude,
longitude
});
}
});
},
fail() {
// 微信小程序位置信息未开启
reject("weixinPositionNotOpen");
}
})
}
},
fail(err) {
let reg = /request:fail/;
if (reg.test(err.errMsg)) {
// 无网络
reject("noNetWork");
} else {
// 请求超时'
reject("requestTimeOut");
}
}
})
});
}
- 效果图
更多推荐
已为社区贡献1条内容
所有评论(0)