Created
June 14, 2021 14:38
-
-
Save wberdowski/20ebd54f304f96ad204ea0c8dcf1404a to your computer and use it in GitHub Desktop.
Convert latitude and longitude to DMS (degrees minutes seconds) format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class LatLon2Dms | |
{ | |
public static string Convert(double lat, double lon) | |
{ | |
return ConvertSingle(lat, true) + ", " + ConvertSingle(lon, false); | |
} | |
private static string ConvertSingle(double value, bool isLat) | |
{ | |
double v = Math.Abs(value); | |
int deg = (int)Math.Floor(v); | |
int min = (int)Math.Floor((v - deg) * 60); | |
int sec = (int)Math.Floor(3600 * (v - deg) - 60 * min); | |
return $"{deg}° {min}' {sec}\" {GetSuffix(value, isLat)}"; | |
} | |
private static char GetSuffix(double value, bool isLat) | |
{ | |
bool isNegative = (Math.Sign(value) == -1); | |
if (isLat) | |
{ | |
if (isNegative) | |
{ | |
return 'S'; | |
} else | |
{ | |
return 'N'; | |
} | |
} else | |
{ | |
if (isNegative) | |
{ | |
return 'W'; | |
} else | |
{ | |
return 'E'; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment