index.js
import config from '@/config/config'; //腾讯地图key
import QQMapWX from '@/js_sdk/qqmap-wx-jssdk.min.js'; //地图js
export function getLocationInfo() {
return new Promise((resolve) => {
//位置信息默认数据
let location = {
longitude: 0,
latitude: 0,
province: "",
city: "",
area: "",
street: "",
address: "",
};
uni.getLocation({
type: "gcj02",
success(res) {
location.longitude = res.longitude;
location.latitude = res.latitude;
// 腾讯地图Api
const qqmapsdk = new QQMapWX({
key: config.aMapKey
});
//城市地址
qqmapsdk.reverseGeocoder({
location,
success(response) {
let info = response.result;
console.log(info);
location.province = info.address_component.province;
location.city = info.address_component.city;
location.area = info.address_component.district;
location.street = info.address_component.street;
location.address = info.address;
resolve(location);
},
});
},
fail(err) {
console.log(err)
resolve(location);
},
});
});
}
export function getLocation() {
return new Promise((resolve) => {
// #ifdef MP-WEIXIN
// 获取用户是否开启 授权获取当前的地理位置、速度的权限。
uni.getSetting({
success(res) {
console.log(res)
// 如果没有授权
if (!res.authSetting['scope.userLocation']) {
// 则拉起授权窗口
uni.authorize({
scope: 'scope.userLocation',
success() {
console.log('存在同意的授权')
getLocationInfo().then(res => {
resolve(res)
})
},
fail(error) {
//点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
console.log('拒绝授权', error)
uni.showModal({
title: '提示',
content: '为了您更好的服务体验,请同意位置授权',
cancelText: '不授权',
cancelColor: '#999',
confirmText: '授权',
confirmColor: '#f94218',
success(res) {
console.log(res)
if (res.confirm) {
// 选择弹框内授权
uni.openSetting({
success(res) {
if (res.authSetting[
'scope.userLocation'
]) {
getLocationInfo().then(
res => {
resolve(res)
})
} else {
}
}
})
} else if (res.cancel) {
uni.showToast({
title: '您没有同意授权'
});
}
}
})
}
})
} else {
getLocationInfo().then(res => {
resolve(res)
})
}
}
})
// #endif
// #ifndef MP-WEIXIN
getLocationInfo().then(res => {
resolve(res)
})
// #endif
})
}
无判断使用
import {
getLocationInfo
} from '@/utils/index';
getLocationInfo.then(res=>{
console.log(res);
})
判断使用
import {
getLocation
} from '@/utils/index';
getLocation.then(res=>{
console.log(res);
})