Coverage

100%
30
30
0

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

100%
30
30
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) {
1416 return deg * (Math.PI / 180);
15};
16
17
18// ----- distance between two points
19// ---------------------------------------
201haversine.distance = function(lat1, lon1, lat2, lon2) {
21
223 var latitudeDifference = this.degreesToRadians(lat2 - lat1);
233 var logitudeDifference = this.degreesToRadians(lon2 - lon1);
24
253 var haversine =
26 Math.sin(latitudeDifference/2) * Math.sin(latitudeDifference/2) +
27 Math.cos(this.degreesToRadians(lat1)) * Math.cos(this.degreesToRadians(lat2)) *
28 Math.sin(logitudeDifference/2) * Math.sin(logitudeDifference/2);
29
303 var distance = 2 * Math.atan2(Math.sqrt(haversine), Math.sqrt(1 - haversine));
31
323 return this.earthRadius * distance;
33
34};
35
36
37// ----- convert degrees/minutes/seconds to decimal degrees
38// ---------------------------------------
391haversine.toDecimal = function(str) {
40
418 str = str.toLowerCase(); // throws if input is not a string
428 var lastChar = str.slice(-1);
438 var negative = false;
44
458 if (lastChar === 'w' || lastChar === 's') {
462 negative = true; // south and west => negative
47 }
48
498 var values = str.split(/[^0-9.]/);
508 var i;
51 // convert strings to numbers
528 for (i = 0; i < values.length; i++) {
53
54 // remove empty values
5527 if (!values[i]) {
568 values.splice(i, 1);
578 continue;
58 }
59
6019 values[i] = parseFloat(values[i]);
61
62 }
63
64 // make sure array has length 3
658 for (i = 0; i < 3; i++) {
6624 values[i] = values[i] || 0;
67 }
68
698 var result = values[0] + (values[1] / 60) + (values[2] / 3600);
70
718 if (negative) {
722 return result * -1;
73 }
74
756 return result;
76
77};