赞
踩
最近在做获取用户当前定位信息的时候,发现uniapp官方提供的uni.getLocation(OBJECT)兼容性并不是特别好,光注意事项都是密密麻麻一大堆,在实际使用场景下,效果并不理想,也不是很稳定。于是便重新封装了一下腾讯地图的一些东西,提高了下兼容度!下边我会把我用的封装思路逻辑给大家一一讲解。
完整代码可私信我我发给你
(可以找我要哈!!)
import './geolocation.min.js' init() { if (origin.indexOf('https') === -1) { uni.hideLoading() uni.showToast({ title: '当前环境无法获取定位信息', icon: 'none', duration: 2000, }); throw '请在 https 环境中使用本插件' } if (!navigator || !navigator.geolocation) { uni.hideLoading() uni.showToast({ title: '当前环境无法获取定位信息', icon: 'none', duration: 2000, }); throw '地理位置服务不可用' } const options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }; return new Promise((resolve, rejace) => { navigator.geolocation.getCurrentPosition((res) => { this.myMap = new qq.maps.Geolocation("你的key", "地图标点"); resolve(this) }, rejace, options) }) },
code 1 表示用户拒绝授权 code 3 未获取到地址信息,可能是设备没有开启定位服务或者系统没有给浏览器定位权限
【H5】 经纬度位置获取navigator.geolocation.getCurrentPosition
navigator.geolocation.getCurrentPosition(function(){
})
参数说明:
经度 : coords.longitude
纬度 : coords.latitude
准确度 : coords.accuracy
海拔 : coords.altitude
海拔准确度 : coords.altitudeAcuracy
行进方向 : coords.heading
地面速度 : coords.speed
请求的时间: new Date(position.timestamp)
getLocation() {
return new Promise((resolve, reject) => {
this.myMap.getLocation(res => {
resolve(res)
}, err => {
reject(err)
})
})
},
<get_location ref='muLocation'></get_location> import getLocation from '@/componentss/getlocation.vue' components: { getLocation, } locationRef: null, onLoad() { //初始化权限,提示用户授权以及重新获取权限 this.$nextTick(() => { uni.showLoading({ title: '定位组件加载中...', mask: true }) this.$refs.muLocation.init().then(location => { this.locationRef = location this.getLocationl(); uni.hideLoading() }, err => { uni.hideLoading() if (err.code === 1) { uni.showModal({ title: '获取定位权限失败', content: '你拒绝了位置授权服务。请允许当前页面获取定位授权,后刷新页面。' }) } else { uni.showModal({ title: '获取定位权限失败', content: '请确定手机定位已打开,并且当前浏览器允许获取定位,开启后请刷新页面。' }) } }) }) }, methods: { // 获取精准定位 getLocationl() { let that = this if (!that.locationRef) return uni.showToast({ title: '未授权位置获取', icon: 'none' }) that.locationRef.getLocation() .then(res => { console.oog(res) //这里面写你自己的逻辑 res即为详细定位信息 that.valiFormData.latitude = res.lat; //纬度 that.valiFormData.longitude = res.lng; //经度 that.valiFormData.areaNum = res.adcode;//市区code that.valiFormData.areaNumName = res.city;//市区 }) }, }
以上便是基于uni-app框架开发,使用Promise进行异步请求和结果返回,封装的H5获取当前详细定位信息组件希望大家一起交流。
启发来源于何木木大佬
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。