我想要转换纬度40.7127837,经度-74.0059413 并采用以下格式
N 40°42'46.0218“ W 74°0'21.3876“
最好的方法是什么?
我尝试过像location.FORMAT_DEGREES,location.FORMAT_MINUTES和location.FORMAT_SECONDS这样的方法,但我不知道如何将它们转换为正确的格式。感谢。
strLongitude = location.convert(location.getLongitude(), location.FORMAT_DEGREES);
strLatitude = location.convert(location.getLatitude(), location.FORMAT_DEGREES);
答案 0 :(得分:13)
您使用的Location.convert()
方法提供了非常好的结果,并且已经很好地实施和测试。您只需格式化输出以满足您的需求:
private String convert(double latitude, double longitude) {
StringBuilder builder = new StringBuilder();
if (latitude < 0) {
builder.append("S ");
} else {
builder.append("N ");
}
String latitudeDegrees = Location.convert(Math.abs(latitude), Location.FORMAT_SECONDS);
String[] latitudeSplit = latitudeDegrees.split(":");
builder.append(latitudeSplit[0]);
builder.append("°");
builder.append(latitudeSplit[1]);
builder.append("'");
builder.append(latitudeSplit[2]);
builder.append("\"");
builder.append(" ");
if (longitude < 0) {
builder.append("W ");
} else {
builder.append("E ");
}
String longitudeDegrees = Location.convert(Math.abs(longitude), Location.FORMAT_SECONDS);
String[] longitudeSplit = longitudeDegrees.split(":");
builder.append(longitudeSplit[0]);
builder.append("°");
builder.append(longitudeSplit[1]);
builder.append("'");
builder.append(longitudeSplit[2]);
builder.append("\"");
return builder.toString();
}
使用输入坐标调用此方法时:
String locationString = convert(40.7127837, -74.0059413);
您将收到此输出:
N 40°42'46.02132" W 74°0'21.38868"
答案 1 :(得分:5)
如果您遇到内置方法的问题,您可以随时创建自己的方法:
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) ;
}
}