Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,
}
like image 862
mohsenJsh Avatar asked Aug 26 '17 04:08

mohsenJsh


1 Answers

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());
    } 
    
like image 148
Naman Avatar answered Oct 16 '22 07:10

Naman