共享單車微信小程式之初體驗
阿新 • • 發佈:2018-12-30
- 從Sensor裡面讀取經緯度,顯示對應的地理位置資訊
//index.wxml
//相關屬性:latitude(緯度),longitude(經度)
<map id='mymap' latitude='{{lat}}' longitude='{{log}}' style='width:100%;height:100%'
>
</map>
//index.js
//獲取應用例項
const app = getApp()
Page({
data: {
lat:0,
log:0
},
//首次載入頁面時呼叫
onLoad: function () {
var that = this ;
//獲取當前位置的地理資訊
wx.getLocation({
success: function(res) {
var longitude = res.longitude;
var latitude = res.latitude;
that.setData({
log : longitude,
lat: latitude
})
}
})
}
})
2.在地圖內新增控制元件
//index.wxml
//相關屬性:controls
<map id='mymap' latitude='{{lat}}' longitude='{{log}}' style='width:100%;height:100%'
controls='{{controls}}'
>
</map>
//index.js
//獲取應用例項
const app = getApp()
Page({
data: {
log:0,
lat:0,
controls: []
},
//首次載入頁面時呼叫
onLoad: function () {
var that = this;
//獲得系統資訊
wx.getSystemInfo({
success: function (res) {
var windowWidth = res.windowWidth;
var windowHeight = res.windowHeight;
console.log(windowWidth)
that.setData({
controls: [
//掃碼按鈕
{
id: 1,
iconPath: '/images/qrcode.png',
position: {
width: 100,
height: 60,
left: windowWidth / 2 - 50,
top: windowHeight - 90
},
clickable: true
}
]
})
}
})
}
})
3.點選回到地圖原來的位置
//屬性:bindcontroltap='controltap'
//index.wxml
<map id='myMap' latitude='{{lat}}' longitude='{{log}}' style='width:100%;height:100%' show-location='true' scale='17'
bindcontroltap='controltap'
controls='{{controls}}'
>
</map>
//index.js
controltap: function(e) {
var cid = e.controlId;
switch(cid) {
case 7: {
//回到原來的位置,mapCtx記錄了地圖移動前的初始位置
this.mapCtx.moveToLocation();
}
}
},
//頁面渲染完成就會執行
onReady: function() {
//建立map上下文
this.mapCtx = wx.createMapContext('myMap')
}