工具类

TencentLocationUtils 提供了一组与定位相关的通用工具方法,用于在客户端进行简单的几何计算与坐标处理。

本文档介绍这些工具方法的接口、平台支持与使用示例。



接口签名

abstract class TencentLocationUtils {
  // 距离与几何
  static double distanceBetween(
    TencentLocationCoordinate a,
    TencentLocationCoordinate b,
  );
  static bool contains({
    required TencentLocationCoordinate center,
    required double radius,
    required TencentLocationCoordinate point,
  });

  // 设备 / 区域信息
  static Future<bool> isSupportGps();
  static Future<bool> isInRegion({
    required double latitude,
    required double longitude,
  });

  // 坐标系互转
  static Future<TencentLocationCoordinate> wgs84ToGcj02(
    TencentLocationCoordinate coord,
  );
}

距离与几何

计算两点距离

final distanceMeters = TencentLocationUtils.distanceBetween(
  const TencentLocationCoordinate(latitude: 39.984120, longitude: 116.307484),
  const TencentLocationCoordinate(latitude: 39.985000, longitude: 116.308500),
);
print('距离:$distanceMeters 米');

要求两个坐标位于同一坐标系下(同为 GCJ-02 或同为 WGS-84),否则结果无意义。

平台支持:Android / iOS 均支持。

判断点是否在圆内

final inside = TencentLocationUtils.contains(
  center: const TencentLocationCoordinate(latitude: 39.984120, longitude: 116.307484),
  radius: 200,
  point: const TencentLocationCoordinate(latitude: 39.984500, longitude: 116.307900),
);
print('是否在圆内:$inside');

边界点(距离恰好等于半径)视为包含在圆内。

平台支持:Android / iOS 均支持。

设备与区域信息

当前设备是否支持 GPS

final supportGps = await TencentLocationUtils.isSupportGps();
print('设备支持 GPS:$supportGps');

平台支持:

  • Android:支持

  • iOS:不支持,调用会抛出 TencentLocationError,错误码为 unsupportedOnThisPlatform

坐标是否在中国境内

final inChina = await TencentLocationUtils.isInRegion(
  latitude: 39.984120,
  longitude: 116.307484,
);
print('坐标是否在中国境内:$inChina');

平台支持:

  • Android:不支持,调用会抛出 TencentLocationError,错误码为 unsupportedOnThisPlatform

  • iOS:支持

坐标系互转

WGS-84 转 GCJ-02

final gcj02 = await TencentLocationUtils.wgs84ToGcj02(
  const TencentLocationCoordinate(latitude: 39.984120, longitude: 116.307484),
);
print('GCJ-02 坐标:${gcj02.latitude}, ${gcj02.longitude}');

平台支持:

  • Android:不支持,调用会抛出 TencentLocationError,错误码为 unsupportedOnThisPlatform

  • iOS:支持

平台差异速查

接口 Android iOS
distanceBetween 支持 支持
contains 支持 支持
isSupportGps 支持 不支持
isInRegion 不支持 支持
wgs84ToGcj02 不支持 支持

调用不支持的接口会抛出 TencentLocationError,错误码为 unsupportedOnThisPlatform,建议在调用前用 defaultTargetPlatform 判断平台或对调用进行 try / on 包裹。

本页内容