Convert Degrees/Minutes/Seconds to Decimal Coordinates

Viewed 49993

In one part of my code I convert from decimal coordinates to degrees/minutes/seconds and I use this:

double coord = 59.345235;
int sec = (int)Math.Round(coord * 3600);
int deg = sec / 3600;
sec = Math.Abs(sec % 3600);
int min = sec / 60;
sec %= 60;

How would I convert back from degrees/minutes/seconds to decimal coordinates?

7 Answers

CoordinateSharp is available as a Nuget package and can handle Coordinate conversions for you. It even does UTM/MGRS conversion and provides solar/lunar times relative to the input location. It's really easy to use!

Coordinate c = new Coordinate(40.465, -75.089);

//Display DMS Format
c.FormatOptions.Format = CoordinateFormatType.Degree_Minutes_Seconds;
c.ToString();//N 40º 27' 54" W 75º 5' 20.4"
c.Latitude.ToString();//N 40º 27' 54"
c.Latitude.ToDouble();//40.465

Coordinate properties are iObservable as as well. So if you change a latitude minute value for example, everything else will update.

For those who prefer regular expression and to handle format like DDMMSS.dddS This function could easily be updated to handle other format.

C#

Regex reg = new Regex(@"^((?<D>\d{1,2}(\.\d+)?)(?<W>[SN])|(?<D>\d{2})(?<M>\d{2}(\.\d+)?)(?<W>[SN])|(?<D>\d{2})(?<M>\d{2})(?<S>\d{2}(\.\d+)?)(?<W>[SN])|(?<D>\d{1,3}(\.\d+)?)(?<W>[WE])|(?<D>\d{3})(?<M>\d{2}(\.\d+)?)(?<W>[WE])|(?<D>\d{3})(?<M>\d{2})(?<S>\d{2}(\.\d+)?)(?<W>[WE]))$");

private double DMS2Decimal(string dms)
            {
                double result = double.NaN;            

                var match = reg.Match(dms);

                if (match.Success)
                {
                    var degrees = double.Parse("0" + match.Groups["D"]);
                    var minutes = double.Parse("0" + match.Groups["M"]);
                    var seconds = double.Parse("0" + match.Groups["S"]);
                    var direction = match.Groups["W"].ToString();
                    var dec = (Math.Abs(degrees) + minutes / 60d + seconds / 3600d) * (direction == "S" || direction == "W" ? -1 : 1);
                    var absDec = Math.Abs(dec);

                    if ((((direction == "W" || direction == "E") && degrees <= 180 & absDec <= 180) || (degrees <= 90 && absDec <= 90)) && minutes < 60 && seconds < 60)
                    {
                        result = dec;
                    }

                }

                return result;

            }
Related