Custom Element: Distance To
by stopsatgreen
HTML
<distance-to fromLat="51.470570" fromLon="-0.079701" toLat="51.524284" toLon="-0.076237">
JavaScript
var distanceToProto = Object.create(HTMLElement.prototype);
distanceToProto.createdCallback = function () {
'use strict';
// Start & end co-ordinates
var toLat = parseInt(this.getAttribute('toLat')),
toLon = parseInt(this.getAttribute('toLon'));
var fromLat = parseInt(this.getAttribute('fromLat')),
fromLon = parseInt(this.getAttribute('fromLat'));
var R, a, c, d, distance;
// The radius of the Earth (km)
R = 6371;
// Define the toRad function for later calculation
if (typeof(Number.prototype.toRad) === 'undefined') {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
};
}
// Perform the distance calculations using the Haversine formula to account for the Earth's curvature.
// This code is from http://www.movable-type.co.uk/scripts/latlong.html
var dLat = (toLat-fromLat).toRad();
var dLon = (toLon-fromLon).toRad();
a = Math.sin(dLat/2) * Math.sin(dLat/2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) + Math.cos(toLat.toRad()) * Math.cos(fromLat.toRad()) * Math.sin(dLon/2) * Math.sin(dLon/2);
d = R * c;
// Round to one decimal place
distance = Math.round(d*10)/10;
this.innerHTML = distance;
}
document.registerElement('distance-to', { prototype: distanceToProto });