我有一组纬度和经度的双精度值(37.33168900, -122.03073100)。
我想将其转换为度数值,例如(37 19' 54 ,48 11' 52 )。
有什么好的方法吗?提前感谢您。
String strLongitude = location.convert(location.getLongitude(), location.FORMAT_SECONDS);
String strLatitude = location.convert(location.getLatitude(), location.FORMAT_SECONDS);
.
public static String getFormattedLocationInDegree(double latitude, double longitude) {
try {
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;
String latDegree = latDegrees >= 0 ? "N" : "S";
String lonDegrees = longDegrees >= 0 ? "E" : "W";
return Math.abs(latDegrees) + "°" + latMinutes + "'" + latSeconds
+ "\"" + latDegree +" "+ Math.abs(longDegrees) + "°" + longMinutes
+ "'" + longSeconds + "\"" + lonDegrees;
} catch (Exception e) {
return ""+ String.format("%8.5f", latitude) + " "
+ String.format("%8.5f", longitude) ;
}
}
应该是一些数学:
(int)37.33168 => 37
37.33168 % 1 = 0.33168
0.33168 * 60 = 19,905 => 19
19.905 % 1 = 0.905
0.905 * 60 => 54
与-122相同(如果是负值,则加上360)
编辑: 可能有一些我不知道的API。
Abi的答案在我的位置上非常好,但在其他一些位置会产生错误,例如,在西半球上出现“E”而不是“W”。在我看来,应该是这样的:
String lonDegrees = longDegrees >= 0 ? "E" : "W";
改为:
String lonDegrees = latDegrees >= 0 ? "E" : "W";
private String convertCoordinate(double coordinate, boolean isLatitude){
String[] pString = isLatitude ? new String[]{"N", "S"} : new String[]{"E", "W"};
int degree = (int) coordinate;
int minute = (int) (Math.abs(coordinate) * 60) % 60;
int second = (int) (Math.abs(coordinate) * 3600) % 60;
int index = degree < 0 ? 1 : 0;
degree = Math.abs(degree);
return degree + pString[index] + " " + minute + "' " + second + "\"";
}
示例:40°42′51″ N 74°00′21″ W
示例调用:getLocationAsDMS(location,8)
其中8是此格式的正确数字。
public String getLocationAsDMS (Location location, int decimalPlace){
String strLatitude = Location.convert(location.getLatitude(), Location.FORMAT_SECONDS);
strLatitude = replaceDelimiters(strLatitude, decimalPlace);
char latCardinal = location.getLongitude() >= 0 ? 'N' : 'S';
strLatitude = strLatitude + " " + latCardinal;
String strLongitude = Location.convert(location.getLongitude(), Location.FORMAT_SECONDS);
strLongitude = replaceDelimiters(strLongitude, decimalPlace);
char lonCardinal = location.getLongitude() >= 0 ? 'E' : 'W';
strLongitude = strLongitude + " " + lonCardinal;
return strLatitude + " " + strLongitude;
}
@NonNull
private String replaceDelimiters(String str, int decimalPlace) {
str = str.replaceFirst(":", "°");
str = str.replaceFirst(":", "'");
int pointIndex = str.indexOf(".");
int endIndex = pointIndex + 1 + decimalPlace;
if(endIndex < str.length()) {
str = str.substring(0, endIndex);
}
str = str + "\"";
return str;
}