You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter考勤应用:如何禁止特定地点/经纬度提交考勤?

解决方案

1. 定义禁止考勤的区域参数

先明确办公地址的经纬度,以及禁止范围的半径(比如50米,可根据实际需求调整):

// 替换为实际办公地址的经纬度
final double officeLatitude = 31.2304; 
final double officeLongitude = 121.4737;
// 禁止提交考勤的范围半径,单位:米
final double forbiddenRadius = 50.0; 

2. 添加距离判断函数

利用geolocator自带的distanceBetween方法,计算当前位置与办公地址的直线距离,判断是否在禁止范围内:

bool _isInForbiddenArea(Position currentPosition) {
  double distance = Geolocator.distanceBetween(
    officeLatitude,
    officeLongitude,
    currentPosition.latitude,
    currentPosition.longitude,
  );
  // 距离小于等于禁止半径则判定为在禁止区域内
  return distance <= forbiddenRadius;
}

3. 修改考勤提交逻辑

在获取地址信息后,先判断是否处于禁止区域,再决定提交考勤还是提示用户:
修改你的_getAddressFromLatLng方法:

Future<void> _getAddressFromLatLng(Position position) async {
  await placemarkFromCoordinates(
    position.latitude,
    position.longitude,
  ).then((List<Placemark> placemarks) {
    Placemark place = placemarks[0];
    setState(() {
      _currentAddress =
          '${place.street}, ${place.locality}, ${place.postalCode}';
    });

    // 新增:判断是否在禁止区域
    if (_isInForbiddenArea(position)) {
      // 显示禁止提示
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('您无法在办公地址内提交考勤'),
          backgroundColor: Colors.red,
        ),
      );
    } else {
      // 不在禁止区域,执行考勤提交
      addAttendanceToDatabase();
    }
  }).catchError((e) {
    debugPrint(e.toString());
  });
}

补充说明

  • 如果想用地址名称判断(比如匹配街道、大厦名称),可以在获取到_currentAddress后做字符串匹配:
    // 示例:判断地址是否包含办公地址关键词
    bool isOfficeAddress = _currentAddress.contains('XX街道XX大厦');
    if (isOfficeAddress) {
      // 显示禁止提示
    }
    
    注意:地址名称匹配受地理编码返回结果影响,稳定性不如经纬度距离判断,建议优先用经纬度方案。
  • 可以把禁止区域的参数(经纬度、半径)放到配置文件或远程服务器,方便后续修改,无需重新打包应用。

内容的提问来源于stack exchange,提问作者Devendiran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:23:15