uniapp在规定坐标内执行任务
xuexi 2025-03-17 11:47:58 发表在:VUE 查看数:168

在data中先定义好

message: '',
        targetLatitude: 30.052943, // 目标纬度
        targetLongitude: 103.114852, // 目标经度
        allowedDistance: 200, // 允许的最大距离(米)
// 定位巡检开始
                    // 获取高精度定位
    // 获取用户位置并判断是否在巡检范围内
    uni.getLocation({
      type: 'wgs84', // 使用国际标准的经纬度坐标系
      success: (res) => {
        const userLatitude = res.latitude; // 用户当前纬度
        const userLongitude = res.longitude; // 用户当前经度

        // 计算用户与目标点的距离
        const distance = calculateDistance(
          userLatitude,
          userLongitude,
          this.targetLatitude,
          this.targetLongitude
        );

        // 判断是否在允许范围内
        if (distance <= this.allowedDistance) {
          this.message = '您已在巡检范围内,可以开始巡检。';

          // 在这里执行巡检逻辑
        } else {
          this.message = `您不在巡检范围内,距离目标点还有 ${distance.toFixed(2)} 米。`;

                    uni.showModal({
                    title: '您不在巡检范围内',
                    icon: 'error',
                    content: uni.getStorageSync('name')+`您不在巡检范围内,距离目标点还有 ${distance.toFixed(2)} 米。`,
                    showCancel: false
              });

        }
      },
      fail: (err) => {
        this.message = '获取位置失败,请检查定位权限是否开启。';
        console.error('获取位置失败:', err);
      },
    });

    // 计算两个坐标点之间的距离(Haversine 公式)
    function calculateDistance(lat1, lon1, lat2, lon2) {
      const toRadians = (degree) => degree * (Math.PI / 180); // 角度转弧度
      const R = 6371000; // 地球半径,单位:米

      const dLat = toRadians(lat2 - lat1); // 纬度差
      const dLon = toRadians(lon2 - lon1); // 经度差

      const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(toRadians(lat1)) *
          Math.cos(toRadians(lat2)) *
          Math.sin(dLon / 2) *
          Math.sin(dLon / 2);

      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

      return R * c; // 返回距离,单位:米
        }

        // 定位巡检结束
最近访问时间:2025-05-01 07:26:14
知识库:340条鸣谢:TAY  备案号:蜀ICP备2024090044号