1.uniapp自带uni.getLocation
uni.getLocation(options) @getlocation | uni-app官网
实现思路:uni.getLocation获取经纬度后调用接口获取城市名
优点:方便快捷,直接调用
缺点:关闭定位后延时很久,无法控制定位延迟时间,流程卡顿。获取手机定位权限方法不支持h5
2.百度map
创建BMap.js
- export default {
- init() {
- const BMap_URL = `https://api.map.baidu.com/api?ak=${ baiduAk }&s=1&callback=onBMapCallback`
- return new Promise((reslove, reject)=> {
- if(typeof BMap !== 'undefined') {
- reslove(BMap)
- }
- window.onBMapCallback = function() {
- reslove(BMap)
- }
- let scriptNode = document.createElement('script')
- scriptNode.setAttribute('type', 'text/javascript')
- scriptNode.setAttribute('src', BMap_URL)
- document.body,appendChild(scriptNode)
- })
- }
- }
引入使用:
- import map from '@/pages/plugins/BMap.js'
- map.init().then(BMap=> {
- const locationCity = new BMap.Geolocation()
- locationCity.getCurrentPosition((options)=> {
- let city = options.address.city
- if(!city) {
- city = '北京'
- }
- // store.commit('getlocation', city)
- Vue.prototype.$cityName = city
-
- // 挂载页面
-
- }).catch((e)=> {
-
- })
- })
优点:比较稳健,功能支持群面
缺点:dom拼接百度map降低性能,初始化时慢3秒
3.浏览器内置对象navigator.geolocation
- if(navigator.geolocation) {
- let options = {
- enableHighAccuracy: true, // 默认false, 为true时使用精准定位
- timeout: 5000, // 获取位置最长等待时间,默认不限时间
- maximumAge: 21600000, // 重复获取位置时,多长时间再次获取定位, 这里设置成6h 21600000
- }
- navigator.geolocation.getCurrentPosition(sucCallback, errorCallback, options)
- }
- function sucCallback(position) {
- var cords = position.coords
- getAddressInfo({ }).then(res=> {
- let city = res.data.city
- if(!city) {
- city = '北京'
- }
- // store.commit('getlocation', city)
- Vue.prototype.$cityName = city
-
- // 挂载页面
- })
- }
- function errorCallback(error) {
- var err = error.code
- switch(err) {
- case 0:
- alert('未识别到位置信息')
- break;
- case 1:
- alert('您拒绝了定位权限')
- break;
- case 2:
- alert('地理位置获取失败')
- break;
- case 3:
- alert('定位超市')
- break;
- default:
- //
- }
- // store.commit('getlocation', '北京')
- Vue.prototype.$cityName = '北京'
-
- // 挂载页面
- }
优点:性能好加载快
缺点:仅支持https协议链接,http协议下无法正常定位