看看 s2 几何 - http://s2geometry.io/。基本概念是您将地球上的每个位置编码为 64 位 #,彼此靠近的位置是接近的 #。然后,您可以通过查找距离该位置 +/- 某个 # 的任何内容来查找 x 距离内的位置。现在,实际的实现有点复杂,所以你最终需要创建多个“单元”,即。范围内的最小值和最大值 #。然后,您对每个单元格进行查找。(更多信息在http://s2geometry.io/devguide/examples/coverings。)
这是在 node.js / javascript 中执行此操作的示例。我在后端使用它并让前端在区域/区域中传递。
const S2 = require("node-s2");
static async getUsersInRegion(region) {
// create a region
const s2RegionRect = new S2.S2LatLngRect(
new S2.S2LatLng(region.NECorner.latitude, region.NECorner.longitude),
new S2.S2LatLng(region.SWCorner.latitude, region.SWCorner.longitude),
);
// find the cell that will cover the requested region
const coveringCells = S2.getCoverSync(s2RegionRect, { max_cells: 4 });
// query all the users in each covering region/range simultaneously/in parallel
const coveringCellQueriesPromies = coveringCells.map(coveringCell => {
const cellMaxID = coveringCell
.id()
.rangeMax()
.id();
const cellMinID = coveringCell
.id()
.rangeMin()
.id();
return firestore
.collection("User")
.where("geoHash", "<=", cellMaxID)
.where("geoHash", ">=", cellMinID).
get();
});
// wait for all the queries to return
const userQueriesResult = await Promise.all(coveringCellQueriesPromies);
// create a set of users in the region
const users = [];
// iterate through each cell and each user in it to find those in the range
userQueriesResult.forEach(userInCoveringCellQueryResult => {
userInCoveringCellQueryResult.forEach(userResult => {
// create a cell id from the has
const user = userResult.data();
const s2CellId = new S2.S2CellId(user.geoHash.toString());
// validate that the user is in the view region
// since cells will have areas outside of the input region
if (s2RegionRect.contains(s2CellId.toLatLng())) {
user.id = userResult.id;
users.push(user);
}
});
});
return users;
}
S2 几何有很多方法可以找到覆盖单元格(即您要查找值的区域),因此绝对值得查看 API 并为您的用例找到正确的匹配项。