微信小程序开发笔记

html

条件渲染

详情参考: https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/conditional.html

<!-- .html 文件 -->
<!-- length 来自 .js 文件中的 data 变量 -->

<view wx:if="{{length > 5}}"> 1 </view>
<view wx:elif="{{length > 2}}"> 2 </view>
<view wx:else> 3 </view>

列表渲染

详情参考: https://developers.weixin.qq.com/miniprogram/dev/reference/wxml/list.html

<!-- .html 文件 -->
<!-- array 是来自 .js 中的 data 数值型变量,里面的元素类型为 Object类型 Object对象类型形式为:{key:value} 键:值 -->
<!-- 使用 wx:for-item 可以指定数组当前元素的变量名,使用 wx:for-index 可以指定数组当前下标的变量名: -->

<view
 wx:for="{{array}}"
 wx:for-index="idx"
 wx:for-item="itemName"
>
	{{idx}}: {{itemName.message}}
</view>

// .js 文件

data: {
  array: [{
    message: 'foo',
  }, {
    message: 'bar'
  }]
}

按钮组件 button

详情参考: https://developers.weixin.qq.com/miniprogram/dev/component/button.html
按钮css样式参考: https://www.runoob.com/css3/css3-buttons.html

<!-- .html 文件 -->
<!-- 设置登录按钮,type=的样式类型,bindtap=绑定按键点击事件的响应函数 -->
<!-- button组件的,详情参考:https://developers.weixin.qq.com/miniprogram/dev/component/button.html -->

<button type='primary' bindtap="signIn">登录</button>

// .js 文件
// 点击事件的响应函数写法

signIn(e) {
    console.log('用户点击登录按钮')
    console.log('打印事件e的详情\t---e:\t', e)
  },
  

css

详情参考: https://www.runoob.com/css/css-intro.html

单位 rpx、px、vw、vh、rem

/* 微信小程序中的单位
px:
像素,图片采样的基本单位。
Vw:
视窗宽度,1vw等 于窗口宽度的1%
vh:
视窗高度、1wh等于窗口高度的1%
rem:
规定屏幕宽度为20rem,实际.上是把页面按比例分割达到自适应的效果(把页面宽度分成20份)
rpx:
规定屏幕宽度为750rpx,以此来根据屏幕宽度进行自适应。如在iphone6 上,屏幕宽度为375px,共有750个物理像素,则
750rpx=375px=750物理像素,相当于1rpx=0.5px=1物理像素。 */

定位方法

/* 页面定位
选择器{ position: relative; }
相对定位的特点: (务必记住)
1.它是相对于自己原来的位置来移动的(移动位置的时候参照点是自己原来的位置)。
2.原来在标准流的位置继续占有,后面的盒子仍然以标准流的方式对待它。(不脱标,继续保留原来位置)

选择器{ position: absolute; }
绝对定位的特点: (务必记住)
1.如果没有祖先元素或者祖先元素没有定位,则以浏览器为准定位( Document文档)。
2.如果祖先元素有定位(相对、绝对、固定定位) , 则以最近一级的有定位祖先元素为参考点移动位置。
3.绝对定位不再占有原先的位置。(脱标) */

设置图片为页面的背景

<!-- .html 文件 -->

<view class='background'>
	<!-- 添加背景图片 -->
	<image src='../../images/icon/background.jpg' mode='aspectFill'></image>
	<!-- 添加背景图片的蒙层 -->
	<view></view>
</view>

/* .css 文件 */

/* 背景图片 */
.background>image {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: -999;
}

/* 背景图片上层的蒙层 */
.background>view {
    background-color: rgba(255, 255, 255, 0.15);
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: -900;
}

自定义按钮的图标

<!-- .html 文件 -->

<button
	class="building-btn"
	size="mini"
	bindtap="showBuildingComplex"
>
	<image
		src='...'
		class="building-btn-img"
		mode='aspectFit'
	></image>
</button>

/* .css 文件 */

/* 建筑物图标按钮 */
.building-btn {
  padding: 0;
  /*按钮透明*/
  background-color: transparent;
  /*设置按钮边框*/
  border: none;
  width: 10vw;
  height: 10vh;
}

/* 建筑物图标 */
.building-btn-img {
  width: 10vw;
  height: 10vh;
}

js

全局变量

// app.js
// 全局变量,在每一个文件中都可以用
// 使用时,需要结合先定义var app = getApp(),然后再app.globalData.student引用
    this.globalData = {
      student: {
        _id: '',
        password: ''
      }
    };
    
// 在其他 .js 文件获取全局变量

var app = getApp()
this.setData({
      student: app.globalData.student,
    })
    

底部导航栏 tabBar

详情参考: https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html#tabBar

// 在 app.json 中

"tabBar": {
    "list": [
      {
        "pagePath": "",
        "text": "",
        "iconPath": "",
        "selectedIconPath": ""
      },
      {
        "pagePath": "",
        "text": "",
        "iconPath": "",
        "selectedIconPath": ""
      }
    ]
  },
  

