微信小程序开发–获取位置信息

1 获取当前地理位置,首先要拿到用户的授权wx.openSetting

微信小程序获取位置信息_微信小程序

在用户首次进入某页面(需要地理位置授权)时候,在页面进行onLoad,onShow时候,进行调用wx.getLocation要求用户进行授权;以后每次进入该页面时,通过wx.getSetting接口,返回用户授权具体信息。

wx.getSetting接口具体API地址链接为点击​链接​

微信小程序获取位置信息_定位_02

当该标志是underfind,表示用户初次进入该页面,当该标志是false,表示用户初次进入该页面拒绝了地理授权,应进行重新要求获取授权。

wx.getSetting({
success: (res) => {
console.log(JSON.stringify(res))
// res.authSetting['scope.userLocation'] == undefined 表示 初始化进入该页面
// res.authSetting['scope.userLocation'] == false 表示 非初始化进入该页面,且未授权
// res.authSetting['scope.userLocation'] == true 表示 地理位置授权
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
wx.showModal({
title: '请求授权当前位置',
content: '需要获取您的地理位置,请确认授权',
success: function (res) {
if (res.cancel) {
wx.showToast({
title: '拒绝授权',
icon: 'none',
duration: 1000
})
} else if (res.confirm) {
wx.openSetting({
success: function (dataAu) {
if (dataAu.authSetting["scope.userLocation"] == true) {
wx.showToast({
title: '授权成功',
icon: 'success',
duration: 1000
})
//再次授权,调用wx.getLocation的API

} else {
wx.showToast({
title: '授权失败',
icon: 'none',
duration: 1000
})
}
}
})
}
}
})
} else if (res.authSetting['scope.userLocation'] == undefined) {
//调用wx.getLocation的API
}
else {
//调用wx.getLocation的API
}
}
})

2、微信小程序地图展示位置信息

在拿到用户授权以后,使用微信的API获取当前位置的经纬度微信获取位置API

onLoad: function () {
wx.getLocation({
success: res=> {
console.log(res);
this.setData({
location: res,
})
// console.log(app.globalData.location);
},
})
}

实现效果如下图:

微信小程序获取位置信息_地理位置_03

微信小程序也支持在地图上选点,获取定位信息(wx.chooseLocation)和使用微信内置地图查看位置(wx.openLocation)

3、结合百度地图获取位置信息

微信小程序的接口,只能得到经纬度,但有时候我们需要得到具体的城市或者区域信息,这就需要借助百度地图了(​或者腾讯地图等,逻辑都是一样的​)。


  • 第一步:先到百度开放平台http://lbsyun.baidu.com申请ak(链接地址为:​​http://lbsyun.baidu.com/index.php?title=wxjsapi/guide/key)​​​​
  • 第二步:在服务器配置中添加百度地图的服务器(​​https://api.baidu.com​​​​)
  • 第三步:下载百度地图的api ​
  • 第四步:引入JS模块,将下载的js放到工程目录下
  • 第五步:在所需的js文件内导入js
    var bmap = require(’…/…/libs/bmap-wx/bmap-wx.js’);
  • 第六步:编辑代码 ,此处我获得的是城市信息,可以log出信息,选择自己要显示的信息,用setData的方式放入数据中进行展示即可

var BMap = new bmap.BMapWX({   
ak: that.data.ak,
});
console.log(BMap)
var fail = function(data) {
console.log(data);
};
var success = function(data) {
//返回数据内,已经包含经纬度
console.log(data);
//使用wxMarkerData获取数据
// = data.wxMarkerData;
wxMarkerData=data.originalData.result.addressComponent.city
//把所有数据放在初始化data内
console.log(wxMarkerData)
that.setData({
// markers: wxMarkerData,
// latitude: wxMarkerData[0].latitude,
// longitude: wxMarkerData[0].longitude,
address: wxMarkerData
});
}
// 发起regeocoding检索请求
BMap.regeocoding({
fail: fail,
success: success
});
},