whuber algorithm
by hoolymama
HTML
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>
<div id="map" style="border: 2px solid #3872ac;"></div>
CSS
html,
body,
#map {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
JavaScript
const EARTH_RADIUS = 6371000
const DEG_TO_RAD = Math.PI / 180.0
const ONE_DEGREE = EARTH_RADIUS * DEG_TO_RAD
const THREE_PI = Math.PI * 3
const TWO_PI = Math.PI * 2
function isFloat(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function recursiveConvert(input, callback) {
if (input instanceof Array) {
return input.map((el) => recursiveConvert(el, callback))
}
if (input instanceof Object) {
input = JSON.parse(JSON.stringify(input))
for (let key in input) {
if (input.hasOwnProperty(key)) {
input[key] = recursiveConvert(input[key], callback)
}
}
return input
}
if (isFloat(input)) {
return callback(input)
}
}
function toRadians(input) {
return recursiveConvert(input, (val) => val * DEG_TO_RAD)
}
function toDegrees(input) {
return recursiveConvert(input, (val) => val / DEG_TO_RAD)
}
lengthOf = function(x, y) {
return Math.sqrt(x * x + y * y)
}
function whuberPointAtDistance(coords, distance) {
var r = distance / 111300,
y0 = coords.latitude,
x0 = coords.longitude,
u = 1,
v = Math.random(),
w = r * Math.sqrt(u),
t = 2 * Math.PI * v,
x = w * Math.cos(t),
y1 = w * Math.sin(t),
x1 = x / Math.cos(y0)
newY = y0 + y1
newX = x0 + x1
return {
latitude: newY,
longitude: newX
}
}
function distanceBetween(start, end) {
const startPoint = toRadians(start)
const endPoint = toRadians(end)
const delta = {
latitude: endPoint.latitude - startPoint.latitude,
longitude: endPoint.longitude - startPoint.longitude
}
const sinDelta = {
latitude: Math.sin(delta.latitude / 2),
longitude: Math.sin(delta.longitude / 2)
}
const A = sinDelta.latitude * sinDelta.latitude +
sinDelta.longitude * sinDelta.longitude * Math.cos(startPoint.latitude) * Math.cos(endPoint.latitude)
return EARTH_RADIUS * 2 * Math.atan2(Math.sqrt(A), Math.sqrt(1 - A))
}
var initLoc = {
"latitude": 67.498454,
"longitude": 21.040181
}
var locations...