開源:weChatApp-Run - 跑步微信小程序
一、準備工作
首先注冊一個小程序賬號,得用一個沒注冊過公眾號的郵箱注冊。
注冊過程中需要很多認證,比較繁瑣。如果暫時只是開發測試,不進行提審、發布的話,只要完成營業執照號的填寫就可以了,不需要完成微信認證。
注冊完賬號,并使用該帳號進行登錄。
在主頁面左邊列表中點擊設置,然后在設置頁面中選開發設置,就可以看到AppID,用于登錄開發工具。
主頁面
設置頁面
二、開發工具
開發工具
開發工具編輯頁面
三、開始項目
打開開發者工具,選擇小程序選項,到達“添加項目”頁面。
“添加項目”頁面
這個時候將前面設置頁面中的AppID填寫此處。
如果項目目錄中的文件是個空文件夾,會提示是否創建quick start 項目。
選擇“是”,開發者工具會幫助我們在開發目錄里生成一個簡單的 Demo。
這個Demo擁有一個完整的小程序的大概框架。
框架
先看下一目錄:
文件目錄
- app.js: 小程序邏輯,生命周期,全局變量。
- app.json: 小程序公共設置,導航欄顏色等,不可以注釋。
- app.wxss :小程序公共樣式,類CSS。
小程序頁面構成:
頁面構成
每一個小程序頁面是由同路徑下同名的四個不同后綴文件的組成,如:index.js、index.wxml、index.wxss、index.json。
各文件介紹
微信小程序中的每一個頁面的“路徑+頁面名”都需要寫在 app.json 的 pages 中,且 pages 中的第一個頁面是小程序的首頁。
路徑
這四個文件按照功能可以分成三個部分:
配置:json 文件。
邏輯層:js文件。
視圖層:wxss.wxml文件。
在 iOS 上,小程序的 JavaScript 代碼是運行在 JavaScriptCore 中。在 Android 上,小程序的 JavaScript 代碼是通過 X5 內核來解析。
在開發工具上,小程序的 JavaScript 代碼是運行在 NW.js(Chrome內核) 中。所以開發工具上的效果跟實際效果有所出入。
組件
微信提供了許多組件,主要分為八種:
- 視圖容器
- 基礎內容
- 表單組件
- 操作反饋
- 導航
- 媒體組件
- 地圖
- 畫布
包含view、scroll-view、button、form等普通常用的組件,也提供了地圖map、畫布canvas。
組件主要屬于視圖層,通過wxml來進行結構布局,類似于html。通過wxss修改樣式,類似于css。
組件使用語法實例:
<!--普通視圖-->
<view>這是一個普通視圖</view>
<!--wxss樣式修改-->
<view clas="mainView">樣式修改過的視圖</view></code></pre>
API
小程序中,大致提供以下幾個部分的 API 接口:
- 網絡
- 媒體
- 數據
- 位置
- 設備
- 界面
- 開發接口
其中網絡請求的使用必須先到公眾平臺登錄小程序賬號,在設置頁面那里,設置允許訪問的域名,網絡請求包含了普通的HTTP請求、支持上傳、下載、Socket。基本上滿足了我們開發中所需要的網絡需求。
這些API屬于邏輯層,寫在JavaScript文件中。
使用實例:
wx.getLocation({
type: 'wgs84',
success: function(res) {
var latitude = res.latitude
var longitude = res.longitude
var speed = res.speed
var accuracy = res.accuracy
}})
編譯運行
1.模擬器
可以在模擬器上看效果,上面提到了小程序的運行底層不同,效果在手機上運行也會有些差異。

模擬器
2.真機
在左邊的選項欄中,選擇項目,然后點預覽會生產一個二維碼,用管理員微信號掃一掃,就可以在真機上看實際效果。本例中,真機測試則掃描下面二維碼。

實踐:跑步小程序
真機運行截圖(運行于iPhone7,微信版本:6.3.30):

