Regex/Javascript to transform Degrees Decimal Minutes to Decimal Degrees

前端 未结 1 1415
情话喂你
情话喂你 2020-12-20 02:56

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 Decim

相关标签:
1条回答
  • 2020-12-20 03:38

    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/

    0 讨论(0)
提交回复
热议问题