Android 如何将纬度和经度转换为度格式

10

我想将纬度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);
2个回答

19

您正在使用的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"

Location.convert(Math.abs(latitude), Location.FORMAT_SECONDS) - 这个方法在默认语言环境下存在问题。 - ajaas azeez

7
如果您在使用内置方法时遇到问题,您总是可以创建自己的方法:
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) ;
    }
}

为什么你在实现代码周围加上了 try...catch 呢?它不可能因为除以零或类似的原因而导致设备出错,所以我认为 catch 块永远不会被执行。 - Cilenco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接