Html5定位终极解决方案

2020-04-25 07:34:02易采站长站整理

*/
const getLocation = () => {
return new Promise((resolve, reject) => {
console.log('进入全局获取用户位置方法')
const storageData = uni.getStorageSync('positionData')
const userAgent = getUserAgent()
if (storageData) {
resolve(storageData)
} else {
// 根据环境判断 如果在微信内使用微信sdk 其他使用腾讯地图定位组件
if (userAgent === UA.WECHAT) {
handlerLoadScript(() => {
handleWXSDKCall(window.location.href, 'location').then((res) => {
uni.setStorageSync('positionData', res)
resolve(res)
}).catch(err => {
reject(err)
})
})
} else {
TMap.getLocation().then(res => {
uni.setStorageSync('positionData', res)
resolve(res)
}).catch((err) => {
reject(err)
})
}
}
})
}

export default getLocation

3. 页面调用

3.1 绑定方法到 Vue 原型上


import getLocation from '@/module/utils/getLocation'
Vue.prototype.$getLocation = getLocation

3.2 在页面组件中调用


onShow() {
// 获取位置信息后请求后台接口
this.$getLocation()
.then(res => {
console.warn('首页获取位置成功', res)
this.latitude = res.lat
this.longitude = res.lng
// 这里根据获取到的经纬度请求后台接口...
})
.catch(err => {
console.error('首页获取位置失败', err)
// 错误处理
})
}

总结

遇到的坑以及需要注意的点:

使用微信sdk获取位置信息需要按顺序完成以下步骤:

异步加载微信sdk
通过接口获取配置信息,配置微信sdk
在wx.ready回调中调用方法

必须严格按顺序完成以上的三个步骤,否则是无法调用微信sdk的功能的。

总之,通过这篇文章,可以解决 H5 定位 99% 以上的应用场景。