Regex/Javascript to transform Degrees Decimal Minutes to Decimal Degrees
I found a function in the GeoServer source that will allow me to convert Degrees Minutes Seconds to Decimal Degrees in Javascript. But i need to conver Degrees Decimal Minutes to Decimal Degrees.
Current function will do this:
input: N 03° 01’ 37”
output: 30.016666666666666
But i need a function that will do this:
input: 26° 23.90473
output: ????
The best answer would be to tweak the existing RegEx but any Javascript solution that converts it will do.
Here's the current function: But i need it to accept Degrees Decimal Minutes instead of Degrees Minutes Seconds.
dmsToDeg: function(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]?(\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.开发者_JAVA技巧0) + (r/3600.0))*neg;
return dec;
},
New function...
dmsToDeg: function(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?)$/,'');
var parts=dms.match(/(\d{1,3})[.,°d ]?\s*(\d{0,2}(?:\.\d+)?)[']?/);
if (parts==null) {
return Number.NaN;
}
// parts:
// 0 : degree
// 1 : degree
// 2 : minutes
var d= (parts[1]? parts[1] : '0.0')*1.0;
var m= (parts[2]? parts[2] : '0.0')*1.0;
var dec= (d + (m/60.0))*neg;
return dec;
}
I have removed the last part of the regex which captures seconds and fractions of seconds. I have added to the part which captures minutes (?:\.\d+)?
This is a non capturing group (?:
) - as we don't need it to be captured separate to the integer part of the minutes. It requires a decimal point (\.
) and then one or more digits (\d+
). The whole group is optional (?
) - ie the input can just be integer still.
Edit: Based on your comments I modified it to be a little more white-space-agnostic... It now looks for an integer followed by a space or one of these chars: ".,°d" and that followed by decimal minutes. Solution also posted to your jsfiddle: http://jsfiddle.net/NJDp4/6/
精彩评论