天天看点

微信小程序中自定义导航和地图定位

在健康码中,主要的难点技术就是在小程序中定位、自定顶部导航。

自定义导航

在微信小程序中,默认的顶部导航不能设置图片背景或者是透明背景,只能自定义导航。

在每一个页面中引入,就是得到自己定义【个性化的】导航。

第一步:

现在app.json文件中配置

"window": {
    "navigationStyle": "custom"
  },      

​"navigationStyle": "custom"​

​设置为使用自定义导航。

第三步:

开始定义导航

navbar.wxml:

<view class='nav-wrap'>
  <!-- 导航栏背景图片 -->
  <!-- <image class="backgroundimg" src="{{bg}}" bindload="imgLoaded"/> -->
  <!-- // 导航栏 中间的标题 -->
  <view class='nav-title'  style='line-height: {{height*2 + 44}}px; color:#fff'>
    {{navbarData.title}}
  </view>
</view>      

navbar.js

const app = getApp()
Component({
  properties: {
    navbarData: {
      //navbarData   由父页面传递的数据,变量名字自命名
      type: Object,
      value: {},
      observer: function(newVal, oldVal) {}
    }
  },
  data: {
    height: '',
    //默认值  默认显示左上角
    navbarData: {
      showCapsule: 1
    },
    imageWidth: wx.getSystemInfoSync().windowWidth, // 背景图片的高度
    imageHeight: '', // 背景图片的长度,通过计算获取
    
  },
  attached: function() {
    // 获取是否是通过分享进入的小程序
    this.setData({
      share: app.globalData.share
    })
    // 定义导航栏的高度   方便对齐
    this.setData({
      height: app.globalData.height
    })
  },
  methods: {
    // 返回上一页面
    _navback() {
      wx.navigateBack()
    },
    // 计算图片高度
    imgLoaded(e) {
      console.log(e.detail.height)
      this.setData({
        imageHeight: e.detail.height *  
          (wx.getSystemInfoSync().windowWidth / e.detail.width)
      })
    },
    tapName: function () {
      console.log(0)
    }
    //返回到首页
    // _backhome() {
    //   wx.switchTab({
    //     url: '/pages/index/index'
    //   })
    // }
  },
})      

在app.js中获取设备顶部窗口的高度,会根据这个值来设置自定义导航栏的高度

//app.js
App({
  onLaunch: function(e) {
    console.log(e)
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
    wx.getSystemInfo({
      success: res => {
        console.log(res)
        this.globalData.height = res.statusBarHeight
      }
    })
  },
  globalData: {
    userInfo: null,
    height: 0 // 顶部高度
  }
})      

navbar.wxss

/* navbar.wxss */

/* 顶部要固定定位   标题要居中   自定义按钮和标题要和右边微信原生的胶囊上下对齐 */

.nav-wrap {
  position: fixed;
  width: 100%;
  top: 0;
  background-image: linear-gradient(#2f52bc, #9198e5, #d0d9f4);
  color: #000;
  z-index: 9999999;
  overflow: hidden;
  height: 400rpx;
}

/* 背景图 */
.backgroundimg {
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
}

/* 标题要居中 */

.nav-title {
  position: absolute;
  text-align: center;
  max-width: 400rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  font-size: 36rpx;
  color: #2c2b2b;
  font-weight: 450;
}

.nav-capsule {
  display: flex;
  align-items: center;
  margin-left: 30rpx;
  width: 140rpx;
  justify-content: space-between;
  height: 100%;
}

.back-pre {
  width: 32rpx;
  height: 36rpx;
  margin-top: 4rpx;
  padding: 10rpx;
}

.nav-capsule {
  width: 36rpx;
  height: 40rpx;
  margin-top: 3rpx;
}
      

navbar.json:

{
  "component": true,
  "usingComponents": {}
}      

在index中引入导航

index.json:

{
  "usingComponents": {
    "nav-bar": "../component/navbar/index"
  },
  "navigationBarTextStyle": "white"
  
}      

index.js:

Page({
    data:[
        nvabarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          title: '健康码', //导航栏 中间的标题
          white: true, // 是就显示白的,不是就显示黑的。
        }
    ]
})      

index.wxml:

<nav-bar navbar-data='{{nvabarData}}'></nav-bar>      

以上是首页引用的自定义导航,重新定义其他页面的导航:

wxml:

<view class='nav-wrap'>
  <!-- 导航栏背景图片 -->
  <!-- <image class="backgroundimg" src="{{bg}}" bindload="imgLoaded"/> -->
  <!-- // 导航栏 中间的标题 -->
  <view class='nav-title' wx:if='{{!navbarData.white}}' style='line-height: {{height*2 + 44}}px;'>
    {{navbarData.title}}
  </view>
  <view class='nav-title' wx:else='{{!navbarData.white}}' style='line-height: {{height*2 + 44}}px; color:#fff'>
    {{navbarData.title}}
  </view>
  <view style='display: flex; justify-content: space-around;flex-direction: column'>
    <view class='nav-capsule' style='height: {{height*2 + 44}}px;'>
      <view bindtap='_navback'>
        <image src='{{backIcon}}' mode='aspectFit' class='back-pre'></image>
      </view>
    </view>
  </view>
</view>      

wxss:

/* navbar.wxss */

/* 顶部要固定定位   标题要居中   自定义按钮和标题要和右边微信原生的胶囊上下对齐 */

.nav-wrap {
  position: fixed;
  width: 100%;
  top: 0;
  background-image: linear-gradient(#2f52bc, #9198e5, #d0d9f4);
  color: #000;
  z-index: 9999999;
  overflow: hidden;
  
}

/* 背景图 */

.backgroundimg {
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
}

/* 标题要居中 */

.nav-title {
  position: absolute;
  text-align: center;
  max-width: 400rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  font-size: 36rpx;
  color: #2c2b2b;
  font-weight: 450;
}

.nav-capsule {
  display: flex;
  align-items: center;
  margin-left: 30rpx;
  width: 140rpx;
  justify-content: space-between;
  height: 100%;
}

.back-pre {
  width: 32rpx;
  height: 36rpx;
  margin-top: 4rpx;
  padding: 10rpx;
}

.nav-capsule {
  width: 36rpx;
  height: 40rpx;
  margin-top: 3rpx;
}      

json:

{
  "component": true,
  "usingComponents": {}
}      

js:

const app = getApp()
Component({
  properties: {
    navbarData: {
      //navbarData   由父页面传递的数据,变量名字自命名
      type: Object,
      value: {},
      observer: function(newVal, oldVal) {}
    }
  },
  data: {
    height: '',
    //默认值  默认显示左上角
    navbarData: {
      showCapsule: 1
    },
    imageWidth: wx.getSystemInfoSync().windowWidth, // 背景图片的高度
    imageHeight: '', // 背景图片的长度,通过计算获取
    backIcon: "../../img/fanhui.png",
  },
  attached: function() {
    // 获取是否是通过分享进入的小程序
    this.setData({
      share: app.globalData.share
    })
    // 定义导航栏的高度   方便对齐
    this.setData({
      height: app.globalData.height
    })
  },
  methods: {
    // 返回上一页面
    _navback() {
      wx.navigateBack()
    },
    // 计算图片高度
    imgLoaded(e) {
      console.log(e.detail.height)
      this.setData({
        imageHeight: e.detail.height *  
          (wx.getSystemInfoSync().windowWidth / e.detail.width)
      })
    },
    tapName: function() {
      console.log(0)
    }
    //返回到首页
    // _backhome() {
    //   wx.switchTab({
    //     url: '/pages/index/index'
    //   })
    // }
  },
})      

其实可以不用定义两个导航,只要navbar.js判断是否是通过分享进入小程序或者是当前页面是否是首页,来决定隐藏/显示导航左上角的返回按钮。

地图定位

在监听小程序初次渲染完成时,通过api​

​wx.getLocation​

​获取小程序当前的经纬度,再通过经纬度在地图给小程序进行定位。但是这个API需要用户授权后才能获取到,只需要在首次打开小程序时 进行授权即可。

在app.json设置:

"permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
  }      
