在微信小程序中获取定位信息
今天一整天基本上都在处理在微信小程序中获取准确地址,给出定位并给出所在城市的问题。经过走了半天弯路,现在总结一下所需要的步骤。
一. 先到腾讯位置服务中心获取KEY
通过小程序ID即可获取定位服务的KEY
二.下载微信小程序JavaScriptSDK
下载地址:
https://mapapi.qq.com/web/miniprogram/JSSDK/qqmap-wx-jssdk1.2.zip
下载完成将下载的js包放到小程序的utils包中
接下来就可以在小程序中使用地图功能了
三.使用地图功能
1.最简单的就是使用一个地图容器,我在上面加了一个搜索框,手机上面显示效果如下:
2.接下来是通过定位来获取当前所在城市
先引入SDK类
//引入SDK核心类
var QQMapWX = require('../../../utils/qqmap-wx-jssdk');
var qqmapsdk;
qqmapsdk = new QQMapWX({
key: '申请的KEY'
});
接着调用 wx.getLocation获取当前用户的地理位置(微信返回的是经纬度、速度等参数)
wx.getLocation({
type: 'gcj02',
altitude: true,
//定位成功,更新定位结果
success: function (res) {
var latitude = res.latitude
var longitude = res.longitude
var speed = res.speed
var accuracy = res.accuracy
that.setData({ //赋值
longitude: longitude,
latitude: latitude,
Mylongitude:longitude,
Mylatitude:latitude,
speed: speed,
accuracy: accuracy
})
app.globalData.latitude = latitude;
app.globalData.longitude = longitude;
}, //定位失败回调
fail: function () {
wx.hideLoading();
console.log("getLocationFail")
},
complete: function () {
//隐藏定位中信息进度
wx.hideLoading()
}
})
在控制台可以看见已拿到了所需要的数据,但其中并没有所在城市的信息
所以需要根据经纬度获取对应城市信息,我也是在这一步上花费了大量的时间,因为我最开始以为方法wx.getLocation中有城市的数据,其实并没有。需要使用qqmapsdk.reverseGeocoder逆地址解析城市信息
//获取当前地理位置
getLocal:function(latitude,longitude){
let that = this
//逆地址解析
qqmapsdk.reverseGeocoder({
location:{
latitude:latitude,
longitude:longitude
},
success:function(res){
console.log(res)
let first_enter = wx.getStorageSync('first_enter')
wx.setStorageSync('first_enter', false)
let province = res.result.ad_info.province;
let city = res.result.ad_info.city;
let cityCode = res.result.ad_info.city_code;
let nationCode = res.result.ad_info.nation_code;
let city_code=cityCode.substring(nationCode.length)
//如果本地存储没有城市信息,则将定位的城市信息存入本地存储
that.setData({
cityName:city,
city_code:city_code
})
// wx.setStorageSync('city', city)
//wx.setStorageSync('city_code', city_code)
},
fail:function(res){
console.log(res)
}
})
},
最终我们拿到了我们所在的城市标签