I’m having trouble converting DMS to DD in javascript using regular expressions. I took this code from geoserver but it does not seem to work. I want it to be able to convert all my test cases with the correct or VERY close answer.
I really don’t care if the function is completely javascript or heavy regular expressions, i just need it to work.
You can test it on JSFIDDLE
http://jsfiddle.net/NJDp4/13/
Here are my test cases:
dmsToDeg(‘ N 03 01’ 37”’);
dmsToDeg(’03 01 37′);
dmsToDeg(’03 01’ 37” N’);
dmsToDeg(‘076 40’ 35” W’);
dmsToDeg(‘W 076 40’ 35”’);
dmsToDeg(‘N 05 11’ 17”’);
Here is my code:
function dmsToDeg (dms) {
if (!dms) {
return Number.NaN;
}
var neg = dms.match(/(^\s?-)|(\s?[SW]\s?$)/) != null ? -1.0 : 1.0;
dms = dms.replace(/(^\s?-)|(\s?[NSEW]\s?)$/, '');
dms = dms.replace(/\s/g, '');
var parts = dms.match(/(\d{1,3})[.,°d ]?\s*(\d{0,2})[']?(\d{0,2})[.,]?(\d{0,})(?:["]|[']{2})?/);
if (parts == null) {
return Number.NaN;
}
// parts:
// 0 : degree
// 1 : degree
// 2 : minutes
// 3 : secondes
// 4 : fractions of seconde
var d = (parts[1] ? parts[1] : '0.0') * 1.0;
var m = (parts[2] ? parts[2] : '0.0') * 1.0;
var s = (parts[3] ? parts[3] : '0.0') * 1.0;
var r = (parts[4] ? ('0.' + parts[4]) : '0.0') * 1.0;
var dec = (d + (m / 60.0) + (s / 3600.0) + (r / 3600.0)) * neg;
return dec;
}
It’s not that tough, the following assumes that the correct format is passed in, you might want to do some validation of that. It also doesn’t format the output, use a generic formatting function if you need that (again, not hard to write, about 5 lines of code max).
Likely you are feeding this into another calculation (degrees to radians conversion?) so formatting is probably unnecessary. Note that javascript numbers can’t accurately represent all decimal numbers, so be careful with rounding. The precision is sufficient for most purposes though.