微信小程序中自定义导航和地图定位

授权过后,在首页的index.js中的​

​onReady​

​监听页面渲染函数中获取小程序的经纬度:

onReady: function() {
    const that = this;
    const markers = that.data.markers;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        markers.latitude = res.latitude;
        markers.longitude = res.longitude;
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          markers: markers
        })
        const latitude = res.latitude
        const longitude = res.longitude
      }
    })
  },      

index.js完整代码如下:

//index.js
//获取应用实例
const app = getApp()
Page({
  data: {
    markers: [{  //地图标注的信息
      iconPath: "../resources/location.png",
      id: 0,
      latitude: 26.64702,
      longitude: 106.63024,
      width: 50,
      height: 50
    }],
    latitude: 26.64702,
    longitude: 106.63024,
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '健康码', //导航栏 中间的标题
      white: true, // 是就显示白的,不是就显示黑的。
    },
    // 导航头的高度
    height: app.globalData.height * 2 + 20,

    userImg: "../img/user1.png",
    cradImg: "../img/user2.png",
    clickCradimg: "../img/jilu.png",
    rightimg: "../img/rightimg.png"
  },
  onLoad: function() {},
  onReady: function() {
    const that = this;
    const markers = that.data.markers;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(res)
        markers.latitude = res.latitude;
        markers.longitude = res.longitude;
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          markers: markers
        })
        const latitude = res.latitude
        const longitude = res.longitude
      }
    })
  },
  login: function() {
    wx.navigateTo({
      url: '/pages/userinfo/index',
    })
  },
  card: function() {
    wx.navigateTo({
      url: '/pages/card/index',
    })
  },
  punchCard: function() {
    wx.navigateTo({
      url: '/pages/punchcard/index',
    })
  }
})      
<nav-bar navbar-data='{{nvabarData}}'></nav-bar>
<map id="map" longitude="{{longitude}}" latitude="{{latitude}}" scale="14" bindcontroltap="controltap" markers="{{markers}}"  show-location>
</map>

<view class="info">
  <view class="login" bindtap="login">
    <image src="{{userImg}}"></image>
    <view>信息登录</view>
  </view>
  <view class="crad" bindtap="card">
    <image src="{{cradImg}}"></image>
    <view>健康卡</view>
  </view>
</view>
<view class="clickCrad" bindtap="punchCard">
  <view class="left">
    <image class="cradImg" src="{{clickCradimg}}"></image>
    <view>每日健康打卡</view>
  </view>
  <image src="{{rightimg}}" class="rightImg"></image>
</view>      
#map {
  width: 100%;
  height: 100%;
}

.info {
  position: fixed;
  top: 250rpx;
  padding: 30rpx 100rpx;
  background: #fff;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  z-index: 99999999999;
  left: 0;
  right: 0;
  margin: 0 40rpx;
}

.info image {
  width: 100rpx;
  height: 100rpx;
}

.login {
  text-align: center;
}

.crad {
  text-align: center;
}

.clickCrad {
  background: #fff;
  margin: 10rpx 40rpx 20rpx 40rpx;
  padding: 20rpx 100rpx;
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  top: 500rpx;
  right: 0;
  left: 0;
  z-index: 999999999999;
}

.left {
  display: flex;
  align-items: center;
}

.cradImg {
  width: 50rpx;
  height: 50rpx;
  margin-right: 10px;
}

.rightImg {
  width: 35rpx;
  height: 35rpx;
}