如何使用firestore运行地理“附近”查询?

时间:2017-10-08 11:19:50

标签: firebase google-cloud-firestore

firebase中的新firestore数据库本身是否支持基于位置的地理查询?即查找10英里内的帖子,或找到最近的50个帖子?

我看到实时firebase数据库有一些现有项目,像geofire这样的项目 - 那些也可以适应firestore吗?

15 个答案:

答案 0 :(得分:34)

  

更新:Firestore目前不支持实际的GeoPoint查询,因此当下面的查询成功执行时,它只按纬度过滤,而不是经度过滤,因此会返回许多不在附近的结果。最好的解决方案是使用geohashes。要了解如何自己做类似的事情,请查看此video

这可以通过创建小于查询的边界框来完成。至于效率,我无法说出来。

请注意,应检查约1英里的纬度/经度偏移的准确度,但这是一种快速的方法:

SWIFT 3.0版本

func getDocumentNearBy(latitude: Double, longitude: Double, distance: Double) {

    // ~1 mile of lat and lon in degrees
    let lat = 0.0144927536231884
    let lon = 0.0181818181818182

    let lowerLat = latitude - (lat * distance)
    let lowerLon = longitude - (lon * distance)

    let greaterLat = latitude + (lat * distance)
    let greaterLon = longitude + (lon * distance)

    let lesserGeopoint = GeoPoint(latitude: lowerLat, longitude: lowerLon)
    let greaterGeopoint = GeoPoint(latitude: greaterLat, longitude: greaterLon)

    let docRef = Firestore.firestore().collection("locations")
    let query = docRef.whereField("location", isGreaterThan: lesserGeopoint).whereField("location", isLessThan: greaterGeopoint)

    query.getDocuments { snapshot, error in
        if let error = error {
            print("Error getting documents: \(error)")
        } else {
            for document in snapshot!.documents {
                print("\(document.documentID) => \(document.data())")
            }
        }
    }

}

func run() {
    // Get all locations within 10 miles of Google Headquarters
    getDocumentNearBy(latitude: 37.422000, longitude: -122.084057, distance: 10)
}

答案 1 :(得分:20)

  

更新:Firestore目前不支持实际的GeoPoint查询,因此当下面的查询成功执行时,它只按纬度过滤,而不是经度过滤,因此会返回许多不在附近的结果。最好的解决方案是使用geohashes。要了解如何自己做类似的事情,请查看此video

(首先让我为这篇文章中的所有代码道歉,我只是希望任何阅读此答案的人都能轻松复制功能。)

为了解决OP所面临的同样问题,我首先调整GeoFire library与Firestore合作(通过查看该库,您可以了解很多关于地理内容的内容)。然后我意识到我并不介意如果位置以精确的圆圈返回。我只是想通过某种方式获得“附近”的位置。

我无法相信我花了多长时间才意识到这一点,但您可以使用SW角和NE角在GeoPoint场上执行双重不等式查询,以获取围绕中心点的边界框内的位置。 / p>

所以我创建了一个类似下面的JavaScript函数(这基本上是Ryan Lee答案的JS版本)。

/**
 * Get locations within a bounding box defined by a center point and distance from from the center point to the side of the box;
 *
 * @param {Object} area an object that represents the bounding box
 *    around a point in which locations should be retrieved
 * @param {Object} area.center an object containing the latitude and
 *    longitude of the center point of the bounding box
 * @param {number} area.center.latitude the latitude of the center point
 * @param {number} area.center.longitude the longitude of the center point
 * @param {number} area.radius (in kilometers) the radius of a circle
 *    that is inscribed in the bounding box;
 *    This could also be described as half of the bounding box's side length.
 * @return {Promise} a Promise that fulfills with an array of all the
 *    retrieved locations
 */
function getLocations(area) {
  // calculate the SW and NE corners of the bounding box to query for
  const box = utils.boundingBoxCoordinates(area.center, area.radius);

  // construct the GeoPoints
  const lesserGeopoint = new GeoPoint(box.swCorner.latitude, box.swCorner.longitude);
  const greaterGeopoint = new GeoPoint(box.neCorner.latitude, box.neCorner.longitude);

  // construct the Firestore query
  let query = firebase.firestore().collection('myCollection').where('location', '>', lesserGeopoint).where('location', '<', greaterGeopoint);

  // return a Promise that fulfills with the locations
  return query.get()
    .then((snapshot) => {
      const allLocs = []; // used to hold all the loc data
      snapshot.forEach((loc) => {
        // get the data
        const data = loc.data();
        // calculate a distance from the center
        data.distanceFromCenter = utils.distance(area.center, data.location);
        // add to the array
        allLocs.push(data);
      });
      return allLocs;
    })
    .catch((err) => {
      return new Error('Error while retrieving events');
    });
}

