地理位置API
地理位置API(Geolocation API)允许用户向web应用提供他们的位置。出于隐私考虑吧,报告地理位置前会先向用户请求许可。
地理位置API是通过调用navigator.geolocation来访问的
- Geolocation.getCurrentPosition(): 获取设备的当前位置
- Geolocation.watchPosition(): 注册一个处理函数,在设备位置发生改变时会自动调用,并返回改变后的位置信息。
对于上述的几种方法,其回调函数最多有三个参数:
- 一个必须的成功的回调函数:如果位置检索成功,则调用该回调函数
- 一个可选的错误回调函数:如果检索失败,则调用该回调函数
- 一个可选的对象:用于提供检索位置数据的选项
腾讯地图定位sdk(lbs.qq.com/webApi/comp…
const mapScriptArr = [
`https://apis.map.qq.com/tools/geolocation/min?key=${this.tMapKey}&referer=myapp`,
];
const promises = mapScriptArr.map((ms) => {
return new Promise((resolve) => {
const mapScript = document.createElement('script');
mapScript.type = 'text/javascript';
mapScript.src = ms;
document.body.appendChild(mapScript);
mapScript.onload = () => {
console.log(ms + 'mapScript 加载完毕');
resolve();
};
});
});
Promise.all(promises)
.then(() => {
this.$nextTick(async () => {
console.timeEnd('init');
console.time('getGeoInfo');
await this.getGeoInfo();
});
})
.catch((e) => {
console.log(e);
});
async getGeoInfo() {
if (navigator.geolocation) {
await this.authorizeGeoInfo()
.then((res) => {
uni.hideLoading();
this.checkShopId = null;
this.$refs?.shopListRef.getShopList();
uni.setStorageSync('hasLocation', 2); // 正常地址
this.location = { longitude: res.lng, latitude: res.lat };
this.getNeedMember();
console.timeEnd('getGeoInfo');
})
.catch((err) => {
uni.hideLoading();
this.$nextTick(() => {
// 非超时情况
if (!err || err.code !== 5) {
this.showShopList = true;
return;
}
// 超时情况处理
this.checkShopId =
getQueryString('itemId') ||
(this.$refs?.shopListRef.shopList.length
? this.$refs?.shopListRef.shopList[0].itemId
: null);
this.getNeedMember();
uni.showToast({
title: '获取地理信息位置超时 ',
icon: 'none',
});
});
uni.setStorageSync('hasLocation', 1); // 拒绝授权
console.timeEnd('getGeoInfo');
});
} else {
this.$nextTick(() => {
this.showShopList = true;
});
uni.setStorageSync('hasLocation', 1); // 拒绝授权
uni.showToast({
title: '获取地理信息位置失败 ',
icon: 'none',
});
console.timeEnd('getGeoInfo');
}
},
// 授权地理信息
authorizeGeoInfo() {
return new Promise((resolve, reject) => {
new qq.maps.Geolocation().getLocation(
(res) => {
if (!res || res.type === 'ip') {
reject(res);
uni.showToast({
title: '获取地理信息位置失败 ',
icon: 'none',
});
} else {
resolve(res);
}
},
(err) => {
reject(err);
}
);
});
},