Last active
August 29, 2015 14:11
-
-
Save pospi/612b9bb496ab4913b05f to your computer and use it in GitHub Desktop.
Parse common lat/lng formats
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var parseLatLng = (function() | |
{ | |
var matchLocDecimal = /^\s*(-?\d+)(\.\d+)?\s*°?\s*(N|S)?(,|\s)+(-?\d+)(\.\d+)?\s*°?\s*(E|W)?\s*$/; | |
var matchLocDegrees = /^\s*(-?\d+)°?\s*((\d+)(\.\d+)?'?)?\s*(N|S)?(,|\s)+(-?\d+)°?\s*((\d+)(\.\d+)?'?)?\s*(E|W)?\s*$/; | |
var matchLocCompass = /^\s*(-?\d+)°?\s*((\d+)('|\s)+)?\s*((\d+)(\.\d+)?(''|")?)?\s*(N|S)?(,|\s)+(-?\d+)°?\s*((\d+)('|\s)+)?\s*((\d+)(\.\d+)?(''|")?)?\s*(E|W)?\s*$/; | |
return function(val) | |
{ | |
var matches, | |
lat, lng, | |
flipLat = false, flipLng = false; | |
if (matches = val.match(matchLocDecimal)) { | |
lat = parseInt(matches[1] || 0) + parseFloat(matches[2] || 0); | |
lng = parseInt(matches[5] || 0) + parseFloat(matches[6] || 0); | |
flipLat = matches[3] === 'S'; | |
flipLng = matches[7] === 'W'; | |
} else if (matches = val.match(matchLocDegrees)) { | |
lat = parseInt(matches[1] || 0) + (parseInt(matches[3] || 0) / 60) + (parseFloat(matches[4] || 0) / 3600); | |
lng = parseInt(matches[7] || 0) + (parseInt(matches[9] || 0) / 60) + (parseFloat(matches[10] || 0) / 3600); | |
flipLat = matches[5] === 'S'; | |
flipLng = matches[11] === 'W'; | |
} else if (matches = val.match(matchLocCompass)) { | |
lat = parseInt(matches[1] || 0) + (parseInt(matches[3] || 0) / 60) + (parseFloat(matches[5] || 0) / 3600); | |
lng = parseInt(matches[11] || 0) + (parseInt(matches[13] || 0) / 60) + (parseFloat(matches[15] || 0) / 3600); | |
flipLat = matches[9] === 'S'; | |
flipLng = matches[19] === 'W'; | |
} else { | |
return null; | |
} | |
if (flipLat) { | |
lat *= -1; | |
} | |
if (flipLng) { | |
lng *= -1; | |
} | |
return [lat, lng]; | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment