Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added gruntfile for linting and automated minification

  • Loading branch information...
commit be8a06b5ea2d693d6ad8447ecd1c859bf2e52cfc 1 parent 390e9d4
@manuelbieh authored
View
0  earth.png → demo/earth.png
File renamed without changes
View
2  demo.html → demo/index.html
@@ -9,7 +9,7 @@
<meta charset="utf-8" />
-<script src="geolib.js"></script>
+<script src="../geolib.js"></script>
<script>
$(function() {
View
445 geolib.js
@@ -1,14 +1,13 @@
/**
- * A small library to provide some basic geo functions like distance calculation,
- * conversion of decimal coordinates to sexagesimal and vice versa, etc.
- * WGS 84 (World Geodetic System 1984)
- *
- * @author Manuel Bieh
- * @url http://www.manuelbieh.com/
- * @version 1.1.7
- * @license http://www.gnu.org/licenses/lgpl-3.0.txt LGPL
- *
- */
+* A small library to provide some basic geo functions like distance calculation,
+* conversion of decimal coordinates to sexagesimal and vice versa, etc.
+* WGS 84 (World Geodetic System 1984)
+*
+* @author Manuel Bieh
+* @url http://www.manuelbieh.com/
+* @version 1.1.8
+* @license LGPL
+**/
(function (window, undefined) {
@@ -23,16 +22,16 @@
distance: 0,
-
/**
- * Get the key names for a geo point.
- *
- * @param object Point position {latitude: 123, longitude: 123, elevation: 123}
- * @return object { longitude: 'lng|long|longitude',
- * latitude: 'lat|latitude',
- * elevation: 'alt|altitude|elev|elevation' }
- */
-
+ * Get the key names for a geo point.
+ *
+ * @param object Point position {latitude: 123, longitude: 123, elevation: 123}
+ * @return object {
+ * longitude: 'lng|long|longitude',
+ * latitude: 'lat|latitude',
+ * elevation: 'alt|altitude|elev|elevation'
+ * }
+ */
getKeys: function(point) {
var latitude = point.hasOwnProperty('lat') ? 'lat' : 'latitude';
var longitude = (point.hasOwnProperty('lng') ? 'lng' : false) ||
@@ -50,16 +49,16 @@
},
/**
- * Calculates geodetic distance between two points specified by latitude/longitude using
- * Vincenty inverse formula for ellipsoids
- * Vincenty Inverse Solution of Geodesics on the Ellipsoid (c) Chris Veness 2002-2010
- * (Licensed under CC BY 3.0)
- *
- * @param object Start position {latitude: 123, longitude: 123}
- * @param object End position {latitude: 123, longitude: 123}
- * @param integer Accuracy (in meters)
- * @return integer Distance (in meters)
- */
+ * Calculates geodetic distance between two points specified by latitude/longitude using
+ * Vincenty inverse formula for ellipsoids
+ * Vincenty Inverse Solution of Geodesics on the Ellipsoid (c) Chris Veness 2002-2010
+ * (Licensed under CC BY 3.0)
+ *
+ * @param object Start position {latitude: 123, longitude: 123}
+ * @param object End position {latitude: 123, longitude: 123}
+ * @param integer Accuracy (in meters)
+ * @return integer Distance (in meters)
+ */
getDistance: function(start, end, accuracy) {
@@ -80,6 +79,8 @@
var a = 6378137, b = 6356752.314245, f = 1/298.257223563; // WGS-84 ellipsoid params
var L = (coord2[longitude]-coord1[longitude]).toRad();
+ var cosSigma, sigma, sinAlpha, cosSqAlpha, cos2SigmaM, sinSigma;
+
var U1 = Math.atan((1-f) * Math.tan(parseFloat(coord1[latitude]).toRad()));
var U2 = Math.atan((1-f) * Math.tan(parseFloat(coord2[latitude]).toRad()));
var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
@@ -88,7 +89,7 @@
var lambda = L, lambdaP, iterLimit = 100;
do {
var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);
- var sinSigma = (
+ sinSigma = (
Math.sqrt(
(
cosU2 * sinLambda
@@ -101,14 +102,16 @@
)
)
);
- if (sinSigma==0) {
+ if (sinSigma === 0) {
return geolib.distance = 0; // co-incident points
}
- var cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
- var sigma = Math.atan2(sinSigma, cosSigma);
- var sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
- var cosSqAlpha = 1 - sinAlpha * sinAlpha;
- var cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
+
+ cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
+ sigma = Math.atan2(sinSigma, cosSigma);
+ sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
+ cosSqAlpha = 1 - sinAlpha * sinAlpha;
+ cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
+
if (isNaN(cos2SigmaM)) {
cos2SigmaM = 0; // equatorial line: cosSqAlpha=0 (§6)
}
@@ -134,8 +137,8 @@
} while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0);
- if (iterLimit==0) {
- return NaN // formula failed to converge
+ if (iterLimit === 0) {
+ return NaN; // formula failed to converge
}
var uSq = (
@@ -183,11 +186,13 @@
var distance = b * A * (sigma - deltaSigma);
distance = distance.toFixed(3); // round to 1mm precision
+
if (start.hasOwnProperty(elevation) && end.hasOwnProperty(elevation)) {
var climb = Math.abs(start[elevation] - end[elevation]);
distance = Math.sqrt(distance*distance + climb*climb);
}
- return geolib.distance = Math.floor(Math.round(distance/accuracy)*accuracy)
+
+ return geolib.distance = Math.floor(Math.round(distance/accuracy)*accuracy);
/*
// note: to return initial/final bearings in addition to distance, use something like:
@@ -201,14 +206,14 @@
/**
- * Calculates the distance between two spots.
- * This method is more simple but also more inaccurate
- *
- * @param object Start position {latitude: 123, longitude: 123}
- * @param object End position {latitude: 123, longitude: 123}
- * @param integer Accuracy (in meters)
- * @return integer Distance (in meters)
- */
+ * Calculates the distance between two spots.
+ * This method is more simple but also more inaccurate
+ *
+ * @param object Start position {latitude: 123, longitude: 123}
+ * @param object End position {latitude: 123, longitude: 123}
+ * @param integer Accuracy (in meters)
+ * @return integer Distance (in meters)
+ */
getDistanceSimple: function(start, end, accuracy) {
var keys = geolib.getKeys(start);
@@ -251,11 +256,11 @@
/**
- * Calculates the center of a collection of geo coordinates
- *
- * @param array Collection of coords [{latitude: 51.510, longitude: 7.1321}, {latitude: 49.1238, longitude: "8° 30' W"}, ...]
- * @return object {latitude: centerLat, longitude: centerLng, distance: diagonalDistance}
- */
+ * Calculates the center of a collection of geo coordinates
+ *
+ * @param array Collection of coords [{latitude: 51.510, longitude: 7.1321}, {latitude: 49.1238, longitude: "8° 30' W"}, ...]
+ * @return object {latitude: centerLat, longitude: centerLng, distance: diagonalDistance}
+ */
getCenter: function(coords) {
if (!coords.length) {
@@ -297,15 +302,15 @@
},
/**
- * Gets the max and min, latitude, longitude, and elevation (if provided).
- * @param array array with coords e.g. [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...]
- * @return object {maxLat: maxLat,
- * minLat: minLat
- * maxLng: maxLng,
- * minLng: minLng,
- * maxElev: maxElev,
- * minElev: minElev}
- */
+ * Gets the max and min, latitude, longitude, and elevation (if provided).
+ * @param array array with coords e.g. [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...]
+ * @return object {maxLat: maxLat,
+ * minLat: minLat
+ * maxLng: maxLng,
+ * minLng: minLng,
+ * maxElev: maxElev,
+ * minElev: minElev}
+ */
getBounds: function(coords) {
if (!coords.length) {
return false;
@@ -321,7 +326,7 @@
maxLat: 0,
minLat: Infinity,
maxLng: 0,
- minLng: Infinity,
+ minLng: Infinity
};
if (useElevation) {
@@ -343,13 +348,13 @@
},
/**
- * Checks whether a point is inside of a polygon or not.
- * Note that the polygon coords must be in correct order!
- *
- * @param object coordinate to check e.g. {latitude: 51.5023, longitude: 7.3815}
- * @param array array with coords e.g. [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...]
- * @return bool true if the coordinate is inside the given polygon
- */
+ * Checks whether a point is inside of a polygon or not.
+ * Note that the polygon coords must be in correct order!
+ *
+ * @param object coordinate to check e.g. {latitude: 51.5023, longitude: 7.3815}
+ * @param array array with coords e.g. [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...]
+ * @return bool true if the coordinate is inside the given polygon
+ */
isPointInside: function(latlng, coords) {
var keys = geolib.getKeys(latlng);
@@ -358,14 +363,20 @@
for(var c = false, i = -1, l = coords.length, j = l - 1; ++i < l; j = i) {
- (
- (coords[i][longitude] <= latlng[longitude] && latlng[longitude] < coords[j][longitude]) ||
- (coords[j][longitude] <= latlng[longitude] && latlng[longitude] < coords[i][longitude])
- )
- && (latlng[latitude] < (coords[j][latitude] - coords[i][latitude])
- * (latlng[longitude] - coords[i][longitude])
- / (coords[j][longitude] - coords[i][longitude]) + coords[i][latitude])
- && (c = !c);
+ if(
+ (
+ (coords[i][longitude] <= latlng[longitude] && latlng[longitude] < coords[j][longitude]) ||
+ (coords[j][longitude] <= latlng[longitude] && latlng[longitude] < coords[i][longitude])
+ ) &&
+ (
+ latlng[latitude] < (coords[j][latitude] - coords[i][latitude]) *
+ (latlng[longitude] - coords[i][longitude]) /
+ (coords[j][longitude] - coords[i][longitude]) +
+ coords[i][latitude]
+ )
+ ) {
+ c = !c;
+ }
}
@@ -375,13 +386,13 @@
/**
- * Checks whether a point is inside of a circle or not.
- *
- * @param object coordinate to check (e.g. {latitude: 51.5023, longitude: 7.3815})
- * @param object coordinate of the circle's center (e.g. {latitude: 51.4812, longitude: 7.4025})
- * @param integer maximum radius in meters
- * @return bool true if the coordinate is inside the given radius
- */
+ * Checks whether a point is inside of a circle or not.
+ *
+ * @param object coordinate to check (e.g. {latitude: 51.5023, longitude: 7.3815})
+ * @param object coordinate of the circle's center (e.g. {latitude: 51.4812, longitude: 7.4025})
+ * @param integer maximum radius in meters
+ * @return bool true if the coordinate is inside the given radius
+ */
isPointInCircle: function(latlng, center, radius) {
return geolib.getDistance(latlng, center) < radius;
@@ -390,18 +401,18 @@
/**
- * Gets rhumb line bearing of two points. Find out about the difference between rhumb line and
- * great circle bearing on Wikipedia. It's quite complicated. Rhumb line should be fine in most cases:
- *
- * http://en.wikipedia.org/wiki/Rhumb_line#General_and_mathematical_description
- *
- * Function heavily based on Doug Vanderweide's great PHP version (licensed under GPL 3.0)
- * http://www.dougv.com/2009/07/13/calculating-the-bearing-and-compass-rose-direction-between-two-latitude-longitude-coordinates-in-php/
- *
- * @param object origin coordinate (e.g. {latitude: 51.5023, longitude: 7.3815})
- * @param object destination coordinate
- * @return integer calculated bearing
- */
+ * Gets rhumb line bearing of two points. Find out about the difference between rhumb line and
+ * great circle bearing on Wikipedia. It's quite complicated. Rhumb line should be fine in most cases:
+ *
+ * http://en.wikipedia.org/wiki/Rhumb_line#General_and_mathematical_description
+ *
+ * Function heavily based on Doug Vanderweide's great PHP version (licensed under GPL 3.0)
+ * http://www.dougv.com/2009/07/13/calculating-the-bearing-and-compass-rose-direction-between-two-latitude-longitude-coordinates-in-php/
+ *
+ * @param object origin coordinate (e.g. {latitude: 51.5023, longitude: 7.3815})
+ * @param object destination coordinate
+ * @return integer calculated bearing
+ */
getRhumbLineBearing: function(originLL, destLL) {
var keys = geolib.getKeys(originLL);
@@ -431,12 +442,12 @@
/**
- * Gets great circle bearing of two points. See description of getRhumbLineBearing for more information
- *
- * @param object origin coordinate (e.g. {latitude: 51.5023, longitude: 7.3815})
- * @param object destination coordinate
- * @return integer calculated bearing
- */
+ * Gets great circle bearing of two points. See description of getRhumbLineBearing for more information
+ *
+ * @param object origin coordinate (e.g. {latitude: 51.5023, longitude: 7.3815})
+ * @param object destination coordinate
+ * @return integer calculated bearing
+ */
getBearing: function(originLL, destLL) {
var keys = geolib.getKeys(originLL);
@@ -483,20 +494,20 @@
/**
- * Gets the compass direction from an origin coordinate to a destination coordinate.
- *
- * @param object origin coordinate (e.g. {latitude: 51.5023, longitude: 7.3815})
- * @param object destination coordinate
- * @param string Bearing mode. Can be either circle or rhumbline
- * @return object Returns an object with a rough (NESW) and an exact direction (NNE, NE, ENE, E, ESE, etc).
- */
+ * Gets the compass direction from an origin coordinate to a destination coordinate.
+ *
+ * @param object origin coordinate (e.g. {latitude: 51.5023, longitude: 7.3815})
+ * @param object destination coordinate
+ * @param string Bearing mode. Can be either circle or rhumbline
+ * @return object Returns an object with a rough (NESW) and an exact direction (NNE, NE, ENE, E, ESE, etc).
+ */
getCompassDirection: function(originLL, destLL, bearingMode) {
- var direction;
+ var direction, bearing;
if(bearingMode == 'circle') { // use great circle bearing
- var bearing = geolib.getBearing(originLL, destLL);
+ bearing = geolib.getBearing(originLL, destLL);
} else { // default is rhumb line bearing
- var bearing = geolib.getRhumbLineBearing(originLL, destLL);
+ bearing = geolib.getRhumbLineBearing(originLL, destLL);
}
switch(Math.round(bearing/22.5)) {
@@ -504,49 +515,49 @@
direction = {exact: "NNE", rough: "N"};
break;
case 2:
- direction = {exact: "NE", rough: "N"}
+ direction = {exact: "NE", rough: "N"};
break;
case 3:
- direction = {exact: "ENE", rough: "E"}
+ direction = {exact: "ENE", rough: "E"};
break;
case 4:
- direction = {exact: "E", rough: "E"}
+ direction = {exact: "E", rough: "E"};
break;
case 5:
- direction = {exact: "ESE", rough: "E"}
+ direction = {exact: "ESE", rough: "E"};
break;
case 6:
- direction = {exact: "SE", rough: "E"}
+ direction = {exact: "SE", rough: "E"};
break;
case 7:
- direction = {exact: "SSE", rough: "S"}
+ direction = {exact: "SSE", rough: "S"};
break;
case 8:
- direction = {exact: "S", rough: "S"}
+ direction = {exact: "S", rough: "S"};
break;
case 9:
- direction = {exact: "SSW", rough: "S"}
+ direction = {exact: "SSW", rough: "S"};
break;
case 10:
- direction = {exact: "SW", rough: "S"}
+ direction = {exact: "SW", rough: "S"};
break;
case 11:
- direction = {exact: "WSW", rough: "W"}
+ direction = {exact: "WSW", rough: "W"};
break;
case 12:
- direction = {exact: "W", rough: "W"}
+ direction = {exact: "W", rough: "W"};
break;
case 13:
- direction = {exact: "WNW", rough: "W"}
+ direction = {exact: "WNW", rough: "W"};
break;
case 14:
- direction = {exact: "NW", rough: "W"}
+ direction = {exact: "NW", rough: "W"};
break;
case 15:
- direction = {exact: "NNW", rough: "N"}
+ direction = {exact: "NNW", rough: "N"};
break;
default:
- direction = {exact: "N", rough: "N"}
+ direction = {exact: "N", rough: "N"};
}
return direction;
@@ -555,12 +566,12 @@
/**
- * Sorts an array of coords by distance from a reference coordinate
- *
- * @param object reference coordinate e.g. {latitude: 51.5023, longitude: 7.3815}
- * @param mixed array or object with coords [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...]
- * @return array ordered array
- */
+ * Sorts an array of coords by distance from a reference coordinate
+ *
+ * @param object reference coordinate e.g. {latitude: 51.5023, longitude: 7.3815}
+ * @param mixed array or object with coords [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...]
+ * @return array ordered array
+ */
orderByDistance: function(latlng, coords) {
var keys = geolib.getKeys(latlng);
@@ -579,12 +590,12 @@
/**
- * Finds the nearest coordinate to a reference coordinate
- *
- * @param object reference coordinate e.g. {latitude: 51.5023, longitude: 7.3815}
- * @param mixed array or object with coords [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...]
- * @return array ordered array
- */
+ * Finds the nearest coordinate to a reference coordinate
+ *
+ * @param object reference coordinate e.g. {latitude: 51.5023, longitude: 7.3815}
+ * @param mixed array or object with coords [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...]
+ * @return array ordered array
+ */
findNearest: function(latlng, coords, offset) {
offset = offset || 0;
@@ -595,11 +606,11 @@
/**
- * Calculates the length of a given path
- *
- * @param mixed array or object with coords [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...]
- * @return integer length of the path (in meters)
- */
+ * Calculates the length of a given path
+ *
+ * @param mixed array or object with coords [{latitude: 51.5143, longitude: 7.4138}, {latitude: 123, longitude: 123}, ...]
+ * @return integer length of the path (in meters)
+ */
getPathLength: function(coords) {
var dist = 0, last;
@@ -614,11 +625,12 @@
},
+ /*global google:true require:true module:true elevationResult*/
/**
- * @param Array Collection of coords [{latitude: 51.510, longitude: 7.1321}, {latitude: 49.1238, longitude: "8° 30' W"}, ...]
- *
- * @return Array [{lat:#lat, lng:#lng, elev:#elev},....]}
- */
+ * @param Array Collection of coords [{latitude: 51.510, longitude: 7.1321}, {latitude: 49.1238, longitude: "8° 30' W"}, ...]
+ *
+ * @return Array [{lat:#lat, lng:#lng, elev:#elev},....]}
+ */
getElevation: function() {
if (typeof window.navigator !== 'undefined') {
geolib.getElevationClient.apply(this, arguments);
@@ -628,15 +640,19 @@
},
getElevationClient: function(coords, cb) {
+
if (!window.google) {
throw new Error("Google maps api not loaded");
}
- if (coords.length == 0) {
- return cb(null, null);
- }
- if (coords.length == 1) {
- return cb(new Error("getElevation requires at least 2 points."));
- }
+
+ if (coords.length === 0) {
+ return cb(null, null);
+ }
+
+ if (coords.length === 1) {
+ return cb(new Error("getElevation requires at least 2 points."));
+ }
+
var path = [];
var keys = geolib.getKeys(coords[0]);
var latitude = keys.latitude;
@@ -648,6 +664,7 @@
geolib.useDecimal(coords[i][longitude])
));
}
+
var positionalRequest = {
'path': path,
'samples': path.length
@@ -656,19 +673,23 @@
elevationService.getElevationAlongPath(positionalRequest,function (results, status){
geolib.elevationHandler(results, status, coords, keys, cb);
});
+
},
- getElevationServer: function(coords, cb){
- if (coords.length == 0) {
- return cb(null, null);
- }
- if (coords.length == 1) {
- return cb(new Error("getElevation requires at least 2 points."));
- }
+ getElevationServer: function(coords, cb) {
+
+ if (coords.length === 0) {
+ return cb(null, null);
+ }
+
+ if (coords.length === 1) {
+ return cb(new Error("getElevation requires at least 2 points."));
+ }
+
var gm = require('googlemaps');
var path = [];
var keys = geolib.getKeys(coords[0]);
- coords[0]
+ //coords[0]
var latitude = keys.latitude;
var longitude = keys.longitude;
for(var i = 0; i < coords.length; i++) {
@@ -676,7 +697,7 @@
geolib.useDecimal(coords[i][longitude]));
}
gm.elevationFromPath(path.join('|'), path.length, function(err, results) {
- geolib.elevationHandler(results.results, results.status, coords, keys, cb)
+ geolib.elevationHandler(results.results, results.status, coords, keys, cb);
});
},
@@ -699,10 +720,10 @@
},
/**
- * @param Array [{lat:#lat, lng:#lng, elev:#elev},....]}
- *
- * @return Number % grade
- */
+ * @param Array [{lat:#lat, lng:#lng, elev:#elev},....]}
+ *
+ * @return Number % grade
+ */
getGrade: function(coords){
var keys = geolib.getKeys(coords[0]);
var elevation = keys.elevation;
@@ -712,10 +733,10 @@
},
/**
- * @param Array [{lat:#lat, lng:#lng, elev:#elev},....]}
- *
- * @return Object {gain:#gain, loss:#loss}
- */
+ * @param Array [{lat:#lat, lng:#lng, elev:#elev},....]}
+ *
+ * @return Object {gain:#gain, loss:#loss}
+ */
getTotalElevationGainAndLoss: function(coords){
var keys = geolib.getKeys(coords[0]);
var elevation = keys.elevation;
@@ -736,18 +757,18 @@
},
/**
- * Converts a distance from meters to km, mm, cm, mi, ft, in or yd
- *
- * @param string Format to be converted in
- * @param float Distance in meters
- * @param float Decimal places for rounding (default: 4)
- * @return float Converted distance
- */
+ * Converts a distance from meters to km, mm, cm, mi, ft, in or yd
+ *
+ * @param string Format to be converted in
+ * @param float Distance in meters
+ * @param float Decimal places for rounding (default: 4)
+ * @return float Converted distance
+ */
convertUnit: function(unit, distance, round) {
- if(distance == 0 || typeof distance == 'undefined') {
+ if(distance === 0 || typeof distance == 'undefined') {
- if(geolib.distance == 0) {
+ if(geolib.distance === 0) {
// throw 'No distance given.';
return 0;
} else {
@@ -763,31 +784,22 @@
case 'm': // Meter
return geolib.round(distance, round);
- break;
case 'km': // Kilometer
return geolib.round(distance / 1000, round);
- break;
case 'cm': // Centimeter
return geolib.round(distance * 100, round);
- break;
case 'mm': // Millimeter
return geolib.round(distance * 1000, round);
- break;
case 'mi': // Miles
return geolib.round(distance * (1 / 1609.344), round);
- break;
case 'sm': // Seamiles
return geolib.round(distance * (1 / 1852.216), round);
- break;
case 'ft': // Feet
return geolib.round(distance * (100 / 30.48), round);
- break;
case 'in': // Inch
return geolib.round(distance * 100 / 2.54, round);
- break;
case 'yd': // Yards
return geolib.round(distance * (1 / 0.9144), round);
- break;
}
return distance;
@@ -796,11 +808,11 @@
/**
- * Checks if a value is in decimal format or, if neccessary, converts to decimal
- *
- * @param mixed Value to be checked/converted
- * @return float Coordinate in decimal format
- */
+ * Checks if a value is in decimal format or, if neccessary, converts to decimal
+ *
+ * @param mixed Value to be checked/converted
+ * @return float Coordinate in decimal format
+ */
useDecimal: function(value) {
value = value.toString().replace(/\s*/, '');
@@ -810,7 +822,7 @@
if (!isNaN(parseFloat(value)) && parseFloat(value).toString() == value) {
return parseFloat(value);
// checks if it's sexagesimal format (HHH° MM' SS" (NESW))
- } else if(geolib.isSexagesimal(value) == true) {
+ } else if(geolib.isSexagesimal(value) === true) {
return parseFloat(geolib.sexagesimal2decimal(value));
} else {
throw 'Unknown format.';
@@ -820,11 +832,11 @@
/**
- * Converts a decimal coordinate value to sexagesimal format
- *
- * @param float decimal
- * @return string Sexagesimal value (XX° YY' ZZ")
- */
+ * Converts a decimal coordinate value to sexagesimal format
+ *
+ * @param float decimal
+ * @return string Sexagesimal value (XX° YY' ZZ")
+ */
decimal2sexagesimal: function(dec) {
if (dec in geolib.sexagesimal) {
@@ -848,11 +860,11 @@
/**
- * Converts a sexagesimal coordinate to decimal format
- *
- * @param float Sexagesimal coordinate
- * @return string Decimal value (XX.XXXXXXXX)
- */
+ * Converts a sexagesimal coordinate to decimal format
+ *
+ * @param float Sexagesimal coordinate
+ * @return string Decimal value (XX.XXXXXXXX)
+ */
sexagesimal2decimal: function(sexagesimal) {
if (sexagesimal in geolib.decimal) {
@@ -861,10 +873,11 @@
var regEx = new RegExp(sexagesimalPattern);
var data = regEx.exec(sexagesimal);
+ var min = 0, sec = 0;
if(data) {
- var min = parseFloat(data[2]/60);
- var sec = parseFloat(data[4]/3600) || 0;
+ min = parseFloat(data[2]/60);
+ sec = parseFloat(data[4]/3600) || 0;
}
var dec = ((parseFloat(data[1]) + min + sec)).toFixed(8);
@@ -879,11 +892,11 @@
/**
- * Checks if a value is in sexagesimal format
- *
- * @param string Value to be checked
- * @return bool True if in sexagesimal format
- */
+ * Checks if a value is in sexagesimal format
+ *
+ * @param string Value to be checked
+ * @return bool True if in sexagesimal format
+ */
isSexagesimal: function(value) {
return sexagesimalPattern.test(value);
@@ -895,18 +908,18 @@
return Math.round(value * decPlace)/decPlace;
}
- }
+ };
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
- }
+ };
}
if (typeof(Number.prototype.toDeg) === "undefined") {
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
- }
+ };
}
// we're in a browser
@@ -918,4 +931,4 @@
module.exports = geolib;
}
-})(this);
+}(this));
View
20 geolib.min.js
@@ -1,11 +1,11 @@
/**
- * A small library to provide some basic geo functions like distance calculation,
- * conversion of decimal coordinates to sexagesimal and vice versa, etc.
- * WGS 84 (World Geodetic System 1984)
- *
- * @author Manuel Bieh
- * @url http://www.manuelbieh.com/
- * @version 1.1.7
- * @license http://www.gnu.org/licenses/lgpl-3.0.txt LGPL
- *
- */(function(a,b){var c=6378137,d=/^([0-9]{1,3})°\s*([0-9]{1,3})'\s*(([0-9]{1,3}(\.([0-9]{1,2}))?)"\s*)?([NEOSW]?)$/,e={decimal:{},sexagesimal:{},distance:0,getKeys:function(a){var b=a.hasOwnProperty("lat")?"lat":"latitude",c=(a.hasOwnProperty("lng")?"lng":!1)||(a.hasOwnProperty("long")?"long":!1)||"longitude",d=(a.hasOwnProperty("alt")?"alt":!1)||(a.hasOwnProperty("altitude")?"altitude":!1)||(a.hasOwnProperty("elev")?"elev":!1)||"elevation";return{latitude:b,longitude:c,elevation:d}},getDistance:function(a,b,c){var d=e.getKeys(a),f=d.latitude,g=d.longitude,h=d.elevation;c=Math.floor(c)||1;var i={},j={};i[f]=e.useDecimal(a[f]),i[g]=e.useDecimal(a[g]),j[f]=e.useDecimal(b[f]),j[g]=e.useDecimal(b[g]);var k=6378137,l=6356752.314245,m=1/298.257223563,n=(j[g]-i[g]).toRad(),o=Math.atan((1-m)*Math.tan(parseFloat(i[f]).toRad())),p=Math.atan((1-m)*Math.tan(parseFloat(j[f]).toRad())),q=Math.sin(o),r=Math.cos(o),s=Math.sin(p),t=Math.cos(p),u=n,v,w=100;do{var x=Math.sin(u),y=Math.cos(u),z=Math.sqrt(t*x*t*x+(r*s-q*t*y)*(r*s-q*t*y));if(z==0)return e.distance=0;var A=q*s+r*t*y,B=Math.atan2(z,A),C=r*t*x/z,D=1-C*C,E=A-2*q*s/D;isNaN(E)&&(E=0);var F=m/16*D*(4+m*(4-3*D));v=u,u=n+(1-F)*m*C*(B+F*z*(E+F*A*(-1+2*E*E)))}while(Math.abs(u-v)>1e-12&&--w>0);if(w==0)return NaN;var G=D*(k*k-l*l)/(l*l),H=1+G/16384*(4096+G*(-768+G*(320-175*G))),I=G/1024*(256+G*(-128+G*(74-47*G))),J=I*z*(E+I/4*(A*(-1+2*E*E)-I/6*E*(-3+4*z*z)*(-3+4*E*E))),K=l*H*(B-J);K=K.toFixed(3);if(a.hasOwnProperty(h)&&b.hasOwnProperty(h)){var L=Math.abs(a[h]-b[h]);K=Math.sqrt(K*K+L*L)}return e.distance=Math.floor(Math.round(K/c)*c)},getDistanceSimple:function(a,b,d){var f=e.getKeys(a),g=f.latitude,h=f.longitude;d=Math.floor(d)||1;var i={},j={};i[g]=parseFloat(e.useDecimal(a[g])).toRad(),i[h]=parseFloat(e.useDecimal(a[h])).toRad(),j[g]=parseFloat(e.useDecimal(b[g])).toRad(),j[h]=parseFloat(e.useDecimal(b[h])).toRad();var k=Math.round(Math.acos(Math.sin(j[g])*Math.sin(i[g])+Math.cos(j[g])*Math.cos(i[g])*Math.cos(i[h]-j[h]))*c);return e.distance=Math.floor(Math.round(k/d)*d)},getCenter:function(a){if(!a.length)return!1;var b=e.getKeys(a[0]),c=b.latitude,d=b.longitude,f=function(a){return Math.max.apply(Math,a)},g=function(a){return Math.min.apply(Math,a)},h,i,j={lat:[],lng:[]};for(var k in a)j.lat.push(e.useDecimal(a[k][c])),j.lng.push(e.useDecimal(a[k][d]));var l=g(j.lat),m=g(j.lng),n=f(j.lat),o=f(j.lng);h=((l+n)/2).toFixed(6),i=((m+o)/2).toFixed(6);var p=e.convertUnit("km",e.getDistance({lat:l,lng:m},{lat:n,lng:o}));return{latitude:h,longitude:i,distance:p}},getBounds:function(a){if(!a.length)return!1;var b=e.getKeys(a[0]),c=b.latitude,d=b.longitude,f=b.elevation,g=a[0].hasOwnProperty(f),h={maxLat:0,minLat:Infinity,maxLng:0,minLng:Infinity};g&&(h.maxElev=0,h.minElev=Infinity);for(var i=0,j=a.length;i<j;++i)h.maxLat=Math.max(a[i][c],h.maxLat),h.minLat=Math.min(a[i][c],h.minLat),h.maxLng=Math.max(a[i][d],h.maxLng),h.minLng=Math.min(a[i][d],h.minLng),g&&(h.maxElev=Math.max(a[i][f],h.maxElev),h.minElev=Math.min(a[i][f],h.minElev));return h},isPointInside:function(a,b){var c=e.getKeys(a),d=c.latitude,f=c.longitude;for(var g=!1,h=-1,i=b.length,j=i-1;++h<i;j=h)(b[h][f]<=a[f]&&a[f]<b[j][f]||b[j][f]<=a[f]&&a[f]<b[h][f])&&a[d]<(b[j][d]-b[h][d])*(a[f]-b[h][f])/(b[j][f]-b[h][f])+b[h][d]&&(g=!g);return g},isPointInCircle:function(a,b,c){return e.getDistance(a,b)<c},getRhumbLineBearing:function(a,b){var c=e.getKeys(a),d=c.latitude,f=c.longitude,g=e.useDecimal(b[f]).toRad()-e.useDecimal(a[f]).toRad(),h=Math.log(Math.tan(e.useDecimal(b[d]).toRad()/2+Math.PI/4)/Math.tan(e.useDecimal(a[d]).toRad()/2+Math.PI/4));return Math.abs(g)>Math.PI&&(g>0?g=(2*Math.PI-g)*-1:g=2*Math.PI+g),(Math.atan2(g,h).toDeg()+360)%360},getBearing:function(a,b){var c=e.getKeys(a),d=c.latitude,f=c.longitude;b[d]=e.useDecimal(b[d]),b[f]=e.useDecimal(b[f]),a[d]=e.useDecimal(a[d]),a[f]=e.useDecimal(a[f]);var g=(Math.atan2(Math.sin(b[f].toRad()-a[f].toRad())*Math.cos(b[d].toRad()),Math.cos(a[d].toRad())*Math.sin(b[d].toRad())-Math.sin(a[d].toRad())*Math.cos(b[d].toRad())*Math.cos(b[f].toRad()-a[f].toRad())).toDeg()+360)%360;return g},getCompassDirection:function(a,b,c){var d;if(c=="circle")var f=e.getBearing(a,b);else var f=e.getRhumbLineBearing(a,b);switch(Math.round(f/22.5)){case 1:d={exact:"NNE",rough:"N"};break;case 2:d={exact:"NE",rough:"N"};break;case 3:d={exact:"ENE",rough:"E"};break;case 4:d={exact:"E",rough:"E"};break;case 5:d={exact:"ESE",rough:"E"};break;case 6:d={exact:"SE",rough:"E"};break;case 7:d={exact:"SSE",rough:"S"};break;case 8:d={exact:"S",rough:"S"};break;case 9:d={exact:"SSW",rough:"S"};break;case 10:d={exact:"SW",rough:"S"};break;case 11:d={exact:"WSW",rough:"W"};break;case 12:d={exact:"W",rough:"W"};break;case 13:d={exact:"WNW",rough:"W"};break;case 14:d={exact:"NW",rough:"W"};break;case 15:d={exact:"NNW",rough:"N"};break;default:d={exact:"N",rough:"N"}}return d},orderByDistance:function(a,b){var c=e.getKeys(a),d=c.latitude,f=c.longitude,g=[];for(var h in b){var i=e.getDistance(a,b[h]);g.push({key:h,latitude:b[h][d],longitude:b[h][f],distance:i})}return g.sort(function(a,b){return a.distance-b.distance})},findNearest:function(a,b,c){c=c||0;var d=e.orderByDistance(a,b);return d[c]},getPathLength:function(a){var b=0,c;for(var d=0,f=a.length;d<f;++d)c&&(b+=e.getDistance(a[d],c)),c=a[d];return b},getElevation:function(){typeof a.navigator!="undefined"?e.getElevationClient.apply(this,arguments):e.getElevationServer.apply(this,arguments)},getElevationClient:function(b,c){if(!a.google)throw new Error("Google maps api not loaded");if(b.length==0)return c(null,null);if(b.length==1)return c(new Error("getElevation requires at least 2 points."));var d=[],f=e.getKeys(b[0]),g=f.latitude,h=f.longitude;for(var i=0;i<b.length;i++)d.push(new google.maps.LatLng(e.useDecimal(b[i][g]),e.useDecimal(b[i][h])));var j={path:d,samples:d.length},k=new google.maps.ElevationService;k.getElevationAlongPath(j,function(a,d){e.elevationHandler(a,d,b,f,c)})},getElevationServer:function(a,b){if(a.length==0)return b(null,null);if(a.length==1)return b(new Error("getElevation requires at least 2 points."));var c=require("googlemaps"),d=[],f=e.getKeys(a[0]);a[0];var g=f.latitude,h=f.longitude;for(var i=0;i<a.length;i++)d.push(e.useDecimal(a[i][g])+","+e.useDecimal(a[i][h]));c.elevationFromPath(d.join("|"),d.length,function(c,d){e.elevationHandler(d.results,d.status,a,f,b)})},elevationHandler:function(a,b,c,d,e){var f=[],g=d.latitude,h=d.longitude;if(b=="OK"){for(var i=0;i<a.length;i++)f.push({lat:c[i][g],lng:c[i][h],elev:a[i].elevation});e(null,f)}else e(new Error("Could not get elevation using Google's API"),elevationResult.status)},getGrade:function(a){var b=e.getKeys(a[0]),c=b.elevation,d=Math.abs(a[a.length-1][c]-a[0][c]),f=e.getPathLength(a);return Math.floor(d/f*100)},getTotalElevationGainAndLoss:function(a){var b=e.getKeys(a[0]),c=b.elevation,d=0,f=0;for(var g=0;g<a.length-1;g++){var h=a[g][c]-a[g+1][c];h>0?f+=h:d+=Math.abs(h)}return{gain:d,loss:f}},convertUnit:function(a,b,c){if(b==0||typeof b=="undefined"){if(e.distance==0)return 0;b=e.distance}a=a||"m",c=c||4;switch(a){case"m":return e.round(b,c);case"km":return e.round(b/1e3,c);case"cm":return e.round(b*100,c);case"mm":return e.round(b*1e3,c);case"mi":return e.round(b*(1/1609.344),c);case"sm":return e.round(b*(1/1852.216),c);case"ft":return e.round(b*(100/30.48),c);case"in":return e.round(b*100/2.54,c);case"yd":return e.round(b*(1/.9144),c)}return b},useDecimal:function(a){a=a.toString().replace(/\s*/,"");if(!isNaN(parseFloat(a))&&parseFloat(a).toString()==a)return parseFloat(a);if(e.isSexagesimal(a)==1)return parseFloat(e.sexagesimal2decimal(a));throw"Unknown format."},decimal2sexagesimal:function(a){if(a in e.sexagesimal)return e.sexagesimal[a];var b=a.toString().split("."),c=Math.abs(b[0]),d=("0."+b[1])*60,f=d.toString().split(".");return d=Math.floor(d),f=(("0."+f[1])*60).toFixed(2),e.sexagesimal[a]=c+"° "+d+"' "+f+'"',e.sexagesimal[a]},sexagesimal2decimal:function(a){if(a in e.decimal)return e.decimal[a];var b=new RegExp(d),c=b.exec(a);if(c)var f=parseFloat(c[2]/60),g=parseFloat(c[4]/3600)||0;var h=(parseFloat(c[1])+f+g).toFixed(8);return h=c[7]=="S"||c[7]=="W"?h*-1:h,e.decimal[a]=h,h},isSexagesimal:function(a){return d.test(a)},round:function(a,b){var c=Math.pow(10,b);return Math.round(a*c)/c}};typeof Number.prototype.toRad=="undefined"&&(Number.prototype.toRad=function(){return this*Math.PI/180}),typeof Number.prototype.toDeg=="undefined"&&(Number.prototype.toDeg=function(){return this*180/Math.PI}),typeof a.navigator!="undefined"?a.geolib=e:module.exports=e})(this);
+* A small library to provide some basic geo functions like distance calculation,
+* conversion of decimal coordinates to sexagesimal and vice versa, etc.
+* WGS 84 (World Geodetic System 1984)
+*
+* @author Manuel Bieh
+* @url http://www.manuelbieh.com/
+* @version 1.1.8
+* @license LGPL
+**/
+(function(a,b){var c=6378137,d=/^([0-9]{1,3})°\s*([0-9]{1,3})'\s*(([0-9]{1,3}(\.([0-9]{1,2}))?)"\s*)?([NEOSW]?)$/,e={decimal:{},sexagesimal:{},distance:0,getKeys:function(a){var b=a.hasOwnProperty("lat")?"lat":"latitude",c=(a.hasOwnProperty("lng")?"lng":!1)||(a.hasOwnProperty("long")?"long":!1)||"longitude",d=(a.hasOwnProperty("alt")?"alt":!1)||(a.hasOwnProperty("altitude")?"altitude":!1)||(a.hasOwnProperty("elev")?"elev":!1)||"elevation";return{latitude:b,longitude:c,elevation:d}},getDistance:function(a,b,c){var d=e.getKeys(a),f=d.latitude,g=d.longitude,h=d.elevation;c=Math.floor(c)||1;var i={},j={};i[f]=e.useDecimal(a[f]),i[g]=e.useDecimal(a[g]),j[f]=e.useDecimal(b[f]),j[g]=e.useDecimal(b[g]);var k=6378137,l=6356752.314245,m=1/298.257223563,n=(j[g]-i[g]).toRad(),o,p,q,r,s,t,u=Math.atan((1-m)*Math.tan(parseFloat(i[f]).toRad())),v=Math.atan((1-m)*Math.tan(parseFloat(j[f]).toRad())),w=Math.sin(u),x=Math.cos(u),y=Math.sin(v),z=Math.cos(v),A=n,B,C=100;do{var D=Math.sin(A),E=Math.cos(A);t=Math.sqrt(z*D*z*D+(x*y-w*z*E)*(x*y-w*z*E));if(t===0)return e.distance=0;o=w*y+x*z*E,p=Math.atan2(t,o),q=x*z*D/t,r=1-q*q,s=o-2*w*y/r,isNaN(s)&&(s=0);var F=m/16*r*(4+m*(4-3*r));B=A,A=n+(1-F)*m*q*(p+F*t*(s+F*o*(-1+2*s*s)))}while(Math.abs(A-B)>1e-12&&--C>0);if(C===0)return NaN;var G=r*(k*k-l*l)/(l*l),H=1+G/16384*(4096+G*(-768+G*(320-175*G))),I=G/1024*(256+G*(-128+G*(74-47*G))),J=I*t*(s+I/4*(o*(-1+2*s*s)-I/6*s*(-3+4*t*t)*(-3+4*s*s))),K=l*H*(p-J);K=K.toFixed(3);if(a.hasOwnProperty(h)&&b.hasOwnProperty(h)){var L=Math.abs(a[h]-b[h]);K=Math.sqrt(K*K+L*L)}return e.distance=Math.floor(Math.round(K/c)*c)},getDistanceSimple:function(a,b,d){var f=e.getKeys(a),g=f.latitude,h=f.longitude;d=Math.floor(d)||1;var i={},j={};i[g]=parseFloat(e.useDecimal(a[g])).toRad(),i[h]=parseFloat(e.useDecimal(a[h])).toRad(),j[g]=parseFloat(e.useDecimal(b[g])).toRad(),j[h]=parseFloat(e.useDecimal(b[h])).toRad();var k=Math.round(Math.acos(Math.sin(j[g])*Math.sin(i[g])+Math.cos(j[g])*Math.cos(i[g])*Math.cos(i[h]-j[h]))*c);return e.distance=Math.floor(Math.round(k/d)*d)},getCenter:function(a){if(!a.length)return!1;var b=e.getKeys(a[0]),c=b.latitude,d=b.longitude,f=function(a){return Math.max.apply(Math,a)},g=function(a){return Math.min.apply(Math,a)},h,i,j={lat:[],lng:[]};for(var k in a)j.lat.push(e.useDecimal(a[k][c])),j.lng.push(e.useDecimal(a[k][d]));var l=g(j.lat),m=g(j.lng),n=f(j.lat),o=f(j.lng);h=((l+n)/2).toFixed(6),i=((m+o)/2).toFixed(6);var p=e.convertUnit("km",e.getDistance({lat:l,lng:m},{lat:n,lng:o}));return{latitude:h,longitude:i,distance:p}},getBounds:function(a){if(!a.length)return!1;var b=e.getKeys(a[0]),c=b.latitude,d=b.longitude,f=b.elevation,g=a[0].hasOwnProperty(f),h={maxLat:0,minLat:Infinity,maxLng:0,minLng:Infinity};g&&(h.maxElev=0,h.minElev=Infinity);for(var i=0,j=a.length;i<j;++i)h.maxLat=Math.max(a[i][c],h.maxLat),h.minLat=Math.min(a[i][c],h.minLat),h.maxLng=Math.max(a[i][d],h.maxLng),h.minLng=Math.min(a[i][d],h.minLng),g&&(h.maxElev=Math.max(a[i][f],h.maxElev),h.minElev=Math.min(a[i][f],h.minElev));return h},isPointInside:function(a,b){var c=e.getKeys(a),d=c.latitude,f=c.longitude;for(var g=!1,h=-1,i=b.length,j=i-1;++h<i;j=h)(b[h][f]<=a[f]&&a[f]<b[j][f]||b[j][f]<=a[f]&&a[f]<b[h][f])&&a[d]<(b[j][d]-b[h][d])*(a[f]-b[h][f])/(b[j][f]-b[h][f])+b[h][d]&&(g=!g);return g},isPointInCircle:function(a,b,c){return e.getDistance(a,b)<c},getRhumbLineBearing:function(a,b){var c=e.getKeys(a),d=c.latitude,f=c.longitude,g=e.useDecimal(b[f]).toRad()-e.useDecimal(a[f]).toRad(),h=Math.log(Math.tan(e.useDecimal(b[d]).toRad()/2+Math.PI/4)/Math.tan(e.useDecimal(a[d]).toRad()/2+Math.PI/4));return Math.abs(g)>Math.PI&&(g>0?g=(2*Math.PI-g)*-1:g=2*Math.PI+g),(Math.atan2(g,h).toDeg()+360)%360},getBearing:function(a,b){var c=e.getKeys(a),d=c.latitude,f=c.longitude;b[d]=e.useDecimal(b[d]),b[f]=e.useDecimal(b[f]),a[d]=e.useDecimal(a[d]),a[f]=e.useDecimal(a[f]);var g=(Math.atan2(Math.sin(b[f].toRad()-a[f].toRad())*Math.cos(b[d].toRad()),Math.cos(a[d].toRad())*Math.sin(b[d].toRad())-Math.sin(a[d].toRad())*Math.cos(b[d].toRad())*Math.cos(b[f].toRad()-a[f].toRad())).toDeg()+360)%360;return g},getCompassDirection:function(a,b,c){var d,f;c=="circle"?f=e.getBearing(a,b):f=e.getRhumbLineBearing(a,b);switch(Math.round(f/22.5)){case 1:d={exact:"NNE",rough:"N"};break;case 2:d={exact:"NE",rough:"N"};break;case 3:d={exact:"ENE",rough:"E"};break;case 4:d={exact:"E",rough:"E"};break;case 5:d={exact:"ESE",rough:"E"};break;case 6:d={exact:"SE",rough:"E"};break;case 7:d={exact:"SSE",rough:"S"};break;case 8:d={exact:"S",rough:"S"};break;case 9:d={exact:"SSW",rough:"S"};break;case 10:d={exact:"SW",rough:"S"};break;case 11:d={exact:"WSW",rough:"W"};break;case 12:d={exact:"W",rough:"W"};break;case 13:d={exact:"WNW",rough:"W"};break;case 14:d={exact:"NW",rough:"W"};break;case 15:d={exact:"NNW",rough:"N"};break;default:d={exact:"N",rough:"N"}}return d},orderByDistance:function(a,b){var c=e.getKeys(a),d=c.latitude,f=c.longitude,g=[];for(var h in b){var i=e.getDistance(a,b[h]);g.push({key:h,latitude:b[h][d],longitude:b[h][f],distance:i})}return g.sort(function(a,b){return a.distance-b.distance})},findNearest:function(a,b,c){c=c||0;var d=e.orderByDistance(a,b);return d[c]},getPathLength:function(a){var b=0,c;for(var d=0,f=a.length;d<f;++d)c&&(b+=e.getDistance(a[d],c)),c=a[d];return b},getElevation:function(){typeof a.navigator!="undefined"?e.getElevationClient.apply(this,arguments):e.getElevationServer.apply(this,arguments)},getElevationClient:function(b,c){if(!a.google)throw new Error("Google maps api not loaded");if(b.length===0)return c(null,null);if(b.length===1)return c(new Error("getElevation requires at least 2 points."));var d=[],f=e.getKeys(b[0]),g=f.latitude,h=f.longitude;for(var i=0;i<b.length;i++)d.push(new google.maps.LatLng(e.useDecimal(b[i][g]),e.useDecimal(b[i][h])));var j={path:d,samples:d.length},k=new google.maps.ElevationService;k.getElevationAlongPath(j,function(a,d){e.elevationHandler(a,d,b,f,c)})},getElevationServer:function(a,b){if(a.length===0)return b(null,null);if(a.length===1)return b(new Error("getElevation requires at least 2 points."));var c=require("googlemaps"),d=[],f=e.getKeys(a[0]),g=f.latitude,h=f.longitude;for(var i=0;i<a.length;i++)d.push(e.useDecimal(a[i][g])+","+e.useDecimal(a[i][h]));c.elevationFromPath(d.join("|"),d.length,function(c,d){e.elevationHandler(d.results,d.status,a,f,b)})},elevationHandler:function(a,b,c,d,e){var f=[],g=d.latitude,h=d.longitude;if(b=="OK"){for(var i=0;i<a.length;i++)f.push({lat:c[i][g],lng:c[i][h],elev:a[i].elevation});e(null,f)}else e(new Error("Could not get elevation using Google's API"),elevationResult.status)},getGrade:function(a){var b=e.getKeys(a[0]),c=b.elevation,d=Math.abs(a[a.length-1][c]-a[0][c]),f=e.getPathLength(a);return Math.floor(d/f*100)},getTotalElevationGainAndLoss:function(a){var b=e.getKeys(a[0]),c=b.elevation,d=0,f=0;for(var g=0;g<a.length-1;g++){var h=a[g][c]-a[g+1][c];h>0?f+=h:d+=Math.abs(h)}return{gain:d,loss:f}},convertUnit:function(a,b,c){if(b===0||typeof b=="undefined"){if(e.distance===0)return 0;b=e.distance}a=a||"m",c=null==c?4:c;switch(a){case"m":return e.round(b,c);case"km":return e.round(b/1e3,c);case"cm":return e.round(b*100,c);case"mm":return e.round(b*1e3,c);case"mi":return e.round(b*(1/1609.344),c);case"sm":return e.round(b*(1/1852.216),c);case"ft":return e.round(b*(100/30.48),c);case"in":return e.round(b*100/2.54,c);case"yd":return e.round(b*(1/.9144),c)}return b},useDecimal:function(a){a=a.toString().replace(/\s*/,"");if(!isNaN(parseFloat(a))&&parseFloat(a).toString()==a)return parseFloat(a);if(e.isSexagesimal(a)===!0)return parseFloat(e.sexagesimal2decimal(a));throw"Unknown format."},decimal2sexagesimal:function(a){if(a in e.sexagesimal)return e.sexagesimal[a];var b=a.toString().split("."),c=Math.abs(b[0]),d=("0."+b[1])*60,f=d.toString().split(".");return d=Math.floor(d),f=(("0."+f[1])*60).toFixed(2),e.sexagesimal[a]=c+"° "+d+"' "+f+'"',e.sexagesimal[a]},sexagesimal2decimal:function(a){if(a in e.decimal)return e.decimal[a];var b=new RegExp(d),c=b.exec(a),f=0,g=0;c&&(f=parseFloat(c[2]/60),g=parseFloat(c[4]/3600)||0);var h=(parseFloat(c[1])+f+g).toFixed(8);return h=c[7]=="S"||c[7]=="W"?h*-1:h,e.decimal[a]=h,h},isSexagesimal:function(a){return d.test(a)},round:function(a,b){var c=Math.pow(10,b);return Math.round(a*c)/c}};typeof Number.prototype.toRad=="undefined"&&(Number.prototype.toRad=function(){return this*Math.PI/180}),typeof Number.prototype.toDeg=="undefined"&&(Number.prototype.toDeg=function(){return this*180/Math.PI}),typeof a.navigator!="undefined"?a.geolib=e:module.exports=e})(this);
View
62 grunt.js
@@ -0,0 +1,62 @@
+/*global module:false*/
+module.exports = function(grunt) {
+
+ // Project configuration.
+ grunt.initConfig({
+ pkg: '<json:package.json>',
+ meta: {
+ banner: '/**\n'+
+ '* A small library to provide some basic geo functions like distance calculation,\n' +
+ '* conversion of decimal coordinates to sexagesimal and vice versa, etc.\n' +
+ '* WGS 84 (World Geodetic System 1984)\n' +
+ '* \n' +
+ '* @author <%= pkg.author.name %>\n' +
+ '* @url <%= pkg.author.url %>\n' +
+ '* @version <%= pkg.version %>\n' +
+ '* @license <%= _.pluck(pkg.licenses, "type").join(", ") %> \n**/'
+ },
+ lint: {
+ files: ['geolib.js']
+ },
+ test: {
+ files: ['tests/*.js']
+ },
+ concat: {
+ dist: {
+ src: ['<banner:meta.banner>', '<file_strip_banner:<%= pkg.name %>.js>'],
+ dest: '<%= pkg.name %>.js'
+ }
+ },
+ min: {
+ dist: {
+ src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
+ dest: '<%= pkg.name %>.min.js'
+ }
+ },
+ watch: {
+ files: '<config:lint.files>',
+ tasks: 'lint test'
+ },
+ jshint: {
+ options: {
+ curly: true,
+ eqeqeq: false,
+ immed: true,
+ latedef: true,
+ newcap: false,
+ noarg: true,
+ sub: true,
+ undef: true,
+ boss: true,
+ eqnull: true
+ },
+ globals: {}
+ },
+ uglify: {}
+ });
+
+ // Default task.
+ //grunt.registerTask('default', 'lint test concat min');
+ grunt.registerTask('default', 'lint concat min');
+
+};
View
62 package.json
@@ -1,26 +1,38 @@
{
- "name": "geolib",
- "homepage": "http://github.com/manuelbieh/Geolib",
- "author": {
- "name": "Manuel Bieh",
- "url": "http://www.manuelbieh.com/"
- },
- "bin": {
- "geolib" : "./geolib.js"
- },
- "repository": {
- "type" : "git",
- "url" : "http://github.com/manuelbieh/geolib.git"
- },
- "dependencies": {
- "googlemaps": ">= 0.1.6"
- },
- "devDependencies": {
- "mocha": "*"
- },
- "files": ["geolib.js"],
- "description": "Growing library to perform geo specific tasks",
- "keywords": ["geolocation", "geo", "distance"],
- "version": "1.1.7",
- "main": "./geolib"
-}
+ "name": "geolib",
+ "homepage": "http://github.com/manuelbieh/Geolib",
+ "author": {
+ "name": "Manuel Bieh",
+ "url": "http://www.manuelbieh.com/"
+ },
+ "bin": {
+ "geolib": "./geolib.js"
+ },
+ "repository": {
+ "type": "git",
+ "url": "http://github.com/manuelbieh/geolib.git"
+ },
+ "dependencies": {
+ "googlemaps": ">= 0.1.6"
+ },
+ "devDependencies": {
+ "mocha": "*"
+ },
+ "licenses": [
+ {
+ "type": "LGPL",
+ "url": "http://www.gnu.org/licenses/lgpl-3.0.txt"
+ }
+ ],
+ "files": [
+ "geolib.js"
+ ],
+ "description": "Library to perform geo specific tasks",
+ "keywords": [
+ "geolocation",
+ "geo",
+ "distance"
+ ],
+ "version": "1.1.8",
+ "main": "./geolib"
+}
View
285 tests/geolib.test.html
@@ -3,283 +3,14 @@
<html>
<head>
- <meta charset="utf-8">
- <script src="http://code.jquery.com/jquery-latest.js"></script>
- <!-- script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDxikL7zFrgea3gBya8OECSsOgvKuuFLb8&sensor=true"></script-->
- <script type="text/javascript" src='http://maps.googleapis.com/maps/api/js?sensor=true'></script>
- <script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script>
- <script type="text/javascript" src="../geolib.js"></script>
- <link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" />
-
-<script>
-$(function(){
-
- var cities = {
- "Berlin": {latitude: 52.518611, longitude: 13.408056},
- "Boston": {latitude: 42.357778, longitude: "71° 3' 34\" W"},
- "Dortmund": {latitude: "51° 31' 10.11\" N", longitude: "7° 28' 01\" E"},
- "London": {latitude: "51° 31' N", longitude: "0° 7' W"},
- "Manchester": {latitude: "53° 29' N", longitude: "2° 14' W"},
- "New York City": {latitude: 40.715517, longitude: -73.9991},
- "San Francisco": {latitude: 37.774514, longitude: -122.418079},
- "Moscow": {latitude: 55.751667, longitude: 37.617778}
- }
-
- var polygon = [{"latitude": 51.513357512, "longitude": 7.45574331},
- {"latitude": 51.515400598, "longitude": 7.45518541},
- {"latitude": 51.516241842, "longitude": 7.456494328},
- {"latitude": 51.516722545, "longitude": 7.459863183},
- {"latitude": 51.517443592, "longitude": 7.463232037},
- {"latitude": 51.5177507, "longitude": 7.464755532},
- {"latitude": 51.517657233, "longitude": 7.466622349},
- {"latitude": 51.51722995, "longitude": 7.468317505},
- {"latitude": 51.516816015, "longitude": 7.47011995},
- {"latitude": 51.516308606, "longitude": 7.471793648},
- {"latitude": 51.515974782, "longitude": 7.472437378},
- {"latitude": 51.515413951, "longitude": 7.472845074},
- {"latitude": 51.514559338, "longitude": 7.472909447},
- {"latitude": 51.512195717, "longitude": 7.472651955},
- {"latitude": 51.511127373, "longitude": 7.47140741},
- {"latitude": 51.51029939, "longitude": 7.469948288},
- {"latitude": 51.509831973, "longitude": 7.468446251},
- {"latitude": 51.509978876, "longitude": 7.462481019},
- {"latitude": 51.510913701, "longitude": 7.460678574},
- {"latitude": 51.511594777, "longitude": 7.459434029},
- {"latitude": 51.512396029, "longitude": 7.457695958},
- {"latitude": 51.513317451, "longitude": 7.45574331}
- ];
-
- var polygon2 = [
- {"latitude": 51.513357512, "longitude": 7.45574331, "elevation":523.92},
- {"latitude": 51.515400598, "longitude": 7.45518541, "elevation":524.54},
- {"latitude": 51.516241842, "longitude": 7.456494328, "elevation":523.12},
- {"latitude": 51.516722545, "longitude": 7.459863183, "elevation":522.77},
- {"latitude": 51.517443592, "longitude": 7.463232037, "elevation":521.12}
- ];
-
- test("Testing distance calculation: getDistance()", function() {
-
- expect(3);
-
- var distance1 = geolib.getDistance({latitude: 52.518611, longitude: 13.408056}, {latitude: 51.519475, longitude: 7.46694444});
- var distance2 = geolib.getDistance({latitude: 52.518611, longitude: 13.408056}, {latitude: 51.519475, longitude: 7.46694444}, 100);
- var distance3 = geolib.getDistance({latitude: 37.774514, longitude: -122.418079}, {latitude: 51.519475, longitude: 7.46694444});
-
- equal(distance1, 422592, "Distance 1 should be 422592" );
- equal(distance2, 422600, "Distance 2 should be 422600" );
- equal(distance3, 8980260, "Distance 3 should be 8980260" );
-
- });
-
- test("Testing distance calculation: getDistanceSimple()", function() {
-
- expect(3);
-
- var distance1 = geolib.getDistanceSimple({latitude: 52.518611, longitude: 13.408056}, {latitude: 51.519475, longitude: 7.46694444});
- var distance2 = geolib.getDistanceSimple({latitude: 52.518611, longitude: 13.408056}, {latitude: 51.519475, longitude: 7.46694444}, 100);
- var distance3 = geolib.getDistanceSimple({latitude: 37.774514, longitude: -122.418079}, {latitude: 51.519475, longitude: 7.46694444});
-
- equal(distance1, 421786, "Distance 1 should be 421786" );
- equal(distance2, 421800, "Distance 2 should be 421800" );
- equal(distance3, 8967172, "Distance 3 should be 8967172" );
-
- });
-
- test("Testing bounding box: getBounds()", function() {
- expect(12);
-
- var box = geolib.getBounds(polygon);
-
- equal(box.maxLat, 51.5177507, "maxLat should be 51.5177507");
- equal(box.minLat, 51.509831973, "minLat should be 51.509831973");
- equal(box.maxLng, 7.472909447, "maxLng should be 7.472909447");
- equal(box.minLng, 7.45518541, "minLng should be 7.45518541");
- equal(typeof box.minElev, "undefined", "minElev should be undefind");
- equal(typeof box.maxElev, "undefined", "maxElev should be undefind");
-
- box = geolib.getBounds(polygon2);
-
- equal(box.maxLat, 51.517443592, "maxLat should be 51.517443592");
- equal(box.minLat, 51.513357512, "minLat should be 51.513357512");
- equal(box.maxLng, 7.463232037, "maxLng should be 7.463232037");
- equal(box.minLng, 7.45518541, "minLng should be 7.45518541");
- equal(box.maxElev, 524.54, "maxElev should be 524.54");
- equal(box.minElev, 521.12, "minElev should be 521.12");
- });
-
- asyncTest("Testing elevation: getElevation()", function() {
- expect(4);
-
- var latsLngsElevs;
- var coords1 = [{"lat":33.76346,"lng":-84.43430000000001},
- {"lat":33.76418,"lng":-84.42999999999995}];
- var coords2 = [{"lat":41.73549,"lng":-111.85842000000002},
- {"lat":41.73600999999999,"lng":-111.85572000000002}];
-
- var doneCount = 0;
- var done = function (){
- ++doneCount;
- if (doneCount === 2) {
- start();
- }
- };
-
- geolib.getElevation(coords1,function(err, results){
- if (err) {
- throw err;
- }
- latsLngsElevs = results;
- equal(latsLngsElevs[0].elev, 297.8508605957031, "1st elev should be 297.8508605957031");
- equal(latsLngsElevs[1].elev, 281.1884155273438, "2nd elev should be 281.1884155273438");
- done();
- });
-
- geolib.getElevation(coords2,function(err, results){
- if (err) {
- throw err;
- }
- latsLngsElevs = results;
- equal(latsLngsElevs[0].elev, 1358.223999023438, "1st elev should be 1358.223999023438");
- equal(latsLngsElevs[1].elev, 1360.70654296875, "2nd elev should be 1360.70654296875");
- done();
- });
-
- });
-
- test("Testing grade: getGrade()", function() {
- expect(2);
- var coords1 = [{"lat":41.72977,"lng":-111.77621999999997,"elev":1702.72412109375},
- {"lat":41.73198,"lng":-111.77636999999999,"elev":1849.7333984375}];
- var coords2 = [{"lat":40.75402,"lng":-111.75475,"elev":2209.137451171875},
- {"lat":40.76481,"lng":-111.76778999999999,"elev":1660.49609375}];
-
- var grade = geolib.getGrade(coords1);
- equal(grade, 51, "grade should be 51");
-
- grade = geolib.getGrade(coords2);
- equal(grade, 31, "grade should be 31");
- });
-
- test("Testing elevation gain and loss: getTotalElevationGainAndLoss()", function() {
- expect(4);
- var coords1 = [{"lat":41.72975,"lng":-111.77580999999998,"elev":1707.123046875},
- {"lat":41.73298475750587,"lng":-111.77603699785413,"elev":1922.056396484375},
- {"lat":41.73517,"lng":-111.77881000000002,"elev":1893.9931640625}];
- var coords2 = [{"lat":40.79162,"lng":-111.76560999999998,"elev":2211.202880859375},
- {"lat":40.79938945887229,"lng":-111.76680525603354,"elev":1995.89990234375},
- {"lat":40.80354,"lng":-111.77384999999998,"elev":1978.573120117188}];
-
- var gainAndLoss = geolib.getTotalElevationGainAndLoss(coords1);
- equal(gainAndLoss.gain, 214.933349609375, "gain should be 214.933349609375");
- equal(gainAndLoss.loss, 28.063232421875, "loss should be 28.063232421875");
-
- gainAndLoss = geolib.getTotalElevationGainAndLoss(coords2);
- equal(gainAndLoss.gain, 0, "gain should be 0");
- equal(gainAndLoss.loss, 232.62976074218705, "loss should be 232.62976074218705");
- });
-
- test("Testing conversion: sexagesimal2decimal()", function() {
-
- expect(7);
-
- var dec1 = geolib.useDecimal("51° 31' 10.11\" N");
- var dec2 = geolib.useDecimal("7° 28' 01\" E");
- var dec3 = geolib.useDecimal("19° 22' 32\" S");
- var dec4 = geolib.useDecimal("71° 3' 34\" W");
- var dec5 = geolib.useDecimal("71°3'W");
- var dec6 = geolib.useDecimal("51.519475");
- var dec7 = geolib.useDecimal("-122.418079");
-
- equal(dec1, 51.519475, "Decimal value should be 51.519475" );
- equal(dec2, 7.46694444, "Decimal value should be 7.46694444" );
- equal(dec3, -19.37555556, "Decimal value should be -19.37555556" );
- equal(dec4, -71.05944444, "Decimal value should be -71.05944444" );
- equal(dec5, -71.05, "Decimal value should be -71.05" );
- equal(dec6, 51.519475, "Decimal value should be 51.519475" );
- equal(dec7, -122.418079, "Decimal value should be -122.418079" );
-
- });
-
- test("Testing conversion: decimal2sexagesimal()", function() {
-
- expect(2);
- var sexa1 = geolib.decimal2sexagesimal(51.519475);
- var sexa2 = geolib.decimal2sexagesimal(-19.37555556);
-
- equal(sexa1, '51° 31\' 10.11"', "Decimal value should be 51° 31' 10.11\"" );
- equal(sexa2, '19° 22\' 32.00"', "Decimal value should be 19° 22' 32\" S" );
-
- });
-
- test("Testing: getCompassDirection()", function() {
-
- expect(2);
- var dir1 = geolib.getCompassDirection({latitude: 52.518611, longitude: 13.408056}, {latitude: 51.519475, longitude: 7.46694444});
-
- equal(dir1.rough, 'W', 'Should be west');
- equal(dir1.exact, 'WSW', 'Should be west-south-west');
-
- });
-
-
- test("Testing: findNearest()", function() {
-
- expect(4);
- var near1 = geolib.findNearest({latitude: 36.1168, longitude: -115.173798}, cities);
-
- equal(near1.key, 'San Francisco', 'Nearest city to Las Vegas from predefined set should be San Francisco');
- equal(near1.distance, 670788, 'Distance should be 670788');
- equal(near1.latitude, 37.774514, 'Latitude should be 37.774514');
- equal(near1.longitude, -122.418079, 'Latitude should be -122.418079');
-
- });
-
- test("Testing: getPathLength()", function() {
-
- var pathLength = geolib.getPathLength(polygon);
- equal(pathLength, 3377, 'Path length should be 3377');
-
- });
-
- test("Testing: isPointInside()", function() {
-
- var isInside1 = geolib.isPointInside({latitude: 51.514252208, longitude: 7.464905736}, polygon); // Point is inside of the polygon
- var isInside2 = geolib.isPointInside({latitude: 51.510539773, longitude: 7.454691884}, polygon); // Point is not inside polygon
-
- ok(isInside1, "Point 1 is inside polygon");
- ok(!isInside2, "Point 2 is not inside polygon");
-
- });
-
- test("Testing: convertUnit()", function() {
-
- equal(geolib.convertUnit('km', 1000), 1, 'Conversion of 1000 m to km');
- equal(geolib.convertUnit('m', 1000), 1000, 'Conversion of 1000 m to m (just to make sure)');
- equal(geolib.convertUnit('cm', 1000), 100000, 'Conversion of 1000 m to cm');
- equal(geolib.convertUnit('mm', 1000), 1000000, 'Conversion of 1000 m to mm');
- equal(geolib.convertUnit('mi', 1000), 0.6214, 'Conversion of 1000 m to miles');
- equal(geolib.convertUnit('sm', 1000), 0.5399, 'Conversion of 1000 m to seamiles');
- equal(geolib.convertUnit('ft', 1000), 3280.8399, 'Conversion of 1000 m to ft');
- equal(geolib.convertUnit('in', 1000), 39370.0787, 'Conversion of 1000 m to in');
- equal(geolib.convertUnit('yd', 1000), 1093.6133, 'Conversion of 1000 m to yd');
-
- });
-
- test("Testing: isSexagesimal()", function() {
-
- ok(geolib.isSexagesimal('51° 31\''), '51° 31\'');
- ok(geolib.isSexagesimal('51° 31\' 12"'), '51° 31\' 12"');
- ok(geolib.isSexagesimal('51° 31\' 12.27"'), '51° 31\' 12.27"');
- ok(geolib.isSexagesimal('51° 31\' 12.27" N'), '51° 31\' 12.27" N');
- ok(geolib.isSexagesimal('51° 31\' N'), '51° 31\' N');
- //ok(geolib.isSexagesimal('51° N'), '51°'); // coming soon
-
- });
-
-
-
-});
-</script>
+<meta charset="utf-8">
+<script src="http://code.jquery.com/jquery-latest.js"></script>
+<!-- script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDxikL7zFrgea3gBya8OECSsOgvKuuFLb8&sensor=true"></script-->
+<script type="text/javascript" src='http://maps.googleapis.com/maps/api/js?sensor=true'></script>
+<script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script>
+<script type="text/javascript" src="../geolib.js"></script>
+<script type="text/javascript" src="geolib.test.js"></script>
+<link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" />
</head>
<body>
View
265 tests/geolib.test.js
@@ -0,0 +1,265 @@
+/*global test:true expect:true geolib:true equal:true asyncTest:true start:true ok:true*/
+
+ var cities = {
+ "Berlin": {latitude: 52.518611, longitude: 13.408056},
+ "Boston": {latitude: 42.357778, longitude: "71° 3' 34\" W"},
+ "Dortmund": {latitude: "51° 31' 10.11\" N", longitude: "7° 28' 01\" E"},
+ "London": {latitude: "51° 31' N", longitude: "0° 7' W"},
+ "Manchester": {latitude: "53° 29' N", longitude: "2° 14' W"},
+ "New York City": {latitude: 40.715517, longitude: -73.9991},
+ "San Francisco": {latitude: 37.774514, longitude: -122.418079},
+ "Moscow": {latitude: 55.751667, longitude: 37.617778}
+ };
+
+ var polygon = [{"latitude": 51.513357512, "longitude": 7.45574331},
+ {"latitude": 51.515400598, "longitude": 7.45518541},
+ {"latitude": 51.516241842, "longitude": 7.456494328},
+ {"latitude": 51.516722545, "longitude": 7.459863183},
+ {"latitude": 51.517443592, "longitude": 7.463232037},
+ {"latitude": 51.5177507, "longitude": 7.464755532},
+ {"latitude": 51.517657233, "longitude": 7.466622349},
+ {"latitude": 51.51722995, "longitude": 7.468317505},
+ {"latitude": 51.516816015, "longitude": 7.47011995},
+ {"latitude": 51.516308606, "longitude": 7.471793648},
+ {"latitude": 51.515974782, "longitude": 7.472437378},
+ {"latitude": 51.515413951, "longitude": 7.472845074},
+ {"latitude": 51.514559338, "longitude": 7.472909447},
+ {"latitude": 51.512195717, "longitude": 7.472651955},
+ {"latitude": 51.511127373, "longitude": 7.47140741},
+ {"latitude": 51.51029939, "longitude": 7.469948288},
+ {"latitude": 51.509831973, "longitude": 7.468446251},
+ {"latitude": 51.509978876, "longitude": 7.462481019},
+ {"latitude": 51.510913701, "longitude": 7.460678574},
+ {"latitude": 51.511594777, "longitude": 7.459434029},
+ {"latitude": 51.512396029, "longitude": 7.457695958},
+ {"latitude": 51.513317451, "longitude": 7.45574331}
+ ];
+
+ var polygon2 = [
+ {"latitude": 51.513357512, "longitude": 7.45574331, "elevation":523.92},
+ {"latitude": 51.515400598, "longitude": 7.45518541, "elevation":524.54},
+ {"latitude": 51.516241842, "longitude": 7.456494328, "elevation":523.12},
+ {"latitude": 51.516722545, "longitude": 7.459863183, "elevation":522.77},
+ {"latitude": 51.517443592, "longitude": 7.463232037, "elevation":521.12}
+ ];
+
+ test("Testing distance calculation: getDistance()", function() {
+
+ expect(3);
+
+ var distance1 = geolib.getDistance({latitude: 52.518611, longitude: 13.408056}, {latitude: 51.519475, longitude: 7.46694444});
+ var distance2 = geolib.getDistance({latitude: 52.518611, longitude: 13.408056}, {latitude: 51.519475, longitude: 7.46694444}, 100);
+ var distance3 = geolib.getDistance({latitude: 37.774514, longitude: -122.418079}, {latitude: 51.519475, longitude: 7.46694444});
+
+ equal(distance1, 422592, "Distance 1 should be 422592" );
+ equal(distance2, 422600, "Distance 2 should be 422600" );
+ equal(distance3, 8980260, "Distance 3 should be 8980260" );
+
+ });
+
+ test("Testing distance calculation: getDistanceSimple()", function() {
+
+ expect(3);
+
+ var distance1 = geolib.getDistanceSimple({latitude: 52.518611, longitude: 13.408056}, {latitude: 51.519475, longitude: 7.46694444});
+ var distance2 = geolib.getDistanceSimple({latitude: 52.518611, longitude: 13.408056}, {latitude: 51.519475, longitude: 7.46694444}, 100);
+ var distance3 = geolib.getDistanceSimple({latitude: 37.774514, longitude: -122.418079}, {latitude: 51.519475, longitude: 7.46694444});
+
+ equal(distance1, 421786, "Distance 1 should be 421786" );
+ equal(distance2, 421800, "Distance 2 should be 421800" );
+ equal(distance3, 8967172, "Distance 3 should be 8967172" );
+
+ });
+
+ test("Testing bounding box: getBounds()", function() {
+ expect(12);
+
+ var box = geolib.getBounds(polygon);
+
+ equal(box.maxLat, 51.5177507, "maxLat should be 51.5177507");
+ equal(box.minLat, 51.509831973, "minLat should be 51.509831973");
+ equal(box.maxLng, 7.472909447, "maxLng should be 7.472909447");
+ equal(box.minLng, 7.45518541, "minLng should be 7.45518541");
+ equal(typeof box.minElev, "undefined", "minElev should be undefind");
+ equal(typeof box.maxElev, "undefined", "maxElev should be undefind");
+
+ box = geolib.getBounds(polygon2);
+
+ equal(box.maxLat, 51.517443592, "maxLat should be 51.517443592");
+ equal(box.minLat, 51.513357512, "minLat should be 51.513357512");
+ equal(box.maxLng, 7.463232037, "maxLng should be 7.463232037");
+ equal(box.minLng, 7.45518541, "minLng should be 7.45518541");
+ equal(box.maxElev, 524.54, "maxElev should be 524.54");
+ equal(box.minElev, 521.12, "minElev should be 521.12");
+ });
+
+ asyncTest("Testing elevation: getElevation()", function() {
+ expect(4);
+
+ var latsLngsElevs;
+ var coords1 = [{"lat":33.76346,"lng":-84.43430000000001},
+ {"lat":33.76418,"lng":-84.42999999999995}];
+ var coords2 = [{"lat":41.73549,"lng":-111.85842000000002},
+ {"lat":41.73600999999999,"lng":-111.85572000000002}];
+
+ var doneCount = 0;
+ var done = function (){
+ ++doneCount;
+ if (doneCount === 2) {
+ start();
+ }
+ };
+
+ geolib.getElevation(coords1,function(err, results){
+ if (err) {
+ throw err;
+ }
+ latsLngsElevs = results;
+ equal(latsLngsElevs[0].elev, 297.8508605957031, "1st elev should be 297.8508605957031");
+ equal(latsLngsElevs[1].elev, 281.1884155273438, "2nd elev should be 281.1884155273438");
+ done();
+ });
+
+ geolib.getElevation(coords2,function(err, results){
+ if (err) {
+ throw err;
+ }
+ latsLngsElevs = results;
+ equal(latsLngsElevs[0].elev, 1358.223999023438, "1st elev should be 1358.223999023438");
+ equal(latsLngsElevs[1].elev, 1360.70654296875, "2nd elev should be 1360.70654296875");
+ done();
+ });
+
+ });
+
+ test("Testing grade: getGrade()", function() {
+ expect(2);
+ var coords1 = [{"lat":41.72977,"lng":-111.77621999999997,"elev":1702.72412109375},
+ {"lat":41.73198,"lng":-111.77636999999999,"elev":1849.7333984375}];
+ var coords2 = [{"lat":40.75402,"lng":-111.75475,"elev":2209.137451171875},
+ {"lat":40.76481,"lng":-111.76778999999999,"elev":1660.49609375}];
+
+ var grade = geolib.getGrade(coords1);
+ equal(grade, 51, "grade should be 51");
+
+ grade = geolib.getGrade(coords2);
+ equal(grade, 31, "grade should be 31");
+ });
+
+ test("Testing elevation gain and loss: getTotalElevationGainAndLoss()", function() {
+
+ expect(4);
+ var coords1 = [{"lat":41.72975,"lng":-111.77580999999998,"elev":1707.123046875},
+ {"lat":41.73298475750587,"lng":-111.77603699785413,"elev":1922.056396484375},
+ {"lat":41.73517,"lng":-111.77881000000002,"elev":1893.9931640625}];
+ var coords2 = [{"lat":40.79162,"lng":-111.76560999999998,"elev":2211.202880859375},
+ {"lat":40.79938945887229,"lng":-111.76680525603354,"elev":1995.89990234375},
+ {"lat":40.80354,"lng":-111.77384999999998,"elev":1978.573120117188}];
+
+ var gainAndLoss = geolib.getTotalElevationGainAndLoss(coords1);
+ equal(gainAndLoss.gain, 214.933349609375, "gain should be 214.933349609375");
+ equal(gainAndLoss.loss, 28.063232421875, "loss should be 28.063232421875");
+
+ gainAndLoss = geolib.getTotalElevationGainAndLoss(coords2);
+ equal(gainAndLoss.gain, 0, "gain should be 0");
+ equal(gainAndLoss.loss, 232.62976074218705, "loss should be 232.62976074218705");
+
+ });
+
+ test("Testing conversion: sexagesimal2decimal()", function() {
+
+ expect(7);
+
+ var dec1 = geolib.useDecimal("51° 31' 10.11\" N");
+ var dec2 = geolib.useDecimal("7° 28' 01\" E");
+ var dec3 = geolib.useDecimal("19° 22' 32\" S");
+ var dec4 = geolib.useDecimal("71° 3' 34\" W");
+ var dec5 = geolib.useDecimal("71°3'W");
+ var dec6 = geolib.useDecimal("51.519475");
+ var dec7 = geolib.useDecimal("-122.418079");
+
+ equal(dec1, 51.519475, "Decimal value should be 51.519475" );
+ equal(dec2, 7.46694444, "Decimal value should be 7.46694444" );
+ equal(dec3, -19.37555556, "Decimal value should be -19.37555556" );
+ equal(dec4, -71.05944444, "Decimal value should be -71.05944444" );
+ equal(dec5, -71.05, "Decimal value should be -71.05" );
+ equal(dec6, 51.519475, "Decimal value should be 51.519475" );
+ equal(dec7, -122.418079, "Decimal value should be -122.418079" );
+
+ });
+
+ test("Testing conversion: decimal2sexagesimal()", function() {
+
+ expect(2);
+ var sexa1 = geolib.decimal2sexagesimal(51.519475);
+ var sexa2 = geolib.decimal2sexagesimal(-19.37555556);
+
+ equal(sexa1, '51° 31\' 10.11"', "Decimal value should be 51° 31' 10.11\"" );
+ equal(sexa2, '19° 22\' 32.00"', "Decimal value should be 19° 22' 32\" S" );
+
+ });
+
+ test("Testing: getCompassDirection()", function() {
+
+ expect(2);
+ var dir1 = geolib.getCompassDirection({latitude: 52.518611, longitude: 13.408056}, {latitude: 51.519475, longitude: 7.46694444});
+
+ equal(dir1.rough, 'W', 'Should be west');
+ equal(dir1.exact, 'WSW', 'Should be west-south-west');
+
+ });
+
+
+ test("Testing: findNearest()", function() {
+
+ expect(4);
+ var near1 = geolib.findNearest({latitude: 36.1168, longitude: -115.173798}, cities);
+
+ equal(near1.key, 'San Francisco', 'Nearest city to Las Vegas from predefined set should be San Francisco');
+ equal(near1.distance, 670788, 'Distance should be 670788');
+ equal(near1.latitude, 37.774514, 'Latitude should be 37.774514');
+ equal(near1.longitude, -122.418079, 'Latitude should be -122.418079');
+
+ });
+
+ test("Testing: getPathLength()", function() {
+
+ var pathLength = geolib.getPathLength(polygon);
+ equal(pathLength, 3377, 'Path length should be 3377');
+
+ });
+
+ test("Testing: isPointInside()", function() {
+
+ var isInside1 = geolib.isPointInside({latitude: 51.514252208, longitude: 7.464905736}, polygon); // Point is inside of the polygon
+ var isInside2 = geolib.isPointInside({latitude: 51.510539773, longitude: 7.454691884}, polygon); // Point is not inside polygon
+
+ ok(isInside1, "Point 1 is inside polygon");
+ ok(!isInside2, "Point 2 is not inside polygon");
+
+ });
+
+ test("Testing: convertUnit()", function() {
+
+ equal(geolib.convertUnit('km', 1000), 1, 'Conversion of 1000 m to km');
+ equal(geolib.convertUnit('m', 1000), 1000, 'Conversion of 1000 m to m (just to make sure)');
+ equal(geolib.convertUnit('cm', 1000), 100000, 'Conversion of 1000 m to cm');
+ equal(geolib.convertUnit('mm', 1000), 1000000, 'Conversion of 1000 m to mm');
+ equal(geolib.convertUnit('mi', 1000), 0.6214, 'Conversion of 1000 m to miles');
+ equal(geolib.convertUnit('sm', 1000), 0.5399, 'Conversion of 1000 m to seamiles');
+ equal(geolib.convertUnit('ft', 1000), 3280.8399, 'Conversion of 1000 m to ft');
+ equal(geolib.convertUnit('in', 1000), 39370.0787, 'Conversion of 1000 m to in');
+ equal(geolib.convertUnit('yd', 1000), 1093.6133, 'Conversion of 1000 m to yd');
+
+ });
+
+ test("Testing: isSexagesimal()", function() {
+
+ ok(geolib.isSexagesimal('51° 31\''), '51° 31\'');
+ ok(geolib.isSexagesimal('51° 31\' 12"'), '51° 31\' 12"');
+ ok(geolib.isSexagesimal('51° 31\' 12.27"'), '51° 31\' 12.27"');
+ ok(geolib.isSexagesimal('51° 31\' 12.27" N'), '51° 31\' 12.27" N');
+ ok(geolib.isSexagesimal('51° 31\' N'), '51° 31\' N');
+ //ok(geolib.isSexagesimal('51° N'), '51°'); // coming soon
+
+ });
View
5 tests/getElevationServer.js
@@ -1,6 +1,5 @@
-var util = require('util')
- , http = require('http')
- , geolib = require('../geolib');
+/*global require:true describe:true it:true*/
+var util = require('util'), http = require('http'), geolib = require('../geolib');
describe('Geolib', function() {
describe('getElevationServer', function() {
Please sign in to comment.
Something went wrong with that request. Please try again.