Flutter Firestore 地理查询距我的位置一定距离

Moz*_*deh 2 geolocation firebase flutter google-cloud-functions

我将用户数据(包括他们的实时位置)存储为我的 firebase 数据库中的GeoPoint数据类型。现在我需要从数据库中选择并获取距我的位置一定距离的用户。我使用这行代码来检索我的位置:

position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
Run Code Online (Sandbox Code Playgroud)

不,我需要在 flutter 中进行 firebase 查询来检索我周围 500 米的用户。这意味着我应该从 firebase 数据库中检索距离为 500 米的所有用户。我怎样才能做到这一点?

Moz*_*deh 8

最后我找到了解决方案:

position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
await getGenderIcons(context);
QuerySnapshot querySnapshot;
double lat = 0.0144927536231884;
double lon = 0.0181818181818182;
double distance = 1000*0.000621371;
double lowerLat = position.latitude - (lat * distance);
double lowerLon = position.longitude - (lon * distance);
double greaterLat = position.latitude + (lat * distance);
double greaterLon = position.longitude + (lon * distance);
GeoPoint lesserGeopoint = GeoPoint(lowerLat,lowerLon);
GeoPoint greaterGeopoint = GeoPoint(greaterLat,greaterLon);
querySnapshot = await usersRef
    .where("livelocation", isGreaterThan: lesserGeopoint)
    .where("livelocation", isLessThan: greaterGeopoint)
    .limit(100)
    .get();
Run Code Online (Sandbox Code Playgroud)

  • 工作完美吗? (2认同)