功能:能夠計算里程、時間、實時獲取跑步路徑(有些粗糙)。
思路:主要使用了微信小程序的獲取位置接口APIwx.getLocation()和地圖組件map。
首先實現一個計時器進行計時,通過wx.getLocation()獲取坐標,把獲取到的坐標存在一個數組中,通過坐標每隔一段時間獲取里程,進行累加得到總里程,同時也通過坐標點進行連線。
存在的問題:
- 因為目前找不到在地圖上畫連線的方法,所以采用了在地圖上貼小紅點圖的方法顯示大概跑步路徑,路徑比較粗糙。
- 雖然采用了API里面的火星坐標gcj02類型,但是獲取的坐標跟國際坐標差不多,依然存在著偏差。
核心代碼:
我把全部代碼放在github上: weChatApp-Run ,可以下載來看看或者先star收藏,我以后還會進行一些優化更新。現在只是一個學習Demo,大家溝通學習,實際應用還需更多優化。
wxml文件布局代碼:
<view class="head" style="flex-direction:row;">
<image class="icon" src="/resources/joyrun.png" mode="aspectFill"/>
<button bindtap="openLocation">打開位置</button>
<button bindtap="starRun">開始跑步</button>
<button bindtap="stopRun">暫停跑步</button>
<text>\n里程數:{{meters}}km</text>
<text>\n\n時間:{{time}}</text>
</view>
<view class="mainView">
<map
class="mapView"
style="width: 100%; height: 375px;"
latitude="{{latitude}}"
longitude="{{longitude}}"
markers="{{markers}}"
covers="{{covers}}"
>
</map>
</view>
</code></pre>
JavaScript文件邏輯代碼:
var countTooGetLocation = 0;
var total_micro_second = 0;
var starRun = 0;
var totalSecond = 0;
var oriMeters = 0.0;
/ 毫秒級倒計時 /
function count_down(that) {
if (starRun == 0) {
return;
}
if (countTooGetLocation >= 100) {
var time = date_format(total_micro_second);
that.updateTime(time);
}
if (countTooGetLocation >= 5000) { //1000為1s
that.getLocation();
countTooGetLocation = 0;
}
setTimeout
setTimeout(function(){
countTooGetLocation += 10;
total_micro_second += 10;
count_down(that);
}
,10
)
}
// 時間格式化輸出,如03:25:19 86。每10ms都會調用一次
function date_format(micro_second) {
// 秒數
var second = Math.floor(micro_second / 1000);
// 小時位
var hr = Math.floor(second / 3600);
// 分鐘位
var min = fill_zero_prefix(Math.floor((second - hr 3600) / 60));
// 秒位
var sec = fill_zero_prefix((second - hr 3600 - min * 60));// equal to => var sec = second % 60;
return hr + ":" + min + ":" + sec + " ";
}
function getDistance(lat1, lng1, lat2, lng2) {
var dis = 0;
var radLat1 = toRadians(lat1);
var radLat2 = toRadians(lat2);
var deltaLat = radLat1 - radLat2;
var deltaLng = toRadians(lng1) - toRadians(lng2);
var dis = 2 Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) Math.cos(radLat2) Math.pow(Math.sin(deltaLng / 2), 2)));
return dis 6378137;
function toRadians(d) { return d * Math.PI / 180;}
}
function fill_zero_prefix(num) {
return num < 10 ? "0" + num : num
}
//**
//**
Page({
data: {
clock: '',
isLocation:false,
latitude: 0,
longitude: 0,
markers: [],
covers: [],
meters: 0.00,
time: "0:00:00"
},
//**
onLoad:function(options){
// 頁面初始化 options為頁面跳轉所帶來的參數
this.getLocation()
console.log("onLoad")
count_down(this);
},
//**
openLocation:function (){
wx.getLocation({
type: 'gcj02', // 默認為 wgs84 返回 gps 坐標,gcj02 返回可用于 wx.openLocation 的坐標
success: function(res){
wx.openLocation({
latitude: res.latitude, // 緯度,范圍為-90~90,負數表示南緯
longitude: res.longitude, // 經度,范圍為-180~180,負數表示西經
scale: 28, // 縮放比例
})
},
})
},
//**
starRun :function () {
if (starRun == 1) {
return;
}
starRun = 1;
count_down(this);
this.getLocation();
},
//**
stopRun:function () {
starRun = 0;
count_down(this);
},
//**
updateTime:function (time) {
var data = this.data;
data.time = time;
this.data = data;
this.setData ({
time : time,
})
},
//**
getLocation:function () {
var that = this
wx.getLocation({
type: 'gcj02', // 默認為 wgs84 返回 gps 坐標,gcj02 返回可用于 wx.openLocation 的坐標
success: function(res){
console.log("res----------")
console.log(res)
//make datas
var newCover = {
latitude: res.latitude,
longitude: res.longitude,
iconPath: '/resources/redPoint.png',
};
var oriCovers = that.data.covers;
console.log("oriMeters----------")
console.log(oriMeters);
var len = oriCovers.length;
var lastCover;
if (len == 0) {
oriCovers.push(newCover);
}
len = oriCovers.length;
var lastCover = oriCovers[len-1];
console.log("oriCovers----------")
console.log(oriCovers,len);
var newMeters = getDistance(lastCover.latitude,lastCover.longitude,res.latitude,res.longitude)/1000;
if (newMeters < 0.0015){
newMeters = 0.0;
}
oriMeters = oriMeters + newMeters;
console.log("newMeters----------")
console.log(newMeters);
var meters = new Number(oriMeters);
var showMeters = meters.toFixed(2);
oriCovers.push(newCover);
that.setData({
latitude: res.latitude,
longitude: res.longitude,
markers: [],
covers: oriCovers,
meters:showMeters,
});
},
})
}
})</code></pre>