上面的函数还会为返回的每个位置数据添加.distanceFromCenter属性,这样您就可以通过检查该距离是否在您想要的范围内来获得类似圆的行为。

我在上面的函数中使用了两个util函数,所以这里也是代码。 (以下所有的util函数实际上都是从GeoFire库中改编而来的。)

<强>距离():

/**
 * Calculates the distance, in kilometers, between two locations, via the
 * Haversine formula. Note that this is approximate due to the fact that
 * the Earth's radius varies between 6356.752 km and 6378.137 km.
 *
 * @param {Object} location1 The first location given as .latitude and .longitude
 * @param {Object} location2 The second location given as .latitude and .longitude
 * @return {number} The distance, in kilometers, between the inputted locations.
 */
distance(location1, location2) {
  const radius = 6371; // Earth's radius in kilometers
  const latDelta = degreesToRadians(location2.latitude - location1.latitude);
  const lonDelta = degreesToRadians(location2.longitude - location1.longitude);

  const a = (Math.sin(latDelta / 2) * Math.sin(latDelta / 2)) +
          (Math.cos(degreesToRadians(location1.latitude)) * Math.cos(degreesToRadians(location2.latitude)) *
          Math.sin(lonDelta / 2) * Math.sin(lonDelta / 2));

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

  return radius * c;
}

boundingBoxCoordinates():(这里还有更多的工具,我在下面粘贴了。)

/**
 * Calculates the SW and NE corners of a bounding box around a center point for a given radius;
 *
 * @param {Object} center The center given as .latitude and .longitude
 * @param {number} radius The radius of the box (in kilometers)
 * @return {Object} The SW and NE corners given as .swCorner and .neCorner
 */
boundingBoxCoordinates(center, radius) {
  const KM_PER_DEGREE_LATITUDE = 110.574;
  const latDegrees = radius / KM_PER_DEGREE_LATITUDE;
  const latitudeNorth = Math.min(90, center.latitude + latDegrees);
  const latitudeSouth = Math.max(-90, center.latitude - latDegrees);
  // calculate longitude based on current latitude
  const longDegsNorth = metersToLongitudeDegrees(radius, latitudeNorth);
  const longDegsSouth = metersToLongitudeDegrees(radius, latitudeSouth);
  const longDegs = Math.max(longDegsNorth, longDegsSouth);
  return {
    swCorner: { // bottom-left (SW corner)
      latitude: latitudeSouth,
      longitude: wrapLongitude(center.longitude - longDegs),
    },
    neCorner: { // top-right (NE corner)
      latitude: latitudeNorth,
      longitude: wrapLongitude(center.longitude + longDegs),
    },
  };
}

<强> metersToLongitudeDegrees():

/**
 * Calculates the number of degrees a given distance is at a given latitude.
 *
 * @param {number} distance The distance to convert.
 * @param {number} latitude The latitude at which to calculate.
 * @return {number} The number of degrees the distance corresponds to.
 */
function metersToLongitudeDegrees(distance, latitude) {
  const EARTH_EQ_RADIUS = 6378137.0;
  // this is a super, fancy magic number that the GeoFire lib can explain (maybe)
  const E2 = 0.00669447819799;
  const EPSILON = 1e-12;
  const radians = degreesToRadians(latitude);
  const num = Math.cos(radians) * EARTH_EQ_RADIUS * Math.PI / 180;
  const denom = 1 / Math.sqrt(1 - E2 * Math.sin(radians) * Math.sin(radians));
  const deltaDeg = num * denom;
  if (deltaDeg < EPSILON) {
    return distance > 0 ? 360 : 0;
  }
  // else
  return Math.min(360, distance / deltaDeg);
}

<强> wrapLongitude():

/**
 * Wraps the longitude to [-180,180].
 *
 * @param {number} longitude The longitude to wrap.
 * @return {number} longitude The resulting longitude.
 */
function wrapLongitude(longitude) {
  if (longitude <= 180 && longitude >= -180) {
    return longitude;
  }
  const adjusted = longitude + 180;
  if (adjusted > 0) {
    return (adjusted % 360) - 180;
  }
  // else
  return 180 - (-adjusted % 360);
}

答案 2 :(得分:11)

截至今天,无法进行此类查询。 SO中还有其他与之相关的问题:

Is there a way to use GeoFire with Firestore?

How to query closest GeoPoints in a collection in Firebase Cloud Firestore?

