• uniapp中地图定位功能实现的几种方案


    1.uniapp自带uni.getLocation

    uni.getLocation(options) @getlocation | uni-app官网

    实现思路:uni.getLocation获取经纬度后调用接口获取城市名

    优点:方便快捷,直接调用

    缺点:关闭定位后延时很久,无法控制定位延迟时间,流程卡顿。获取手机定位权限方法不支持h5

    2.百度map

    创建BMap.js

    1. export default {
    2. init() {
    3. const BMap_URL = `https://api.map.baidu.com/api?ak=${ baiduAk }&s=1&callback=onBMapCallback`
    4. return new Promise((reslove, reject)=> {
    5. if(typeof BMap !== 'undefined') {
    6. reslove(BMap)
    7. }
    8. window.onBMapCallback = function() {
    9. reslove(BMap)
    10. }
    11. let scriptNode = document.createElement('script')
    12. scriptNode.setAttribute('type', 'text/javascript')
    13. scriptNode.setAttribute('src', BMap_URL)
    14. document.body,appendChild(scriptNode)
    15. })
    16. }
    17. }

    引入使用:

    1. import map from '@/pages/plugins/BMap.js'
    2. map.init().then(BMap=> {
    3. const locationCity = new BMap.Geolocation()
    4. locationCity.getCurrentPosition((options)=> {
    5. let city = options.address.city
    6. if(!city) {
    7. city = '北京'
    8. }
    9. // store.commit('getlocation', city)
    10. Vue.prototype.$cityName = city
    11. // 挂载页面
    12. }).catch((e)=> {
    13. })
    14. })

    优点:比较稳健,功能支持群面   

    缺点:dom拼接百度map降低性能,初始化时慢3秒

    3.浏览器内置对象navigator.geolocation

    1. if(navigator.geolocation) {
    2. let options = {
    3. enableHighAccuracy: true, // 默认false, 为true时使用精准定位
    4. timeout: 5000, // 获取位置最长等待时间,默认不限时间
    5. maximumAge: 21600000, // 重复获取位置时,多长时间再次获取定位, 这里设置成6h 21600000
    6. }
    7. navigator.geolocation.getCurrentPosition(sucCallback, errorCallback, options)
    8. }
    9. function sucCallback(position) {
    10. var cords = position.coords
    11. getAddressInfo({ }).then(res=> {
    12. let city = res.data.city
    13. if(!city) {
    14. city = '北京'
    15. }
    16. // store.commit('getlocation', city)
    17. Vue.prototype.$cityName = city
    18. // 挂载页面
    19. })
    20. }
    21. function errorCallback(error) {
    22. var err = error.code
    23. switch(err) {
    24. case 0:
    25. alert('未识别到位置信息')
    26. break;
    27. case 1:
    28. alert('您拒绝了定位权限')
    29. break;
    30. case 2:
    31. alert('地理位置获取失败')
    32. break;
    33. case 3:
    34. alert('定位超市')
    35. break;
    36. default:
    37. //
    38. }
    39. // store.commit('getlocation', '北京')
    40. Vue.prototype.$cityName = '北京'
    41. // 挂载页面
    42. }

    优点:性能好加载快

    缺点:仅支持https协议链接,http协议下无法正常定位

  • 相关阅读:
    QT开发实例之常用控件(上)
    shiro反序列化和log4j
    Redis Cluster 集群搭建与扩容、缩容
    微信native支付
    Appium 使用
    Synchronized 原 理
    JavaScript 56 JavaScript 调试
    CSS常见选择器
    C++入门学习笔记
    串的基本操作(数据结构)
  • 原文地址:https://blog.csdn.net/q_qman/article/details/134215646