标题小程序获取当前位置----逆地址解析----地图选点
实现功能:小程序首页定位当前城市类似于
某宝:
某团:
获取当前位置:
在小程序首页创建getLocation函数并在onLoad调用
首先需要引入腾讯位置服务的 微信小程序JavaScript SDK
1.申请开发者密钥(key):申请密钥
2.开通webserviceAPI服务:控制台 -> key管理 -> 设置(使用该功能的key)-> 勾选webserviceAPI -> 保存
(小程序SDK需要用到webserviceAPI的部分服务,所以使用该功能的KEY需要具备相应的权限)
3.下载微信小程序JavaScriptSDK,微信小程序JavaScriptSDK v1.2 安全域名设置,在“设置” ->
4.“开发设置”中设置request合法域名,添加https://apis.
并在首页文件头部引入
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
getLocation:
getLocation() {let _this = thiswx.getLocation({// 调用微信小程序的wx.getLocation获取当前的经纬度type: 'wgs84',success(res) {const latitude = res.latitudeconst longitude = res.longitudeconst key = ''; // 使用在腾讯位置服务申请的key// 实例化API核心类var qqmapsdk = new QQMapWX({key: key});// 逆地址解析qqmapsdk.reverseGeocoder({location: {latitude,longitude},success(res) {// console.log('getLocation: ', res.result)_this.setData({location: res.result.address_component.city})}})}})},
可以获取这么一堆数据
我们取其中的市级city
选择位置:
我们这里采用的是腾讯位置服务地图选点插件实现选择位置功能。
接入指引官网有详细讲解。
在文件头部引入:
const chooseLocation = requirePlugin('chooseLocation');
在点击首页城市选择区域时调用location()函数,因为页面加载时获取位置已经提示用户授权小程序的定位功能,这里调用wx.getSetting验证用户是否同意授权,如果同意则跳转地图选点页面,否则提示用户授权。
location()函数:
// 定位location() {const key = ''; //使用在腾讯位置服务申请的keyconst referer = ''; //调用插件的app的名称// const category = '生活服务,娱乐休闲';const scale = 7;wx.getSetting({success(res) {if (!res.authSetting['scope.userLocation']) {wx.authorize({scope: 'scope.userLocation',success() {// 用户已经同意小程序使用定位功能wx.navigateTo({url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&scale=${scale}`});},fail(err) {console.log(err)if (err.errMsg.indexOf('auth deny')) {// 用户拒绝定位授权Dialog.alert({message: '您已拒绝地理位置授权,\n请在右上角设置打开',})}}})} else {wx.navigateTo({url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&scale=${scale}`});}}})},
获取位置信息:
如果用户选点完成,则在onShow里获取用户的选点结果对象。
大部分选点的返回结果都可以直接获取到city,但是某些选点不会直接返回city如:公交车站点等
此时就需再次调用逆地址解析来获取位置信息
const location = chooseLocation.getLocation(); // 如果点击确认选点按钮,则返回选点结果对象,否则返回null// console.log('location:', location)if (location) {if (location.city) {this.setData({location: location.city})} else {const latitude = location.latitudeconst longitude = location.longitudeconst key = '';//使用在腾讯位置服务申请的key// 实例化API核心类var qqmapsdk = new QQMapWX({key: key});// 逆地址解析qqmapsdk.reverseGeocoder({location: {latitude,longitude},success(res) {// console.log('getLocation: ', res.result)_this.setData({location: res.result.address_component.city})}})}}
最后记得页面卸载时设置插件选点数据为null,防止再次进入页面,geLocation返回的是上次选点结果
onHide() {chooseLocation.setLocation(null);},