Skip to content

Instantly share code, notes, and snippets.

@twolfson
Created November 12, 2012 05:25
Show Gist options
  • Save twolfson/4057653 to your computer and use it in GitHub Desktop.
Save twolfson/4057653 to your computer and use it in GitHub Desktop.
Latitude and longitude normalization
// ASIDE: This was built during NodeKO 2012 -- hence the window.'s lying around
// Define latLngPadder
function normalizeLat(lat) {
var latStr = lat + '';
// Guarantee a decimal place in the number
if (latStr.indexOf('.') === -1) {
latStr = latStr + '.';
}
// Pad out to 4 decimal places
latStr = latStr.replace(/(\.\d{0,3})$/, function (_, decimal) {
// Add on the missing amount of items
var decimalPlaces = decimal.length - 1,
i = 0,
len = 4 - decimalPlaces;
for (; i < len; i++) {
decimal += '0';
}
return decimal;
});
// Truncate off excess decimal places
latStr = latStr.replace(/(\.\d{4})\d*$/, function (_, decimal) {
return decimal;
});
// Return the latStr
return latStr;
}
// Define window.properLat and window.properLng
window.properLat = function (lat) {
// Fallback lat
if (lat === undefined) { lat = window.lat; }
// Convert lat to a number and determine direction
var latNum = +lat,
isNonNegative = latNum >= 0,
direction = isNonNegative ? 'N' : 'S';
// Get the absolute value and output it
var absLat = Math.abs(latNum),
normalLat = normalizeLat(absLat),
properLat = normalLat + direction;
return properLat;
};
// Define window.properLng
window.properLng = function (lng) {
// Fallback lng
if (lng === undefined) { lng = window.lng; }
// Convert lng to a number and determine direction
var latNum = +lng,
isNonNegative = latNum >= 0,
direction = isNonNegative ? 'E' : 'W';
// Get the absolute value and output it
var absLng = Math.abs(latNum),
normalLng = normalizeLat(absLng),
properLng = normalLng + direction;
return properLng;
};
// Normalize lat and lng to 4 decimal places with direction
normalizeLat(100.000000002); // Normalizes -> 100.0000N
normalizeLng(100); // Normalizes -> 100.0000E
normalizeLat(-90.0001); // Normalizes -> 90.0001S
normalizeLng(-20.20); // Normalizes -> 20.2000W
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment