使用 Realm 来过滤和排序附近的位置

问题描述 投票:0回答:4

我想查询领域数据库以获取附近的位置。纬度和经度信息保存在数据库中。当我生成边界框时,我可以查询边界框中的所有站点。我知道它不是半径,因为我使用的是边界框。

所以我有一个

RealmResult
包含该地区的所有位置。我想将其保留为
RealmResult
,以便从自动更新对象中受益。

如何按距当前位置的距离对位置进行排序?仅保留和排序位置的位置和纬度。

此外,如果我可以为距离添加一个额外的过滤器,那么所有位置都在半径内,那就太好了。

android location realm
4个回答
3
投票

Realm 目前不支持地理空间查询,但我们在此处跟踪它时遇到问题:https://github.com/realm/realm-java/issues/1772

所以我担心您通过 Realm API 来完成此操作有点不走运,但您可能会考虑研究类似 GeoHash 的东西:https://en.wikipedia.org/wiki/Geohash。它是使用位串的位置表示,并且可以通过比较前缀来近似距离。


1
投票

RealmGeoQueries 使在 iOS 上查找Nearby 和 findInRegion 变得容易


0
投票

Realm-js v12引入了对地理空间查询的支持。

  • 查询可用于过滤点位于球形几何形状的特定区域内的对象,使用 Results.filtered() 的查询字符串中的 geoWithin 运算符。

  • 地理空间查询支持以下形状:圆(GeoCircle 类型,由其圆心和半径以弧度定义)、长方体(GeoBox 类型,由其左下角和右上角定义)和多边形(GeoPolygon 类型,由其弧度定义)顶点)。

  • 此外,还添加了两个新函数 kmToRadians() 和 miToRadians(),可分别用于将公里和英里转换为弧度,简化了圆半径的转换。

import Realm, {
  ObjectSchema,
  GeoCircle,
  CanonicalGeoPoint,
  GeoPosition,
  kmToRadians,
} from "realm";

// Example of a user-defined point class that can be queried using geospatial queries
class MyGeoPoint extends Realm.Object implements CanonicalGeoPoint {
  coordinates!: GeoPosition;
  type = "Point" as const;

  static schema: ObjectSchema = {
    name: "MyGeoPoint",
    embedded: true,
    properties: {
      type: "string",
      coordinates: "double[]",
    },
  };
}

class PointOfInterest extends Realm.Object {
  name!: string;
  location!: MyGeoPoint;

  static schema: ObjectSchema = {
    name: "PointOfInterest",
    properties: {
      name: "string",
      location: "MyGeoPoint",
    },
  };
}

realm.write(() => {
  realm.create(PointOfInterest, {
    name: "Copenhagen",
    location: {
      coordinates: [12.558892784045568, 55.66717839648401],
      type: "Point",
    } as MyGeoPoint
  });
  realm.create(PointOfInterest, {
    name: "New York",
    location: {
      coordinates: [-73.92474936213434, 40.700090994927415],
      type: "Point",
    } as MyGeoPoint
  });
});

const pois = realm.objects(PointOfInterest);

const berlinCoordinates: GeoPoint = [13.397255909303222, 52.51174463251085];
const radius = kmToRadians(500); //500 km = 0.0783932519 rad

// Circle with a radius of 500kms centered in Berlin
const circleShape: GeoCircle = {
  center: berlinCoordinates,
  distance: radius,
};

// All points of interest in a 500kms radius from Berlin
let result = pois.filtered("location geoWithin $0", circleShape);

// Equivalent string query without arguments
result = pois.filtered("location geoWithin geoCircle([13.397255909303222, 52.51174463251085], 0.0783932519)");


-1
投票

您可以做的是,在将数据存储在 Realm 中时,您可以存储一个名为“距用户的距离”的值或类似的值。您可以通过计算用户纬度、经度和对象纬度之间的距离来获取该值,长。

然后您可以使用“与用户的距离”值按降序或升序对数据进行排序,这在 Realm 中非常容易。或者您可以使用 Realm 中的比较器 API 来获取距用户特定距离的对象。

© www.soinside.com 2019 - 2024. All rights reserved.