Is there a way to use GeoFire with Firestore?

在我目前的Android项目中,我可以使用https://github.com/drfonfon/android-geohash添加geohash字段,而Firebase团队正在开发本机支持。

使用其他问题中建议的Firebase实时数据库意味着您无法同时按位置和其他字段过滤结果集,这是我想要首先切换到Firestore的主要原因。

答案 3 :(得分:7)

自@monkeybonkey首次提出此问题以来,已经引入了一个新项目。该项目称为GEOFirestore

使用此库,您可以在一圈内执行查询,例如查询文档:

  const geoQuery = geoFirestore.query({
    center: new firebase.firestore.GeoPoint(10.38, 2.41),
    radius: 10.5
  });

您可以通过npm安装GeoFirestore。您将必须单独安装Firebase(因为它是GeoFirestore的对等依赖项):

$ npm install geofirestore firebase --save

答案 4 :(得分:5)

当前,有一个适用于iOS和Android的新库,允许开发人员执行基于位置的地理查询。该库称为GeoFirestore。我已经实现了该库,并且找到了大量文档,没有错误。它似乎经过了充分的测试,是一个很好的选择。

答案 5 :(得分:4)

截至 2020 年末,现在还有 how to do geoqueries with Firestore 的文档。

这些适用于 iOS、Android 和 Web 的解决方案构建在 Firebase 创建的 GeoFire 库的精简版之上,然后展示了如何:

  • 生成 geohash 值并将其存储在 Firestore 中
  • 确定某个点和半径的边界框的 geohash 范围
  • 在这些 geohash 范围内执行查询

这比此处介绍的大多数其他库要低级一些,因此它可能更适合某些用例,而不太适合其他用例。

答案 6 :(得分:3)

对于Dart

///
/// Checks if these coordinates are valid geo coordinates.
/// [latitude]  The latitude must be in the range [-90, 90]
/// [longitude] The longitude must be in the range [-180, 180]
/// returns [true] if these are valid geo coordinates
///
bool coordinatesValid(double latitude, double longitude) {
  return (latitude >= -90 && latitude <= 90 && longitude >= -180 && longitude <= 180);
}

///
/// Checks if the coordinates  of a GeopPoint are valid geo coordinates.
/// [latitude]  The latitude must be in the range [-90, 90]
/// [longitude] The longitude must be in the range [-180, 180]
/// returns [true] if these are valid geo coordinates
///
bool geoPointValid(GeoPoint point) {
  return (point.latitude >= -90 &&
      point.latitude <= 90 &&
      point.longitude >= -180 &&
      point.longitude <= 180);
}

///
/// Wraps the longitude to [-180,180].
///
/// [longitude] The longitude to wrap.
/// returns The resulting longitude.
///
double wrapLongitude(double longitude) {
  if (longitude <= 180 && longitude >= -180) {
    return longitude;
  }
  final adjusted = longitude + 180;
  if (adjusted > 0) {
    return (adjusted % 360) - 180;
  }
  // else
  return 180 - (-adjusted % 360);
}

double degreesToRadians(double degrees) {
  return (degrees * math.pi) / 180;
}

///
///Calculates the number of degrees a given distance is at a given latitude.
/// [distance] The distance to convert.
/// [latitude] The latitude at which to calculate.
/// returns the number of degrees the distance corresponds to.
double kilometersToLongitudeDegrees(double distance, double latitude) {
  const EARTH_EQ_RADIUS = 6378137.0;
  // this is a super, fancy magic number that the GeoFire lib can explain (maybe)
  const E2 = 0.00669447819799;
  const EPSILON = 1e-12;
  final radians = degreesToRadians(latitude);
  final numerator = math.cos(radians) * EARTH_EQ_RADIUS * math.pi / 180;
  final denom = 1 / math.sqrt(1 - E2 * math.sin(radians) * math.sin(radians));
  final deltaDeg = numerator * denom;
  if (deltaDeg < EPSILON) {
    return distance > 0 ? 360.0 : 0.0;
  }
  // else
  return math.min(360.0, distance / deltaDeg);
}

///
/// Defines the boundingbox for the query based
/// on its south-west and north-east corners
class GeoBoundingBox {
  final GeoPoint swCorner;
  final GeoPoint neCorner;

  GeoBoundingBox({this.swCorner, this.neCorner});
}

///
/// Defines the search area by a  circle [center] / [radiusInKilometers]
/// Based on the limitations of FireStore we can only search in rectangles
/// which means that from this definition a final search square is calculated
/// that contains the circle
class Area {
  final GeoPoint center;
  final double radiusInKilometers;

