Android Write Gps Coordinate Into Image Exif Data

December 28, 2018
fun convertGpsToDMS(latOrLon: Double): String {
    val degMinSec = Location.convert(latOrLon, Location.FORMAT_SECONDS).split(":")

    val degrees = degMinSec[0].toInt().absoluteValue
    val seconds = (degMinSec[2].toDouble() * 10000).roundToInt()
    return "$degrees/1,${degMinSec[1]}/1,$seconds/10000"
}

fun saveGpsExif(mediaFilePath: String, lat: Double, lon: Double) {
    val exif = ExifInterface(mediaFilePath)

    exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, convertGpsToDMS(lat))
    exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, if (lat < 0) "S" else "N")
    exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, convertGpsToDMS(lon))
    exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, if (lon < 0) "W" else "E")

    exif.saveAttributes()
}

If the value for TAG_GPS_LATITUDE or TAG_GPS_LONGITUDE provided is incorrect, there is not error shown or exception raised, just a warning:

ExifInterface: Given tag (GPSLatitude) value didn’t match with one of expected formats: URATIONAL (guess: STRING)

Example of conversion:

46.3322297995342, -63.02775911986828 = 46/1,19/1,560273/10000 N, 63/1,1/1,399328/10000 W

Use Convert Lat and Long to DMS to check for correctness of conversion.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.