How do I calculate route distance between many GeoJSON points in MongoDB?
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 :
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 ascendingList<GeoData> geoData = Lists.newArrayList(collection.find().sort(sortFilter));
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));}
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());}