  Area(this.center, this.radiusInKilometers): 
  assert(geoPointValid(center)), assert(radiusInKilometers >= 0);

  factory Area.inMeters(GeoPoint gp, int radiusInMeters) {
    return new Area(gp, radiusInMeters / 1000.0);
  }

  factory Area.inMiles(GeoPoint gp, int radiusMiles) {
    return new Area(gp, radiusMiles * 1.60934);
  }

  /// returns the distance in km of [point] to center
  double distanceToCenter(GeoPoint point) {
    return distanceInKilometers(center, point);
  }
}

///
///Calculates the SW and NE corners of a bounding box around a center point for a given radius;
/// [area] with the center given as .latitude and .longitude
/// and the radius of the box (in kilometers)
GeoBoundingBox boundingBoxCoordinates(Area area) {
  const KM_PER_DEGREE_LATITUDE = 110.574;
  final latDegrees = area.radiusInKilometers / KM_PER_DEGREE_LATITUDE;
  final latitudeNorth = math.min(90.0, area.center.latitude + latDegrees);
  final latitudeSouth = math.max(-90.0, area.center.latitude - latDegrees);
  // calculate longitude based on current latitude
  final longDegsNorth = kilometersToLongitudeDegrees(area.radiusInKilometers, latitudeNorth);
  final longDegsSouth = kilometersToLongitudeDegrees(area.radiusInKilometers, latitudeSouth);
  final longDegs = math.max(longDegsNorth, longDegsSouth);
  return new GeoBoundingBox(
      swCorner: new GeoPoint(latitudeSouth, wrapLongitude(area.center.longitude - longDegs)),
      neCorner: new GeoPoint(latitudeNorth, wrapLongitude(area.center.longitude + longDegs)));
}

///
/// Calculates the distance, in kilometers, between two locations, via the
/// Haversine formula. Note that this is approximate due to the fact that
/// the Earth's radius varies between 6356.752 km and 6378.137 km.
/// [location1] The first location given
/// [location2] The second location given
/// sreturn the distance, in kilometers, between the two locations.
///
double distanceInKilometers(GeoPoint location1, GeoPoint location2) {
  const radius = 6371; // Earth's radius in kilometers
  final latDelta = degreesToRadians(location2.latitude - location1.latitude);
  final lonDelta = degreesToRadians(location2.longitude - location1.longitude);

  final a = (math.sin(latDelta / 2) * math.sin(latDelta / 2)) +
      (math.cos(degreesToRadians(location1.latitude)) *
          math.cos(degreesToRadians(location2.latitude)) *
          math.sin(lonDelta / 2) *
          math.sin(lonDelta / 2));

  final c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a));

  return radius * c;
}

我刚刚基于上述JS代码发布了Flutter软件包 https://pub.dartlang.org/packages/firestore_helpers

答案 7 :(得分:3)

劫持此线程可以帮助仍在寻找任何人。 Firestore仍然不支持基于地理的查询,使用Google的GeoFirestore库也不是理想选择,因为它只能让您按位置搜索,没有别的。

我把这些放在一起: https://github.com/mbramwell1/GeoFire-Android

基本上,它可以让您使用位置和距离进行附近的搜索:

QueryLocation queryLocation = QueryLocation.fromDegrees(latitude, longitude);
Distance searchDistance = new Distance(1.0, DistanceUnit.KILOMETERS);
geoFire.query()
    .whereNearTo(queryLocation, distance)
    .build()
    .get();

回购中有更多文档。它对我有用,因此请尝试一下,希望它能够满足您的需求。

答案 8 :(得分:1)

这还没有经过充分测试,但是应该比李安(Ryan Lee)的回答有所改善

我的计算更加准确,然后我过滤出答案以删除落在边界框内但在半径范围之外的匹配项

雨燕4

select * from node where title LIKE '%born in care shelter breed%';

可精确测量2个地理位置之间的距离(以米为单位)的功能

