微信小程序获取当前位置
首先用微信小程序官方文档中提供的wx.getLocation方法来获取用户的地理位置信息。
WXML:
JS:
控制台打印结果:
补充:若获取失败则在app.json文件里写上这样获取到的是当前的经纬度位置,若要转化为具体地址还需要借助第三方地图(腾讯地图,百度地图,高德地图)。
以下是以腾讯地图作为第三方地图的步骤:
第一步,在https://lbs.qq.com/qqmap_wx_jssdk/index.html(腾讯地图服务)里完成四个步骤
第二步,下载的微信小程序JavaScriptSDK使用qqmap-wx-jssdk.min.js(另外一个也可以),在根目录上新建一个lib文件夹存放js。
第三步,引入
第四步:将经纬度转化为具体位置:
//获取用户当前位置
getLocation() {
wx.getLocation({
type: ‘wgs84’,
success(res) {
console.log(res)
const latitude = res.latitude
const longitude = res.longitude
const speed = res.speed
const accuracy = res.accuracy
// 调用接口转换成具体位置
demo.reverseGeocoder({
location: {
latitude: res.latitude,
longitude: res.longitude
},
success: function (res) {
console.log(res.result);
},
fail: function (res) {
console.log(res);
},
// complete: function (res) {
// console.log(res);
// }
})
}
})
},
控制台打印结果: