微信小程序提供一些API(地址)用於獲取當前用戶的地理位置等信息,但不管是wx.getLocation,仍是wx.chooseLocation均沒有單獨的字段表示國家與城市信息,僅有經緯度信息。在實際使用過程當中僅顯示地名是不夠的,咱們能夠將微信提供的經緯度信息利用第三方地圖API轉換爲國家與城市信息。百度地圖、高德地圖、騰訊地圖均有相似服務。本文以百度地圖爲例。php
微信小程序官方地理位置相關API:https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html#wxchooselocationobjecthtml
1.首先咱們須要在百度地圖開放平臺(http://lbsyun.baidu.com/index.php) 註冊爲開發者。git
2.申請開發者密鑰(AK):
web
其中,APPID處填寫小程序的APP ID。json
3.百度地圖逆地址解析API能夠接受經緯度座標座標,返回帶有國家和城市的地址信息。小程序
逆地址解析API:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
微信小程序
此處注意:百度地圖API默認採用座標爲bd09ll(百度經緯度座標),而微信內置地圖得到的經緯度座標爲wgs84ll( GPS經緯度)。api
1.利用微信選擇位置API,得到經緯度信息
2.百度地圖API,將微信得到的經緯度傳給百度,得到城市等信息
'https://api.map.baidu.com/geocoder/v2/?ak=本身申請的百度密鑰&location=' + lb.latitude + ',' + lb.longitude + '&output=json&coordtype=wgs84ll'
3.咱們將微信獲得的位置名稱「故宮博物館」與百度地圖API獲得的「北京市東城區」合併顯示在頁面上。
完整代碼:微信
wx.chooseLocation({ // ①.利用微信選擇位置API,得到經緯度信息 success: function (lb) { console.log("地理位置") console.log(lb) that.data.addressData = lb wx.request({ // ②百度地圖API,將微信得到的經緯度傳給百度,得到城市等信息 url: 'https://api.map.baidu.com/geocoder/v2/?ak=GuMNe9FqXsvKoWY9VZaWNw9wlzUGjyTE&location=' + lb.latitude + ',' + lb.longitude + '&output=json&coordtype=wgs84ll', data: {}, header: { 'Content-Type': 'application/json' }, success: function (res) { console.log(res.data.result); console.log(res.data.result.addressComponent.city + res.data.result.addressComponent.district); that.setData({ addressAll: res.data.result.addressComponent.city + res.data.result.addressComponent.district + "·" + lb.name //③.咱們將微信獲得的位置名稱「故宮博物館」與百度地圖API獲得的「北京市東城區」合併顯示在頁面上。 }) }, fail: function () { // fail }, complete: function () { // complete } }) }, cancel: function (lb) { }, fail: function (lb) { console.log(lb) } })
此功能較爲簡單。
1.在地址處定義好須要的數據:app
<block wx:if="{{resultData[k].address != 'undefined'}}"> <text class="address" bindtap="bindLocation" data-address="{{resultData[k].address}}" data-name="{{resultData[k].name}}" data-longitude="{{resultData[k].longitude}}" data-latitude="{{resultData[k].latitude}}">{{resultData[k].addressAll}}</text> </block>
2.藉助微信小程序的查看位置的API wx.openLocation。這個API會自動打開地圖。
微信小程序顯示位置的API:https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html#wxopenlocationobject
bindLocation: function (e) {// 點擊地址,查看位置 wx.openLocation({ latitude: e.target.dataset.latitude, longitude: e.target.dataset.longitude, name: e.target.dataset.name, address: e.target.dataset.address }) },