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) {
callBack("GPSunauthorized");
} else {
uni.authorize({
scope: 'scope.userLocation',
success() {
uni.getLocation({
type: 'gcj02',
success({
latitude,
longitude
}) {
callBack("Authorized", {
latitude,
longitude
});
}
});
},
fail() {
callBack("WENXINunauthorized");
uni.showModal({
title: '未打开小程序定位',
content: '找不到您的位置,请开启定位',
confirmText: '开启定位',
showCancel: false,
success: (res) => {
if (res.confirm) {
uni.openSetting();
}
}
});
}
});
}
}
})
}
function authorizedPositioningPromise() {
return new Promise((resolve, reject) => {
uni.getSystemInfo({
success({
locationEnabled,
locationAuthorized
}) {
if (!locationEnabled && !locationAuthorized) {
reject("GPSnotOpen");
} else if (locationEnabled && !locationAuthorized) {
reject("GPSauthorization");
} else if (locationEnabled && locationAuthorized) {
uni.authorize({
scope: "scope.userLocation",
success() {
uni.getLocation({
success({
latitude,
longitude
}) {
resolve({
latitude,
longitude
});
}
});
},
fail() {
reject("weixinPositionNotOpen");
}
})
}
},
fail(err) {
let reg = /request:fail/;
if (reg.test(err.errMsg)) {
reject("noNetWork");
} else {
reject("requestTimeOut");
}
}
})
});
}
- 效果图