美文网首页
小程序使用腾讯地图定位当前城市

小程序使用腾讯地图定位当前城市

作者: 你若像风 | 来源:发表于2019-07-19 11:17 被阅读0次

这个迭代使用mpvue框架开发了小程序。对于之前一直用vue来开发web项目的我来说,有这么一个框架来开发小程序真的是很激动啊,提升了很多开发效率。

这里记录一下在小程序中使用腾讯地图来定位当前城市的功能。

首先会有一个授权提示: image.png

分析一下思路:


image.png

接下来需要做的事情如下:

1、接入腾讯地图SDK

文档地址:https://lbs.qq.com/qqmap_wx_jssdk/index.html
按照文档的步骤来:

image.png
前3步都很简单,第4步需要注意一点的就是,如果你是在开发工具调试的话,可以直接勾选这个使用:
image.png

但是,如果要发体验版或者发布正式环境了之后,就要加上合法域名了,不然使用不了。添加合法域名就是在小程序的管理后台这个地方加入即可。


image.png

准备工作就是这么多。现在可以写代码了。

2、引入核心代码,并初始化
//qqmap-wx-jssdk.min.js是下载下来的包,放在utils 或者static目录下都行
let QQMapWX = require('../../../../static/js/qqmap-wx-jssdk.min.js')
let qqmapsdk
export default {
 data() {
  return {
    city: '',
    userLocation: {
      latitude: '',
      longitude: ''
    }
  }
},
onLoad() {
  qqmapsdk = new QQMapWX({
    key: 'xxxxxxxxxxxxxxxxxxxx' // 申请的key
  })
  this.getUserLocation()  //获取用户定位
  }
},
methods: {
  getUserLocation() {
    wx.getSetting({  //获取用户授权情况
      success: res => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) { // 用户非首次访问,且曾经拒绝过授权,此时res.authSetting['scope.userLocation'] 一般返回false
          //这里是跳转开启定位页面,引导用户授权的代码
          return false
        }
        this.getLocation() //继续下一步
      },
      fail: () => {
        Utils.showToast('网络错误:获取用户授权信息失败!')
      }
    })
  },
  getLocation() {
    wx.getLocation({  // 这一步 如果用户是首次访问,则会弹出授权弹窗
      type: 'gcj02',
      success: res => {
        this.userLocation = res  // res包含经纬度信息
        this.getLocal()  //继续下一步
      },
      fail: res => {
        if (res.errMsg == 'getLocation:fail 1' || res.errMsg == 'getLocation:fail system permission denied') { 
            // 用户允许授权但获取位置失败,可能有多种原因,比如网络原因、手机系统拒绝使用定位
            //这里写相应的代码
        } else if (res.errMsg == 'getLocation:fail auth deny' || res.errMsg == 'getLocation:fail:auth denied') {
            // 用户拒绝了授权,跳去开启定位页面引导授权的代码
        } else { // 别的错误
            Utils.showToast('网络错误:获取用户所在位置经纬度失败!')
        }
      }
    })
  },
  getLocal() {
    qqmapsdk.reverseGeocoder({
        location: {
            latitude: this.userLocation.latitude,
            longitude: this.userLocation.longitude
        },
        success: res => {
            this.userLocation = {
                ...this.userLocation,
                ...res.result
            }
            this.city = this.userLocation.address_component.city
            this.city = this.city.replace('市', '')  // 深圳、广州
        },
        fail: error => {
            Utils.showToast(error.message)
        }
    })
  }
}

整个流程就是这样,记录下来加深记忆的同时希望能帮助到需要的朋友,如果写得不明白或者看不懂的欢迎留言。

相关文章

网友评论

      本文标题:小程序使用腾讯地图定位当前城市

      本文链接:https://www.haomeiwen.com/subject/lradlctx.html