func getDocumentNearBy(latitude: Double, longitude: Double, meters: Double) {

    let myGeopoint = GeoPoint(latitude:latitude, longitude:longitude )
    let r_earth : Double = 6378137  // Radius of earth in Meters

    // 1 degree lat in m
    let kLat = (2 * Double.pi / 360) * r_earth
    let kLon = (2 * Double.pi / 360) * r_earth * __cospi(latitude/180.0)

    let deltaLat = meters / kLat
    let deltaLon = meters / kLon

    let swGeopoint = GeoPoint(latitude: latitude - deltaLat, longitude: longitude - deltaLon)
    let neGeopoint = GeoPoint(latitude: latitude + deltaLat, longitude: longitude + deltaLon)

    let docRef : CollectionReference = appDelegate.db.collection("restos")

    let query = docRef.whereField("location", isGreaterThan: swGeopoint).whereField("location", isLessThan: neGeopoint)
    query.getDocuments { snapshot, error in
      guard let snapshot = snapshot else {
        print("Error fetching snapshot results: \(error!)")
        return
      }
      self.documents = snapshot.documents.filter { (document)  in
        if let location = document.get("location") as? GeoPoint {
          let myDistance = self.distanceBetween(geoPoint1:myGeopoint,geoPoint2:location)
          print("myDistance:\(myDistance) distance:\(meters)")
          return myDistance <= meters
        }
        return false
      }
    }
  }

答案 9 :(得分:1)

Flutter的一种解决方法,直到我们在Firestore中具有本机查询以拉出基于经纬度的有序文档为止: https://pub.dev/packages/geoflutterfire 一个将地理哈希存储在Firestore中并进行查询的插件。

限制:不支持限制

答案 10 :(得分:0)

是的,这是一个古老的话题,但是我只想在Java代码上提供帮助。我如何解决经度问题?我使用了 Ryan Lee Michael Teper 的代码。

代码:

if (lowerLon <= user.getUserGeoPoint().getLongitude() && user.getUserGeoPoint().getLongitude() <= greaterLon) {
    Log.d(LOG_TAG, "location: " + document.getId());
}  

发布结果后仅在内部,将过滤器设置为经度:

browserZoomLevel = Math.round(window.devicePixelRatio * 100);

我希望这会对某人有所帮助。 祝你有美好的一天!

答案 11 :(得分:0)

有一个用于Firestore的GeoFire库,名为Geofirestore:https://github.com/imperiumlabs/GeoFirestore(免责声明:我帮助开发了它)。它非常易于使用,并且为Firestore提供的功能与Geofire对Firebase Realtime DB的功能相同)

答案 12 :(得分:0)

最简单的方法是在数据库中存储位置时计算“地理哈希”。

geo hash是一个字符串,它表示精确到一定位置的位置。地理位置哈希值越长,带有该地理位置哈希值的位置就必须越近。两个位置,例如相距100m可能具有相同的6个字符的地理哈希,但是在计算7个字符的地理哈希时,最后一个字符可能会有所不同。

有很多库可让您计算任何语言的地理哈希。只需将其存储在位置旁边,然后使用==查询查找具有相同地理位置哈希值的位置即可。

答案 13 :(得分:0)

在javascript中,您可以简单地

const db = firebase.firestore();

 //Geofire
import { GeoCollectionReference, GeoFirestore, GeoQuery, GeoQuerySnapshot } from 'geofirestore';

// Create a GeoFirestore reference
const geofirestore: GeoFirestore = new GeoFirestore(db);

// Create a GeoCollection reference
const geocollection: GeoCollectionReference = geofirestore.collection('<Your_collection_name>');

const query: GeoQuery = geocollectionDrivers.near({ 
        center: new firebase.firestore.GeoPoint(location.latitude, location.longitude), 
        radius: 10000 
    });
    query.onSnapshot(gquerySnapshot => {
        gquerySnapshot.forEach(res => {
            console.log(res.data());
        })
    });

答案 14 :(得分:0)

您应该使用 GeoFire(适用于 Firestore)。有了这个,您可以过滤服务器上的文档并从 Firestore 数据库中读取更少的文档。这也会减少您的阅读次数。

检查 GroFire 这个库:https://github.com/patpatchpatrick/GeoFirestore-iOS

“patpatchpatrick”使其与 Swift 5 兼容。

只需按如下方式安装 pod:

pod 'Geofirestore', :git => 'https://github.com/patpatchpatrick/GeoFirestore-iOS'

我在我的一个项目中使用了这个库,它运行良好。

设置位置:

let location: CLLocation = CLLocation(latitude: lat, longitude: lng)
yourCollection.setLocation(location: location, forDocumentWithID: "YourDocId") { (error) in }

删除位置:

collection.removeLocation(forDocumentWithID: "YourDocId")

获取文档:

let center = CLLocation(latitude: lat, longitude: lng)
let collection = "Your collection path"
let circleQuery = collection.query(withCenter: center, radius: Double(yourRadiusVal))
        
let _ = circleQuery.observe(.documentEntered, with: { (key, location) in
        //Use info as per your need
})

我使用了 .documentEntered,您可以根据需要使用其他可用的地理查询,例如(文档退出、文档移动)。

您也可以使用 GeoPoint 进行查询。