Coverage

100%
34
34
0

/Users/sebastiansandqvist/Documents/Sites & Projects/apps/#modules/s-haversine/index.js

100%
34
34
0
LineHitsSource
11'use strict';
2
31var haversine = module.exports = {};
4
5
6// ----- configurable earthRadius
7// ---------------------------------------
81haversine.earthRadius = 6371000;
9
10
11// ----- convert degrees to radians
12// ---------------------------------------
131haversine.degreesToRadians = function(deg) {
1424 return deg * (Math.PI / 180);
15};
16
17
18// ----- distance between two points
19// ---------------------------------------
201haversine.distance = function(coords1, coords2) {
21
225 var lat1 = coords1[0];
235 var lon1 = coords1[1];
245 var lat2 = coords2[0];
255 var lon2 = coords2[1];
26
275 var latitudeDifference = this.degreesToRadians(lat2 - lat1);
285 var logitudeDifference = this.degreesToRadians(lon2 - lon1);
29
305 var haversine =
31 Math.sin(latitudeDifference/2) * Math.sin(latitudeDifference/2) +
32 Math.cos(this.degreesToRadians(lat1)) * Math.cos(this.degreesToRadians(lat2)) *
33 Math.sin(logitudeDifference/2) * Math.sin(logitudeDifference/2);
34
355 var distance = 2 * Math.atan2(Math.sqrt(haversine), Math.sqrt(1 - haversine));
36
375 return this.earthRadius * distance;
38
39};
40
41
42// ----- convert degrees/minutes/seconds to decimal degrees
43// ---------------------------------------
441haversine.toDecimal = function(str) {
45
468 str = str.toLowerCase(); // throws if input is not a string
478 var lastChar = str.slice(-1);
488 var negative = false;
49
508 if (lastChar === 'w' || lastChar === 's') {
512 negative = true; // south and west => negative
52 }
53
548 var values = str.split(/[^0-9.]/);
558 var i;
56 // convert strings to numbers
578 for (i = 0; i < values.length; i++) {
58
59 // remove empty values
6027 if (!values[i]) {
618 values.splice(i, 1);
628 continue;
63 }
64
6519 values[i] = parseFloat(values[i]);
66
67 }
68
69 // make sure array has length 3
708 for (i = 0; i < 3; i++) {
7124 values[i] = values[i] || 0;
72 }
73
748 var result = values[0] + (values[1] / 60) + (values[2] / 3600);
75
768 if (negative) {
772 return result * -1;
78 }
79
806 return result;
81
82};