其他

配置config.js

// config.js 文件

module.exports = {
  "appName": "应用",
  "default_scale": 16,
  "buildingComplexNameAndIconPath": [],
}

// 在其他 .js 文件中使用 config.js 的数据

// 加载 config.js 文件
const config = require('../../config.js');

// 使用配置文件中的参数
config.default_scale

带参数跳转页面

详情参考: https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.navigateTo.html

    // .js 文件
    // wx.navigateTo,详情参考:https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.navigateTo.html
    // url传参,详情参考:https://blog.csdn.net/weixin_43970434/article/details/98876750
    // 跳转至当前建筑物详情的界面,传递变量名为 building 的参数,传参时变量必须用字符串
    // 所以可以在当前界面使用 JSON.stringify() 转化为 JSON 字符串,在目的地界面使用 JSON.parse() 转化为 JavaScript 对象
    // JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串
    // JSON.parse() 方法将数据转换为 JavaScript 对象
    
    wx.navigateTo({
      url: '../detailsBuilding/detailsBuilding?building=' + JSON.stringify(building),
    })
  },
  

云数据库的使用

初始化

详情参考: https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/init.html

// .js 文件
// 调用云数据库 const db=wx.cloud.database()

const db = wx.cloud.database()

查找

详情参考:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/read.html
通过调用集合上的 where 方法可以指定查询条件,再调用 get 方法即可只返回满足指定查询条件的记录,

// .js 文件

db.collection('Site').where({ buildingComplexName: this.data.buildingComplexName }).get().then(res => {
      console.log('从云数据库Site数据集中,获得了' + res.data.length + '条数据')
})

地图组件 map

从云数据库中调用经纬度,并且使用 marker 渲染标记点

详情参考:https://developers.weixin.qq.com/miniprogram/dev/component/map.html#marker

<!-- .html 文件 -->

<map
 class="map"
 scale="{{defaultScale}}"
 longitude='{{longitude}}'
 latitude='{{latitude}}'
 show-location="{{true}}"
 markers="{{markers}}"
 polyline="{{polyline_Object}}"
 bindmarkertap="detailsBuilding"
 bindlabeltap="detailsBuilding"
>
    // .js 文件
    // 调取云数据库中的Site数据集,
    // 查询属性buildingComplexName的值为this.data.building的数据
    
    db.collection('Site').where({ buildingComplexName: this.data.buildingComplexName }).get().then(res => {
      console.log('从云数据库Site数据集中,获得了' + res.data.length + '条数据')

      // 将云数据库中的相关数据值转换为可用合法的markers值
      // 标记点用于在地图上显示标记的位置,详情参考:https://developers.weixin.qq.com/miniprogram/dev/component/map.html#marker
      for (let i = 0; i < res.data.length; i++) {
        let markObj = {
          id: i,                            // 当前标记点的编号
          latitude: res.data[i].latitude,   // 当前标记点的维度
          longitude: res.data[i].longitude, // 当前标记点的经度
          iconPath: markersIconPath,        // 当前标记点的图标路径
          width: config.iconHeight,         // 当前标记点的图标的宽
          height: config.iconWidth,         // 当前标记点的图标的宽
          zIndex: i + 1,                    // 当前标记点的图标图层
          // 当前标记点的标签显示
          label: {
            content: res.data[i].buildingName,   // 当前标记点的标签文字
            color: config.iconLabelColor,
            fontSize: config.iconLabelFontSize,
            anchorX: config.iconLabelAnchorX,
            anchorY: config.iconLabelAnchorY,
            borderWidth: config.iconLabelBorderWidth,
            borderColor: config.iconLabelBorderColor,
            borderRadius: config.iconLabelBorderRadius,
            bgColor: config.themeColors,
            padding: config.iconLabelPadding,
          }
        }

        // 将当前的标记点带加入标记点集合中
        this.data.markers.push(markObj)
      }

      // 更新当前的标记点集合,相当于刷新显示
      // 并且将获取到的建筑物群信息赋值给this.data.buildingComplex
      this.setData({
        markers: this.data.markers,
        buildingComplex: res.data
      })
      console.log("当前获取的标记点详情为:\t---this.data.markers:\t\t\t", this.data.markers, "\n")
      console.log("当前获取的建筑群详情为:\t---this.data.buildingComplex:\t", this.data.buildingComplex, "\n")
    })

实时监控用户位置变化

