JSFiddle - React, Tailwind, and code Playground
by oroce
HTML
<script src="https://raw.github.com/manuelbieh/Geolib/master/geolib.js"></script>
<script src="http://oroszi.net/stations.json"></script>
JavaScript
$(function() {
var startDate = Date.now();
var closest = {};
var rlatitude = deg2rad(47.4762154225);
var rlongitude = deg2rad(19.0755586075);
stations.forEach(function(item, i) {
if (item.latitude && item.longitude) {
stations[i].latitude = deg2rad(item.latitude);
stations[i].longitude = deg2rad(item.longitude);
}
});
var unsorted = []
stations.forEach(function(item) {
if (!item.latitude || !item.longitude) {
return;
}
var distance = calculateDistance(rlatitude, rlongitude, item.latitude, item.longitude);
unsorted.push($.extend({}, item, {
distance: distance
}));
if (!closest.distance || distance < closest.distance) {
closest = item;
closest.distance = distance;
}
});
var sorted = unsorted.sort(function(a, b) {
return a.distance - b.distance;
}).splice(0, 10).map(function(item) {
return item.station
}).join("<br/>");
document.body.innerHTML = "<br /><br />" + (Date.now() - startDate) + " ms<br />" + JSON.stringify(closest) + "<br/><br/>" + sorted;
console.log(closest);
});
var Rm = 3961; // mean radius of the earth (miles) at 39 degrees from the equator
var Rk = 6373;
calculateDistance = (function() {
var pow = Math.pow,
sin = Math.sin,
cos = Math.cos,
sqrt = Math.sqrt,
atan2 = Math.atan2;
return function(lat1, lon1, lat2, lon2) {
var dlat = lat2 - lat1;
var dlon = lon2 - lon1;
// here's the heavy lifting
var a = pow(sin(dlat / 2), 2) + cos(lat1) * cos(lat2) * pow(sin(dlon / 2), 2);
var c = 2 * atan2(sqrt(a), sqrt(1 - a)); // great circle distance in radians
var dk = c * Rk; // great circle distance in km
// round the results down to the nearest 1/1000
var km = round(dk);
return km;
};
})();
function deg2rad(deg) {
rad = deg *...