微信小程序获取地理位置和地名的方法

1、微信小程序获取地理位置和详细地名的思路
2)、使用拿到的经纬度请求地图位置服务的逆地址解析接口,获取省市县和详细地址。这是最关键的步骤,也是腾讯地图API官网没有写清楚的一步
2、微信小程序获取地理位置和详细地名的思路
1)、获取用户当前位置经纬度
// 微信api,获取经纬度 getLocation() { wx.getLocation({ type: 'gcj02', success: this.updateLocation, fail: (e)=> { this.openLocation() } }) }2)、根据经纬度获取当前位置

腾讯地图提供的微信小程序JavaScript SDK
WebService API,即直接发送请求,调用API接口
小程序 SDK 和 WebService API 都很方便,不需要加密数据,密钥都是对外暴露的
WebService API 使用微信 wx.request 方法可以直接发送请求,对代码无侵入性
小程序 SDK 本质上还是用 wx.request 封装的 WebService API
2.1、获取签名计算sig信息

// pages/index/index.jsimport md5 from '../../utils/md5.js'// 获取应用实例// ……
JavaScript-MD5库时,直接调用md5(value)方法,其中value是String类型2.2、完整的地理位置获取流程
//pages/index/index.js// QQMapKey是在腾讯地图开放平台设置的密钥// 请使用你自己的密钥const QQMapKey = 'NILBZ-BOIHP-SOOD3-LTPVO-ITVWK-*****';// 在密钥设置中开启WebServiceAPI,选择签名校验,即可获取Secret key,即SK// 请使用你自己的SKconst SK = '25rlrIUFfYbJkN54yqB7IX4sR*****';// 引入MD5库import md5 from '../../utils/md5.js';//获取应用实例const app = getApp()Page({data: {lat: 40.056974,lon: 116.307689,address: '定位中'},onLoad() {this.getLocation()},// 根据经纬度,逆地址解析getAddress(lat, lon) {// 在wx.request中,this指向wx.request,故无法setData,此处将this指向thatvar that = thiswx.showLoading({title: '定位中',mask: true,duration: 3000})let SIG = md5("/ws/geocoder/v1?key=" + QQMapKey +"&location="+String(lat)+","+String(lon)+SK)wx.request({url: 'https://apis.map.qq.com/ws/geocoder/v1',data: {key: QQMapKey,location: `${lat},${lon}`,sig: SIG},success(res) {let result = res.data.result// console.log(result)// formatted_addresses.recommend是经过腾讯地图优化过的描述方式,更具人性化特点let formatted_addresses = result.formatted_addresses.recommend// 此处的that指向appthat.setData({address: formatted_addresses})wx.hideLoading()},fail:(e) => {console.log(e)wx.hideLoading()}})},// 根据经纬度,设置数据updateLocation(res) {let {latitude: lat, longitude: lon} = reslet data = {lat,lon}this.setData(data)this.getAddress(lat, lon)},// 微信api,获取经纬度getLocation() {wx.getLocation({type: 'gcj02',success: this.updateLocation,fail: (e)=> {console.log(e)}})}})
本文完~
评论

