uni-app 小程序获取实时定位和车辆签到(wx.onLocationChange方法)
1、需求描述
实现一个车辆定位签到功能,获取当前车辆的实时定位,当车辆到达签到点1公里范围内时,可以进行签到,当大于1公里时,禁止签到。同时用户还可以手动刷新定位。
2、wx.getLocation弊端
在小程序中,我们使用wx.getLocation api来获取经纬度,但是该api存在一个弊端,就是频繁调用会增加电量损耗,30秒内调用getLocation,仅第一次有效,剩余返回fail。
wx.getLocation({type: 'wgs84',success (res) {console.log(res.latitude, res.longitude)}
})
3、解决方法
若需要实时的来监听车辆定位,那么则不采取wx.getLocation,需要使用wx.onLocationChange,具体的流程图如下所示:
4、核心代码
<template><view class="container"><view class="map-box"><map id="myMap" :scale="14" :latitude="myLat" :longitude="myLon" :markers="markers" :circles="circles"></map><view class="local-icon" @click="handleRefresh"></view></view><view class="btn-box"><view class="submit" v-if="distance <= radius" @click="handleArrive">请先到达签到范围,后确认签到</view><view class="submit2" v-else @click="handleSign">确认签到</view></view></view>
</template>
<script>import { host } from '../../config/config.js'export default {name: 'sign',data() {return {centerLon: 0, // 中心经度centerLat: 0, // 中心纬度circles: [], // 中心签到圈radius: 0, // 签到半径myLon: 0, // 当前定位经度myLat:0, // 当前定位纬度markers: [], // 当前定位标记点distance: 99999,// 车辆到签到中心点距离}},methods: {// 获取中心点坐标, 获取签到圈getCoordinate() {uni.request({url: host + '/api/getCoordinate',method: 'GET',header:{'Content-Type' : 'application/json',token : uni.getStorageSync("TOKEN")},data: {},success: res => {if(res.data.code === "0") {this.centerLon = res.data.data.longitude;this.centerLat = res.data.data.latitude;this.radius = res.data.data.radius;this.circles = [{longitude: this.centerLon,latitude: this.centerLat,fillColor: "rgba(255,42,65,0.08)",color: "#FF0000",radius: this.radius,strokeWidth: 1}]}},fail: () => {},complete: () => {}});},async authorization() {try {await this.getWxLocation();} catch (error) {uni.showModal({title: '温馨提示',content: '获取权限失败,需要获取您的地理位置才能为您提供更好的服务!是否授权获取地理位置?',success: (res) => {if (res.confirm) {this.handleOpenSettng();}}});return;}},// 获取定位getWxLocation() {uni.showLoading({title: '定位中...'});return new Promise((resolve, reject) => {console.log("定位中...");// 开启定位追踪wx.startLocationUpdate({success: (res) => {console.log("开启定位追踪", res);wx.onLocationChange(this.handleLocationChange);resolve();},fail: (err) => {console.log('获取当前位置失败', err);uni.hideLoading();reject();}})})},// 用户授权定位handleOpenSettng() {console.log("获取用户授权");wx.openSetting({success: (res) => {if (res.authSetting["scope.userLocation"]) { // 用户同意授权console.log("用户同意授权");this.authorization();}}})},// 关闭定位追踪stopLocation() {wx.offLocationChange(this.handleLocationChange);return new Promise((resolve, reject) => {wx.stopLocationUpdate({success: (res) => {console.log("关闭定位追踪", res);resolve();},fail: (err) => {reject();},});})},// 刷新定位async handleRefresh() {await this.stopLocation();this.authorization();},// 监听到定位变化, 绘制定位点handleLocationChange(res) {console.log('定位改变, 绘制定位点:', res);this.myLon = res.longitude;this.myLat = res.latitude;this.markers = [{id: 1,longitude: this.myLon,latitude: this.myLat,iconPath: "../../static/img/record/point.png",width: 25,height: 25}]this.distance = this.getDistance();uni.hideLoading();},// 获取当前位置距离签到点的距离getDistance() {let red1 = this.myLat * Math.PI / 180.0;let red2 = this.centerLat * Math.PI / 180.0;let a = red1 - red2;let b = this.myLon * Math.PI / 180.0 - this.centerLon * Math.PI / 180.0;let R = 6378137;let distance = R * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(red1) * Math.cos(red2) * Math.pow(Math.sin(b / 2), 2)));return distance.toFixed(2) * 1;}},onLoad(option) {this.getCoordinate();this.authorization();},onUnload() {this.stopLocation();}}
</script>
<style lang="less" scoped>
</style>
5、补充
2022 年 7 月 14 日后,微信小程序对wx.onLocationChange API的使用场景做了限制,很多的场景都不允许再使用wx.onLocationChange方法,后续我补充发布了一篇使用wx.getLocation的签到方法,大家可以看看,见链接 uni-app 小程序获取实时定位和车辆签到(wx.getLocation方法)
uni-app 小程序获取实时定位和车辆签到(wx.onLocationChange方法)相关推荐
- uni-app 小程序获取实时定位和车辆签到(wx.getLocation方法)
一.需求描述 实现一个车辆定位签到功能,获取当前车辆的实时定位,当车辆到达签到点1公里范围内时,可以进行签到,当大于1公里时,禁止签到.同时用户还可以手动刷新定位. 二.wx.getLocation ...
- 微信小程序获取实时定位(记录)
首先在app.json里配置: "requiredBackgroundModes": ["location"] 在需要定位的页面js里: getUserLoca ...
- 解决通过微信小程序获取的定位坐标在百度地图渲染误差过大问题
微信小程序可以获取两种坐标系的经纬度,分别为WGS84(大地坐标系)和GCJ02(国测局坐标系)而百度却是在其基础上进行加密形成了自己的一套坐标系bd09(百度坐标系),如果直接用微信小程序获取的经纬 ...
- 微信小程序获取当前定位 超简单
1:去腾讯地图官网下载地图工具包放到lib文件夹下 2:在所用的js里引入 var QQMapWX = require("../../libs/qqmap-wx-jssdk.js" ...
- uni.app小程序的ajax封装详细讲解
我懒得说了 //放url相同的片段 const rootUrl = ""// 示例: ajax({ url:'/api/login', param: param, method: ...
- 微信小程序获取实时天气
一.实验目标 1.掌握服务器域名配置和临时服务器部署:2.掌握 wx.request 接口的用法. 二.实验步骤 1.使用和风天气申请key 2.导航栏设计 3.页面设计 4.逻辑实现 更新地区信息 ...
- uni.app小程序实现跳转获取数据
式例如上图所示 (前提是点击索引获得的id与获得数据的id是一样的) 首先是获取文档的数据 我用的async await来获取数据,也可以用.then方法获取数据 async onLoad() {le ...
- uni.app小程序登录页持久化存储和退出后清除本地缓存
持久化存储 在store里面的user.js(自己创建的)中 export default {state: {status: false, //登录的状态,获取数据中status是1,登录成功时状态为 ...
- uni.app小程序失焦聚焦,表单验证
<input type="text" placeholder="请输入手机号/邮箱/账号" v-model="username" @f ...
最新文章
- 大数据时代,如何构建精准用户画像,直击精细化运营
- python web-Python的哪个Web框架学习周期短,学习成本低?
- python协程库_python中协程的详解(附示例)
- 6.2 常见多媒体标准及压缩技术
- python字频统计软件_python结巴分词以及词频统计实例
- 前端学习(3122):react-hello-react总结state
- 《剑指Offer》62:圆圈中最后剩下的数字(约瑟夫环)
- Java消息服务~@JmsListener集成
- 终端到服务器丢包,服务器丢包 ping的时候产生丢包的解决方法
- 第五课 vim基本用法、bash编程初步和for循环
- python groupby 不保留源index、_Python数据分析 I 全国旅游景点分析案例,哪里好玩一目了然...
- 【编译原理笔记01】什么是编译,编译系统各结构作用
- Linux 常用基础命令(入门版)
- 微信小程序腾讯云实时语音转写
- 颜色对照表(四)(16进制、RGB、CMYK、HSV、中英文名)
- linux的ls -l显示的total 4是什么意思?我使用ls -a -l显示的total12,同一个文件夹显示了不同的信息?
- 【STC15】定时器/计数器的相关寄存器解读
- ubuntu18.04 桌面不定时crash重置问题
- WKwebview弹框报错Attempt to present UIAlertController on XXwhich is already presenting (null)
- javaSE基础全覆盖