背景:
在進行小程序開發時,有一個定位城市的需求,下面就來講講怎么實現這個功能的吧
解決方案:
小程序的wx.getLocation()獲得是經緯度並不包含地名,所以要通過經緯度用相應的地圖轉換出地名(本文使用的是百度地圖)。
/* 微信獲取城市定位 */ wx.getLocation({ type: 'wgs84', success(res) { const latitude = res.latitude const longitude = res.longitude const speed = res.speed const accuracy = res.accuracy console.log('-d---------------------') console.log(res) scope.getCityInfo(latitude,longitude) } })
1.1代碼詳解
wx.getLocation(object):獲取當前的地理位置、速度。注意:需要用戶授權地理定位權限。
詳細參數說明請查看小程序API:https://developers.weixin.qq.com/miniprogram/dev/api/location.html#wxgetlocationobject
我們看看wx.getLocation()成功后獲得到的數據:

從獲得到的數據我們可以看到並沒有我們想要的地名,因此就需要我們把經緯度轉換成相應的地名,本文使用的是百度地圖相應功能轉換出相應地名。
1.2 百度地圖的准備工作
1.在使用百度地圖API之前,首先要獲得百度地圖的密鑰ak,ak由百度地圖方生成;
2.打開百度地圖開放平台,導航欄處選擇 “開發文檔” > “微信小程序JavaScript API”,在“入門指南”處有詳細介紹怎么生成密鑰ak,本文不再介紹。
參考文檔:http://lbsyun.baidu.com/index.php?title=wxjsapi/guide/key
3.復制生成好的ak,把ak粘貼到小程序中。其實,百度地圖有提供小程序使用的地圖api的壓縮包,但是出於小程序發布時對大小的限制,我選擇了使用鏈接。
百度地圖線上轉換鏈接地址:https://api.map.baidu.com/geocoder/v2/?ak=獲得的AK&location=' + latitude + ',' + longitude + '&output=json'
4.使用小程序的賬號登錄微信公眾平台(https://mp.weixin.qq.com/),在“設置” 中選擇 “開發設置”,把百度地圖api的url添加到request合法域名中。
注意:百度地圖提供的有關於小程序API的下載包,不想使用鏈接地址的可以使用下載包,出於小程序發布時對大小的限制,本文使用的是鏈接地址未使用下載包。
/* 逆向地理編碼 */ getCityInfo(latitude,longitude){ let scope=this; wx.request({ url:'http://api.map.baidu.com/geocoder/v2/?location='+latitude+','+longitude+'&output=json&pois=1&ak=', data:{}, header:{ 'Content-Type':"application/json" }, success:function(res){ if(res&&res.data){ console.log(res); scope.cityName=res.data.result.addressComponent.city; scope.getCommunity(); console.log(res.data.result.addressComponent.city) }else{ console.log('獲取失敗') } } })

