微信小程式定位當前城市
阿新 • • 發佈:2018-12-31
定位獲取當前所在城市
1、利用微信小程式介面 wx.getLocation() 獲取當前經緯度。
https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html#wxopenlocationobject
2、拿到經緯度之後,通過微信的wx.request()請求百度地圖的解析介面,傳入我們獲取到的經緯度,拿到當前定位的城市。
Page({ data: { city: '' }, onLoad: function (options) { this.loadInfo(); }, loadInfo: function () { var page = this wx.getLocation({ type: 'wgs84', // 預設為 wgs84 返回 gps 座標,gcj02 返回可用於 wx.openLocation 的座標 success: function (res) { // success var longitude = res.longitude var latitude = res.latitude page.loadCity(longitude, latitude) }, fail: function () { // fail }, complete: function () { // complete } }) }, loadCity: function (longitude, latitude) { var page = this wx.request({ url: 'http://api.map.baidu.com/geocoder/v2/?ak=寫自己的ak&location=' + latitude + ',' + longitude + '&output=json&pois=1', //這裡的ak 是去百度地圖api獲取的需要自己登陸獲取一下 地址:https://lbsyun.baidu.com/index.php?title=wxjsapi data: {}, header: { 'Content-Type': 'application/json' }, success: function (res) { // success console.log(res); var city = res.data.result.addressComponent.city; console.log("城市為" + city) page.setData({ city: city }); }, fail: function () { // fail }, complete: function () { // complete } }) } });