Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uber h3 for finding distance between two geo locations

Tags:

h3

I read the h3 doc and I am not sure finding the absolute distance between two geo point is one of the use case. There are formulas for it like in this page or google maps provides API for it. I see an h3 API for finding distance between hexagons but not sure how accurately or how to use it across different resolution etc. Any example or details are greatly appreciated. I hope using h3 I may reduce external API usages.

like image 849
bsr Avatar asked Nov 28 '18 14:11

bsr


2 Answers

You are correct, there is no current H3 function to calculate the physical distance between two geographic points. We have a function internally in the library that will return the physical distance in kilometers, but we don't currently expose it in the H3 library API. There's an open request for this feature, and it's likely to be added in the next month or two.

Update: this is now available as h3.pointDist

like image 100
nrabinowitz Avatar answered Dec 27 '22 09:12

nrabinowitz


Will below help?

const h3 = require("h3-js");

function distanceBetweenIndexCentres(h3Index1, h3Index2){
    if(!h3.h3IsValid(h3Index1) || !h3.h3IsValid(h3Index2))
        throw 'invalid h3 indexes provided'

    let index1CenterCoordinates = h3.h3ToGeo(h3Index1);
    let index2CenterCoordinates = h3.h3ToGeo(h3Index2);

    return distanceInKm(index1CenterCoordinates[0], index1CenterCoordinates[1], index2CenterCoordinates[0], index2CenterCoordinates[1])
}

function distanceInKm(lat1, lon1, lat2, lon2) {
    if ((lat1 == lat2) && (lon1 == lon2)) {
        return 0;
    }
    else {
        var radlat1 = Math.PI * lat1/180;
        var radlat2 = Math.PI * lat2/180;
        var theta = lon1-lon2;
        var radtheta = Math.PI * theta/180;
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        if (dist > 1) {
            dist = 1;
        }
        dist = Math.acos(dist);
        dist = dist * 180/Math.PI;
        dist = dist * 60 * 1.1515;
        return dist * 1.609344;
    }
}


let h3Index1 = h3.geoToH3(16.750642, 78.017239, 7);
let h3Index2 = h3.geoToH3(16.806983, 78.027875, 6);
console.log('distance in km: '+distanceBetweenIndexCentres(h3Index1, h3Index2))

//prints - distance in km: 7.60193311570551
like image 43
Kisanagaram Avatar answered Dec 27 '22 10:12

Kisanagaram