由于微信小程序只提供了获取地理位置(经纬度)、速度的api,并没有获取地理位置的信息。因此,我们需要利用第三方地图api来解决这个问题。
原理
通过调用wx.getLocation()获取到设备当前所在地理位置的经纬度。再申请一个第三方地图api的ak(访问应用),然后通过ajax请求把ak和经纬度传给第三方服务端,该服务端返回地理位置信息。
1,这里使用了百度地图的api,进入百度地图开发平台,创建一个应用,申请一个ak。
2,调用wx.getLocation()获取到设备当前的经纬度。
3,用ajax把ak和经纬度(lat<纬度>,lng<经度>)传给百度地图服务端即可。
getCity: function(e) {var that = this;console.log(e);//返回true和falseconsole.log(e.detail.value);//选中状态if (e.detail.value){wx.showLoading({title: '加载中',});wx.getLocation({success: function (res) {console.log(res);console.log(res.latitude);console.log(res.longitude);const url= 'http://api.map.baidu.com/geocoder/v2/';const ak = '填上自己申请的ak';//小程序的ajax请求需要在后台安全域名配置增加 开发测试中在详情里勾选-不校验合法域名即可wx.request({url,data: {ak,location: `${res.latitude},${res.longitude}`,output: 'json', //格式},success: function (res){console.log(res);if(res.data.status == "0"){that.setData({province: res.data.result.addressComponent.province,city: res.data.result.addressComponent.city,district: res.data.result.addressComponent.district,isShow: true});wx.hideLoading()}else{that.setData({unGeo: '未知位置',isShow: false});wx.hideLoading()}}})}})}}
