微信小程式入門之指南針
阿新 • • 發佈:2020-10-24
微信小程式入門案例——指南針,供大家參考,具體內容如下
涉及技術:獲取地理位置、監聽指南針角度
目錄結構:
pages\index\index.js
Page({ /** * 頁面的初始資料 */ data: { rotate:0,degree:'未知',direction:'',lat:0,lon:0,alt:0 },/** * 生命週期函式--監聽頁面載入 */ onLoad: function (options) { var that = this; wx.getLocation({ altitude: true,success:function(res){ that.setData({ lat:res.latitude.toFixed(2),lon:res.longitude.toFixed(2),alt:res.altitude.toFixed(2) }) } }) wx.onCompassChange(function(res){ let degree = res.direction.toFixed(0); that.getDirection(degree) that.setData({ rotate:360 - degree }) }) },/** * 判斷方向 */ getDirection:function(deg){ let dir = '未知'; if(deg>=340||deg<=20){ dir='北'; }else if(deg>20&°<70){ dir='東北'; }else if(deg>=70&°<=110){ dir='東'; }else if(deg>110&°<160){ dir='東南'; }else if(deg>=160&°<=200){ dir='南'; }else if(deg>200&°<250){ dir='西南'; }else if(deg>=250&°<=290){ dir='西'; }else if(deg>290&°<340){ dir='西北'; } this.setData({ degree:deg,direction:dir }) },/** * 生命週期函式--監聽頁面初次渲染完成 */ onReady: function () { },/** * 生命週期函式--監聽頁面顯示 */ onShow: function () { },/** * 生命週期函式--監聽頁面隱藏 */ onHide: function () { },/** * 生命週期函式--監聽頁面解除安裝 */ onUnload: function () { },/** * 頁面相關事件處理函式--監聽使用者下拉動作 */ onPullDownRefresh: function () { },/** * 頁面上拉觸底事件的處理函式 */ onReachBottom: function () { },/** * 使用者點選右上角分享 */ onShareAppMessage: function () { } })
pages\index\index.wxml
<view class="container"> <image src="/images/1.jpg" mode="widthFix" style="transform:rotate({{rotate}}deg);"></image> <view class="status"> <text class="bigTxt">{{degree}}°{{direction}}</text> <text class="smallTxt">北緯{{lat}}東經{{lon}}</text> <text class="smallTxt">海拔{{alt}}米</text> </view> </view>
pages\index\index.wxss
.container{ height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: space-around; color: #A46248; } image{ width: 80%; } .status{ display: flex; flex-direction: column; align-items: center; } .bigTxt{ font-size: 30pt; margin: 15rpx; } .smallTxt{ font-size: 20pt; margin: 15rpx; }
app.js
App({ /** * 當小程式初始化完成時,會觸發 onLaunch(全域性只觸發一次) */ onLaunch: function () { },/** * 當小程式啟動,或從後臺進入前臺顯示,會觸發 onShow */ onShow: function (options) { },/** * 當小程式從前臺進入後臺,會觸發 onHide */ onHide: function () { },/** * 當小程式發生指令碼錯誤,或者 api 呼叫失敗時,會觸發 onError 並帶上錯誤資訊 */ onError: function (msg) { } })
app.json
{ "pages":[ "pages/index/index" ],"window":{ "backgroundTextStyle":"light","navigationBarBackgroundColor": "#fff","navigationBarTitleText": "指南針","navigationBarTextStyle":"black" },"permission":{ "scope.userLocation":{ "desc":"你的位置資訊將用於小程式指南針的效果展示" } },"style": "v2","sitemapLocation": "sitemap.json" }
執行截圖:
為大家推薦現在關注度比較高的微信小程式教程一篇:《微信小程式開發教程》小編為大家精心整理的,希望喜歡。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。