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

倖福魔咒の 提交于 2019-12-08 19:44:15

问题


How do I calculate route distance between many GeoJSON points in MongoDB? Can I have a database query that sort items by their date field, then calculates the distance between points and finally sums all of then to calculate the total distance?

Here are some examples of my data:

{ 
 _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,
}

回答1:


As pointed out in the comments as well, would try to draw a similar picture here using Java. Assuming your database name db and collection name as col and the document type as GeoData which could be modelled as :

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;
}

It would proceed as follows :

  1. Sort items by date field (let's say in ascending order)

    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. Calculate the distance between points using 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. Sum all of them to calculate route distance

    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());
    } 
    


来源:https://stackoverflow.com/questions/45891865/how-do-i-calculate-route-distance-between-many-geojson-points-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!