微信小程式獲取經緯度
阿新 • • 發佈:2018-11-14
1、在index.wxml檔案建立如下程式碼,longitude,latitude為以獲取經緯度為地圖中心,獲取當前位置經緯度資訊
<view>緯度:{{latitude}}</view> <view>經度:{{longitude}}</view> <button bindtap="mapViewTap" style="margin:10px">檢視地圖</button> <button bindtap="chooseMapViewTap" style="margin:10px">選擇位置</button>
2、index.js檔案如下,onload 事件自動獲取經緯度位置並且顯示到頁面,點選檢視地圖通過 wx.getLocation為獲取使用者位置API,也可以點選選擇位置按鈕選擇自己當前位置
Page({ data: { latitude: '', longitude: '' }, onLoad: function () { var that = this; wx.getLocation({ type: 'wgs84', success: function (res) { that.setData({ latitude: res.latitude, longitude: res.longitude }) } }) } ,// 檢視地圖 mapViewTap: function () { wx.getLocation({ type: 'gcj02', //返回可以用於wx.openLocation的經緯度 success: function (res) { console.log(res) wx.openLocation({ latitude: res.latitude, longitude: res.longitude, scale: 28 }) } }) }, // 選擇位置 chooseMapViewTap: function () { var that = this wx.chooseLocation({ success: function (res) { that.setData({ location: { latitude: res.latitude, longitude: res.longitude, name: res.name } }) }, }) }, })
具體顯示如下圖: