如何计算 MongoDB 中许多 GeoJSON 点之间的路线距离?

How do I calculate route distance between many GeoJSON points in MongoDB?

如何计算 MongoDB 中许多 GeoJSON 点之间的路线距离?我可以有一个数据库查询,按日期字段对项目进行排序,然后计算点之间的距离,最后将所有这些相加以计算总距离吗?

以下是我的一些数据示例:

{ 
 _id: 599cfc236ed0d81c98007f66
 tracerId: 59a07ea26ed0d81d78001acd
 loc { 
      type: "2dsphere",
      coordinates: [ 159.9, -37.92 ]
     },
 date: 2017-08-26 00:16:42,
 speed: 58,
}
{ 
 _id: 59a074d46ed0d81d78001acc
 tracerId: 59a07ea26ed0d81d78001acd
 loc { 
      type: "2dsphere",
      coordinates: [ 160, -38.20 ]
     },
 date: 2017-08-26 00:18:42,
 speed: 75,
}
{ 
 _id: 59a074d46ed0d81d78ac11cc
 tracerId: 59a07ea26ed0d81d78001acd
 loc { 
      type: "2dsphere",
      coordinates: [ 160.222, -38.92 ]
     },
 date: 2017-08-26 00:20:42,
 speed: 60,
}

正如评论中指出的那样,将尝试使用 Java 在此处绘制类似的图片。假设您的数据库名称 db 和集合名称为 col,文档类型为 GeoData,可以建模为:

public class GeoData {
    String tracerId;
    Location loc;
    Date date;
    Integer speed;
    ...getters, setters and other overrides
}

public class Location {
    String type;
    Coordinate coordinates;
}

public class Coordinate {
    double x;
    double y;
}

它将进行如下:

  1. 按日期字段对项目排序(假设按升序排列)

    MongoDatabase database = getDatabase("db");
    MongoCollection<GeoData> collection = database.getCollection("col", GeoData.class);
    Bson sortFilter = Filters.eq("date", "1"); //sort ascending
    List<GeoData> geoData = Lists.newArrayList(collection.find().sort(sortFilter));
    
  2. 使用c = square root of [(xA-xB)^2+(yA-yB)^2]

    计算点之间的距离
    private static double distanceBetweenCoordinates(Coordinate a, Coordinate b) {
        return Math.sqrt(Math.pow(b.getX() - a.getX(), 2) + Math.pow(b.getY() - a.getY(),2));
    }
    
  3. 将所有这些加起来计算路线距离

    double routeDist = 0.0;
    for (int i = 0; i < geoData.size()-1; i++) {
        routeDist += distanceBetweenCoordinates(geoData.get(i+1).getLoc().getCoordinates(), geoData.get(i+1).getLoc().getCoordinates());
    }