Search code examples
androidcoordinate-systems

Android: LatLng object to String format


I'm using the function place.getLatLng() and i need it as "31°47′0″N 35°13′0″E", Is there a function for this?


Solution

  • You can use Location Api and formatting:

    Get latitude and longitude from LatLang object then pass in following method-

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

    }