How to format GPS latitude and longitude?

后端 未结 7 898
囚心锁ツ
囚心锁ツ 2021-01-04 07:48

In android(java) when you get the current latitude and longitude using the function getlatitude() etc you get the coordinates in decimal format:

latit

7条回答
  •  太阳男子
    2021-01-04 08:30

    As already mentioned, there are some string manipulations required. I created the following helper class, which converts the location to DMS format and allows to specify the decimal places for the seconds:

    import android.location.Location;
    import android.support.annotation.NonNull;
    
    public class LocationConverter {
    
        public static String getLatitudeAsDMS(Location location, int decimalPlace){
            String strLatitude = Location.convert(location.getLatitude(), Location.FORMAT_SECONDS);
            strLatitude = replaceDelimiters(strLatitude, decimalPlace);
            strLatitude = strLatitude + " N";
            return strLatitude;
        }
    
        public static String getLongitudeAsDMS(Location location, int decimalPlace){
            String strLongitude = Location.convert(location.getLongitude(), Location.FORMAT_SECONDS);
            strLongitude = replaceDelimiters(strLongitude, decimalPlace);
            strLongitude = strLongitude + " W";
            return strLongitude;
        }
    
        @NonNull
        private static 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;
        }
    }
    

提交回复
热议问题