Last active
January 19, 2021 15:21
-
-
Save adarshpastakia/21567ead3f950add90aad38bceabc396 to your computer and use it in GitHub Desktop.
Geo Location Helper Methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Calculate center geo-coords from list of location coordinates | |
function calculateCenterPoint(data, latProperty = "latitude", lonProperty = "longitude") { | |
var num_coords = data.length; | |
var X = 0.0; | |
var Y = 0.0; | |
var Z = 0.0; | |
for (i = 0; i < data.length; i++) { | |
var lat = data[i][latProperty] * Math.PI / 180; | |
var lon = data[i][lonProperty] * Math.PI / 180; | |
var a = Math.cos(lat) * Math.cos(lon); | |
var b = Math.cos(lat) * Math.sin(lon); | |
var c = Math.sin(lat); | |
X += a; | |
Y += b; | |
Z += c; | |
} | |
X /= num_coords; | |
Y /= num_coords; | |
Z /= num_coords; | |
var lon = Math.atan2(Y, X); | |
var hyp = Math.sqrt(X * X + Y * Y); | |
var lat = Math.atan2(Z, hyp); | |
var newX = (lat * 180 / Math.PI); | |
var newY = (lon * 180 / Math.PI); | |
var ret = {}; | |
ret[latProperty] = newX; | |
ret[lonProperty] = newY; | |
return ret; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Calculate distance between two location coordinates | |
function calculateDistance(from, to, unit, latProperty = "latitude", lonProperty = "longitude") { | |
var radlat1 = Math.PI * from[latProperty] / 180; | |
var radlat2 = Math.PI * to[latProperty] / 180; | |
var radlon1 = Math.PI * from[lonProperty] / 180; | |
var radlon2 = Math.PI * to[lonProperty] / 180; | |
var theta = from[lonProperty] - to[lonProperty]; | |
var radtheta = Math.PI * theta / 180; | |
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); | |
dist = Math.acos(dist); | |
dist = dist * 180 / Math.PI; | |
dist = dist * 60 * 1.1515; | |
if (unit === "K") { | |
// Unit in Kilometers | |
dist = dist * 1.609344 | |
} else if (unit === "N") { | |
// Unit in Nautical Miles | |
dist = dist * 0.8684 | |
} else if (unit === "M") { | |
// Unit in Miles | |
dist = dist; | |
} else if (unit === "y") { | |
// Unit in Yards | |
dist = dist * 1760; | |
} else { | |
// Default to unit in meters | |
dist = (dist * 1.609344) * 1000 | |
} | |
return dist; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment