Search code examples
node.jsdistancearangodbaql

How we calculate distance between two co-ordinate. ArangoDB


I have a Users table that contains latitude and longitude attribute for every user. So I need to calculate the distance between two users in AQL Query.

I have done the same in Orientdb with the below query.

var laltitude = CURRENT_USER_laltitude;
var longitude = CURRENT_USER_longitude;
var query = "select distance(latitude, longitude,"+laltitude+","+longitude+") as distance from users";

Solution

  • First, create a js file distance.js (or whatever you want to name it) and put below code as below.

    /* distance.js */
    'use strict';
    
    function gdistance(latitude1, longitude1, latitude2, longitude2, radius) {
        if (!latitude1 || !longitude1 || !latitude2 || !longitude2) { 
            return null; 
        };
    
        var lat1 = Number(latitude1), lon1 = Number(longitude1);
        var lat2 = Number(latitude2), lon2 = Number(longitude2);
    
        radius = (radius === undefined) ? 6371e3 : Number(radius);
    
        var R = radius;
        var φ1 = (lat1 * Math.PI / 180), λ1 = (lon1 * Math.PI / 180);
        var φ2 = (lat2 * Math.PI / 180), λ2 = (lon2 * Math.PI / 180);
        var Δφ = φ2 - φ1;
        var Δλ = λ2 - λ1;
    
        var a = Math.sin(Δφ/2) * Math.sin(Δφ/2)
              + Math.cos(φ1) * Math.cos(φ2)
              * Math.sin(Δλ/2) * Math.sin(Δλ/2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        var d = R * c;     // Meters
        var d2 = d / 1000; // Meters to KM
        return d2; 
    }
    
    module.exports = gdistance;
    

    Now open Arango Console with arangosh. This will open with _system database by default. So if you have other than this database like me then use db._useDatabase("myDatabase") command to change database.

    Now write below commands to add custom to your desired database.

    Version 2.8

    db._useDatabase("myDatabase");
    var aqlfunctions = require("org/arangodb/aql/functions");
    var f = require("/path/to/file/distance.js");
    aqlfunctions.register("geo::gdistance", f, true)
    

    Version 3.0+

    db._useDatabase("myDatabase");
    var aqlfunctions = require("@arangodb/aql/functions");
    var f = require("/path/to/distance.js");
    
    i.e.
    var f = require("/home/ubuntu/distance.js");
    var f = require("distance.js");
    
    # If you want to remove this group's UDFs (User defined functions)
    # aqlfunctions.unregisterGroup("geo");
    aqlfunctions.register("geo::gdistance", f, true);
    

    Now use in your AQL queries as below.

    LET distance = geo::gdistance(attrbute_name.latitude, attrbute_name.longitude, @your_latitude, @your_longitude)
    

    For more references with here.