由于微信小程序只提供了獲取地理位置(經(jīng)緯度)侨嘀、速度的api臭挽,并沒有獲取地理位置的信息。因此咬腕,我們需要利用第三方地圖api來解決這個問題欢峰。
一、原理
通過調(diào)用wx.getLocation()獲取到設(shè)備當(dāng)前所在地理位置的經(jīng)緯度涨共。再申請一個第三方地圖api的ak(訪問應(yīng)用)纽帖,然后通過ajax請求把ak和經(jīng)緯度傳給第三方服務(wù)端,該服務(wù)端返回地理位置信息(如廣東省廣州市白云區(qū))举反。
二抛计、效果圖
三、實現(xiàn)過程
這里使用了百度地圖的api照筑,進入百度地圖開發(fā)平臺吹截,創(chuàng)建一個應(yīng)用,申請一個ak凝危。
getCity: function(e) {
var that = this;
console.log(e);
//返回true和false
console.log(e.detail.value);
//選中狀態(tài)
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請求需要在后臺安全域名配置增加 開發(fā)測試中在詳情里勾選-不校驗合法域名即可
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()
}
}
})
}
})
}
}
好了蛾默,很簡單的一個案例~