开源:weChatApp-Run - 跑步微信小程序

RubyKneebon 7年前
   <h2>一、准备工作</h2>    <p>首先注册一个小程序账号,得用一个没注册过公众号的邮箱注册。</p>    <p>注册过程中需要很多认证,比较繁琐。如果暂时只是开发测试,不进行提审、发布的话,只要完成营业执照号的填写就可以了,不需要完成微信认证。</p>    <p>注册完账号,并使用该帐号进行登录。</p>    <p>在主页面左边列表中点击设置,然后在设置页面中选开发设置,就可以看到AppID,用于登录开发工具。</p>    <p style="text-align: center;"><img src="https://simg.open-open.com/show/8f9daee0517e0916f8edad16512c0133.png"></p>    <p>主页面</p>    <p style="text-align: center;"><img src="https://simg.open-open.com/show/c2ac016ae4f58e581094145a8f2be1a6.png"></p>    <p>设置页面</p>    <h2>二、开发工具</h2>    <p style="text-align:center"><img src="https://simg.open-open.com/show/ec5e079eff58230255f3e7ddaf4ec8af.png"></p>    <p>开发工具</p>    <p style="text-align: center;"><img src="https://simg.open-open.com/show/8174181c9361b69b921c0509823fd2aa.png"></p>    <p>开发工具编辑页面</p>    <h2>三、开始项目</h2>    <p>打开开发者工具,选择小程序选项,到达“添加项目”页面。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/d9f3ded251aa67c8e63cc9eb998867ac.png"></p>    <p>“添加项目”页面</p>    <p>这个时候将前面设置页面中的AppID填写此处。</p>    <p>如果项目目录中的文件是个空文件夹,会提示是否创建quick start 项目。</p>    <p>选择“是”,开发者工具会帮助我们在开发目录里生成一个简单的 Demo。</p>    <p>这个Demo拥有一个完整的小程序的大概框架。</p>    <p>框架</p>    <p>先看下一目录:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/e1f93f777e2f01990704ccb56ce96744.png"></p>    <p>文件目录</p>    <ul>     <li>app.js: 小程序逻辑,生命周期,全局变量。</li>     <li>app.json: 小程序公共设置,导航栏颜色等,不可以注释。</li>     <li>app.wxss :小程序公共样式,类CSS。</li>    </ul>    <p>小程序页面构成:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/47d3fd7a48a1de1287d86c554768173d.png"></p>    <p>页面构成</p>    <p>每一个小程序页面是由同路径下同名的四个不同后缀文件的组成,如:index.js、index.wxml、index.wxss、index.json。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/d30ea1fa7f7a6ed7923463abf24bfa81.png"></p>    <p><strong>各文件介绍</strong></p>    <p>微信小程序中的每一个页面的“路径+页面名”都需要写在 app.json 的 pages 中,且 pages 中的第一个页面是小程序的首页。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/cca5d903776fb8cb1f85b8ccef5ab16f.png"></p>    <p><strong>路径</strong></p>    <p>这四个文件按照功能可以分成三个部分:</p>    <p>配置:json 文件。</p>    <p>逻辑层:js文件。</p>    <p>视图层:wxss.wxml文件。</p>    <p>在 iOS 上,小程序的 JavaScript 代码是运行在 JavaScriptCore 中。在 Android 上,小程序的 JavaScript 代码是通过 X5 内核来解析。</p>    <p>在开发工具上,小程序的 JavaScript 代码是运行在 NW.js(Chrome内核) 中。所以开发工具上的效果跟实际效果有所出入。</p>    <p><strong>组件</strong></p>    <p>微信提供了许多组件,主要分为八种:</p>    <ul>     <li>视图容器</li>     <li>基础内容</li>     <li>表单组件</li>     <li>操作反馈</li>     <li>导航</li>     <li>媒体组件</li>     <li>地图</li>     <li>画布</li>    </ul>    <p>包含view、scroll-view、button、form等普通常用的组件,也提供了地图map、画布canvas。</p>    <p>组件主要属于视图层,通过wxml来进行结构布局,类似于html。通过wxss修改样式,类似于css。</p>    <p>组件使用语法实例:</p>    <pre>  <code class="language-javascript"><!--普通视图-->  <view>这是一个普通视图</view>    <!--wxss样式修改-->  <view clas="mainView">样式修改过的视图</view></code></pre>    <p><strong>API</strong></p>    <p>小程序中,大致提供以下几个部分的 API 接口:</p>    <ul>     <li>网络</li>     <li>媒体</li>     <li>数据</li>     <li>位置</li>     <li>设备</li>     <li>界面</li>     <li>开发接口</li>    </ul>    <p>其中网络请求的使用必须先到公众平台登录小程序账号,在设置页面那里,设置允许访问的域名,网络请求包含了普通的HTTP请求、支持上传、下载、Socket。基本上满足了我们开发中所需要的网络需求。</p>    <p>这些API属于逻辑层,写在JavaScript文件中。</p>    <p>使用实例:</p>    <pre>  <code class="language-javascript">wx.getLocation({     type: 'wgs84',     success: function(res) {         var latitude = res.latitude          var longitude = res.longitude          var speed = res.speed          var accuracy = res.accuracy   }})</code></pre>    <p><strong>编译运行</strong></p>    <p>1.模拟器</p>    <p>可以在模拟器上看效果,上面提到了小程序的运行底层不同,效果在手机上运行也会有些差异。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/33e3b797437647fd68c838f9adada372.png"></p>    <p><strong>模拟器</strong></p>    <p>2.真机</p>    <p>在左边的选项栏中,选择项目,然后点预览会生产一个二维码,用管理员微信号扫一扫,就可以在真机上看实际效果。本例中,真机测试则扫描下面二维码。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/6141c700f97da81a3d78c94c71789828.png"></p>    <h2>实践:跑步小程序</h2>    <p>真机运行截图(运行于iPhone7,微信版本:6.3.30):</p>    <p style="text-align: center;"><img src="https://simg.open-open.com/show/c5e44d89359a6fd41a873a8a7ed1e21c.jpg"></p>    <p>功能:能够计算里程、时间、实时获取跑步路径(有些粗糙)。</p>    <p>思路:主要使用了微信小程序的获取位置接口APIwx.getLocation()和地图组件map。</p>    <p>首先实现一个计时器进行计时,通过wx.getLocation()获取坐标,把获取到的坐标存在一个数组中,通过坐标每隔一段时间获取里程,进行累加得到总里程,同时也通过坐标点进行连线。</p>    <p>存在的问题:</p>    <ol>     <li>因为目前找不到在地图上画连线的方法,所以采用了在地图上贴小红点图的方法显示大概跑步路径,路径比较粗糙。</li>     <li>虽然采用了API里面的火星坐标gcj02类型,但是获取的坐标跟国际坐标差不多,依然存在着偏差。</li>    </ol>    <p>核心代码:</p>    <p>我把全部代码放在github上: weChatApp-Run ,可以下载来看看或者先star收藏,我以后还会进行一些优化更新。现在只是一个学习Demo,大家沟通学习,实际应用还需更多优化。</p>    <p>wxml文件布局代码:</p>    <pre>  <code class="language-javascript"><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>    <p>JavaScript文件逻辑代码:</p>    <pre>  <code class="language-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>    <p> </p>