How to calculate the distance between many points of GeoJSON in MongoDB?

How to calculate the distance between many points of GeoJSON in MongoDB? Can I get a database query that sorts items by date field, then calculates the distance between points and finally sums everything 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, } 
+5
source share
1 answer

As noted in the comments, try using a similar picture here using Java. Assuming your db database name and collection name as col , and the document type is GeoData , which can be modeled 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; } 

He will act as follows:

  • Sort items by date (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)); 
  • 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 the distance of the route.

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

Source: https://habr.com/ru/post/1271245/


All Articles