Convert decimal coordinate into degrees, minutes, seconds, direction

前端 未结 6 1752
遥遥无期
遥遥无期 2020-12-28 21:13

I have the following so far, but can\'t figure out a tidy way to get the direction letters in without a bunch of messy if statements. Any ideas? Ideally I\'d like to extend

6条回答
  •  半阙折子戏
    2020-12-28 21:52

    Here's a solution in C#:

        void Run(double latitude, double longitude)
        {
            int latSeconds = (int)Math.Round(latitude * 3600);
            int latDegrees = latSeconds / 3600;
            latSeconds = Math.Abs(latSeconds % 3600);
            int latMinutes = latSeconds / 60;
            latSeconds %= 60;
    
            int longSeconds = (int)Math.Round(longitude * 3600);
            int longDegrees = longSeconds / 3600;
            longSeconds = Math.Abs(longSeconds % 3600);
            int longMinutes = longSeconds / 60;
            longSeconds %= 60;
    
            Console.WriteLine("{0}° {1}' {2}\" {3}, {4}° {5}' {6}\" {7}",
                Math.Abs(latDegrees),
                latMinutes,
                latSeconds,
                latDegrees >= 0 ? "N" : "S",
                Math.Abs(longDegrees),
                longMinutes,
                longSeconds,
                latDegrees >= 0 ? "E" : "W");
        }
    

    This is an example run:

    new Program().Run(-15.14131211, 56.345678);
    new Program().Run(15.14131211, -56.345678);
    new Program().Run(15.14131211, 56.345678);
    

    Which prints:

    15° 8' 29" S, 56° 20' 44" W
    15° 8' 29" N, 56° 20' 44" E
    15° 8' 29" N, 56° 20' 44" E
    

    Hope this helps, and that it does the right thing. Good luck!

提交回复
热议问题