EA&UML日拱一卒-微信小程序實戰:位置鬧鈴 (2)-在地圖上顯示自己的位置

有了最終目標以後,我們繼續採取每天一小步的方式進行開發,今天首先實現在地圖上顯示自己位置的功能。


畫面截圖



index.wxml


<!--index.wxml-->

<view class="container">

 <map longitude="{{longitude}}" latitude="{{latitude}}" markers="{{markers}}" style=" width: 375px; height: 500px;"></map>

 <text class="angle_text">{{location}}</text>

</view>

 

內容很簡單,畫面上佈置了一個map對象和text對象。


其中map對象分別指定了longitude,latitude和markers。相信你還記得:在雙重花括號{{}}包圍的部分是變量,它們的值在對應頁面的js文件中定義。


index.js


//index.js

//獲取應用實例

const app = getApp()

Page({

 data: {                   //數據定義

   longitude: 0,       // 對應wxml文件中的longitude變量

   latitude: 0,          // 對應wxml文件中的latitude變量

   location: ',',         // 對應wxml文件中的location變量

   markers: [{          // 對應wxml文件中的markers變量

     id: 0,

     latitude: 0,

     longitude: 0,

     width: 50,

     height: 50

   }],

 },

 

 onShow: function() {

   var that = this

   wx.getLocation({

     type: 'gcj02', // 返回 可以 用於 wx. openLocation 的 經緯度

     success: function (res) {

       var latitude = res.latitude

       var longitude = res.longitude

       console.log(res)

       var location = latitude.toFixed(2) + ',' + longitude.toFixed(2)

       that.setData({ longitude: longitude,

                      latitude: latitude,

                      location: location,

                      markers: [{latitude: latitude,

                                 longitude: longitude,

                               }]

                   });

     }

   })

 },

})


這段代碼實現了生命週期函數onShow,它的核心是ws.getLocation,它的輸出通過傳遞的success:function來處理。處理的內容很簡單,就是通過setData函數設定到各個數據上。


雖然有點突然,但是這就是全部了。


參考資料


地圖表示

https://mp.weixin.qq.com/debug/wxadoc/dev/component/map.html#map


獲取位置

https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html


寫在文章的最後


既然已經讀到這裏了,拜託大家再用一分鐘時間,將文章轉發到各位的朋友圈,微信羣中。本公衆號的成長需要您的支持!
以上就是今天的文章,歡迎點贊並推薦給您的朋友!
閱讀更多更新文章,請掃描下面二維碼,關注微信公衆號【面向對象思考】