2016-07-24 113 views
6

我想緯度40.7127837,東經-74.0059413 轉換,並按照以下格式的Android如何轉換經緯度成度格式

ñ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); 

回答

9

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" 
+0

謝謝,它的作品很棒。 – Julia

2

如果你面臨着內置的方法的問題,你總是可以創建自己的方法:

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) ; 
    } 
} 
+0

爲什麼你用'try ... catch'包圍了實現?它不能通過零或類似的東西來到一個設備,所以我認爲catch塊永遠不會被執行。 – Cilenco