详情参考: https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.startLocationUpdate.html

    // .js 文件
    // wx.startLocationUpdate,开启小程序进入前台时接收位置消息。详情参考:https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.startLocationUpdate.html
    // 注意,需要在 app.json 中配置 "requiredPrivateInfos": ["startLocationUpdate"]
    
    wx.startLocationUpdate({
      success: (res) => {
        type: 'gcj02',
          // wx.onLocationChange,监听实时地理位置变化事件。详情参考:https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.onLocationChange.html
          // 需要配合,移除实时地理位置变化事件的监听函数wx.offLocationChange使用——【 wx.offLocationChange(this.data.locationChangeFn)】。详情参考:https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.offLocationChange.html
          // 注意,需要在 app.json 中配置 "requiredPrivateInfos": ["onLocationChange"]
          wx.onLocationChange(this.data.locationChangeFn)
        console.log('开启小程序进入前台时接收位置消息函数wx.startLocationUpdate的返回值\t---res:\t', res)
      },
      fail: (err) => {
        // 重新获取位置权限
        wx.openSetting({
          success(res) {
            res.authSetting = {
              "scope.userLocation": true
            }
          }
        })
        reject(err)
      }
    })
    

调用腾讯位置服务微信小程序 JavaScript SDK 实现实时路线规划

详情参考: https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/methodDirection

  1. 申请开发者密钥(key):申请密钥
  2. 开通webserviceAPI服务:控制台 ->应用管理 -> 我的应用 ->添加key-> 勾选WebServiceAPI -> 保存
    (小程序SDK需要用到webserviceAPI的部分服务,所以使用该功能的KEY需要具备相应的权限)
  3. 下载微信小程序JavaScriptSDK,微信小程序JavaScriptSDK v1.1 JavaScriptSDK v1.2
  4. 安全域名设置,在小程序管理后台 -> 开发 -> 开发管理 -> 开发设置 -> “服务器域名” 中设置request合法域名,添加https://apis.map.qq.com
  5. 小程序示例
    在这里插入图片描述
<!-- .html 文件 -->

<map
 class="map"
 scale="{{defaultScale}}"
 longitude='{{longitude}}'
 latitude='{{latitude}}'
 show-location="{{true}}"
 markers="{{markers}}"
 polyline="{{polyline_Object}}"
>
    // .js 文件
    // 位置改变时,执行当前函数,wx.onLocationChange(function listener)的示例代码,详情参考:https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.onLocationChange.html#%E7%A4%BA%E4%BE%8B%E4%BB%A3%E7%A0%81
    
    this.data.locationChangeFn = function (res) {
      console.log('位置开始改变,获取\t---res:\t', res)

      // 实时更新用户当前的位置,也是路线的开始位置,即start_address
      // 同时将用户当前的位置设置为地图的中心位置
      that.setData({
        latitude: res.latitude,
        longitude: res.longitude,
        default: 20,
        start_address: {
          longitude: res.longitude,
          latitude: res.latitude
        }
      })

      console.log('获取起始位置为\t---that.data.start_address:\t', that.data.start_address)
      console.log('获取终点位置为\t---that.data.end_address:\t', that.data.end_address)


      // 使用腾讯位置服务,调用距离计算接口
      // 详情参考:https://lbs.qq.com/service/webService/webServiceGuide/webServiceRoute#3 
      // 以及以下网页,特别是其中的‘Javascript 关键代码片段(驾车、步行、骑行路线规划):’:https://lbs.qq.com/miniProgram/jsSdk/jsSdkGuide/methodDirection
      qqmapsdk.direction({
        // 路线规划选择
        mode: 'walking',
        // 起始位置坐标,采用Object格式
        from: {
          latitude: that.data.start_address.latitude,
          longitude: that.data.start_address.longitude
        },
        // 终点位置坐标,采用Object格式
        to: {
          latitude: that.data.start_address.latitude,
          longitude: that.data.end_address.longitude
        },
        // // 用于测试的几组数据,不用看
        // from: {
        //   latitude: 29.9781013308885,
        //   longitude: 103.000237941741
        // },
        // to: {
        //   latitude: 29.9774832826657,
        //   longitude: 102.993076443672
        // },

        success: function (res) {
        
          console.log('\n开始规划路线');

          console.log('调用距离计算接口qqmapsdk.direction的返回值\t---res:\t', res);

          // res.status状态码,正常为0
          if (res.status == 0) {

            // 解压路线坐标点串
            let coors = res.result.routes[0].polyline;
            for (let i = 2; i < coors.length; i++) {
              coors[i] = coors[i - 2] + coors[i] / 1000000
            }
            console.log('路线坐标点串解压完毕!路线坐标点串解压结果如下:\c---oors:', coors)

            // 将解压后的坐标点串进行拼接成polyline想要的样子
            var coors_new = []
            for (var j = 0; j < coors.length; j++) {
              coors_new.push({
                latitude: parseFloat(coors[j]),
                longitude: parseFloat(coors[j + 1])
              })
              j++;
            }

            // 更新路线
            that.setData({
              polyline_Object: [{
                points: coors_new,
                color: "#3FB837",
                width: 5,
                dottedLine: false
              }]
            })
          }

          console.log('当前的路线为:\t---that.polyline_Object:\t', that.data.polyline_Object);
        },
        fail: function (res) {
          console.log('调用路线规划函数失败\t---res:\t', res);
        },
        complete: function (res) {
          console.log('调用路线规划函数结束\t---res:\t', res);
        }
      });

    }
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值