Tech Tip: Add Latitude/Longitude Information to Photos

I wanted to store geolocation information in the photos I take with my digital camera. That way I wouldn't have to specify the photo locations manually when I upload them to the Picasa webpage. Since my camera doesn't have built in GPS support, I wrote this script to add the location information to the pictures when they are on the computer already.

The script can be used together with Dave Taylor's whereis.sh script, described in this artcle. Dave's script takes an address and returns the latitude/longitude values using the Yahoo Maps service. My script - I call it jpgloc.sh - can be piped the output from whereis.sh, for example:

sh whereis.sh 2001 Blake Street, Denver, CO | ./jpgloc.sh

# OR

sh whereis.sh 2001 Blake Street, Denver, CO | sh jpgloc.sh

It takes the two values from the standard input. Converts them to Degrees/Minutes format and also figures out whether it is a North/South latitude and East/West longitude. After that it loops through the JPEGg images in the current directory and sets the GPS Latitude/Longitude values to the provided location. It uses the exiv2 utility for the last step. This program should be available for recent distributions through the package management system. For example on Ubuntu Linux it can be installed with this command:

sudo apt-get install exiv2

If the Latitude/Longitude data is available in some other format, the script can be easily modified/extended to take the same information from command-line arguments. The source for the script follows:

#!/bin/sh

# Grabs latitude and longitude values from stdin and stores
# them in all JPGs in current directory.
# The two values have to be separated by a comma.
#

IFS=","
read lat long

# If sign is negative, we have to change reference
latRef="N";
latSign=$(echo $lat | cut -c 1)
if [ "X$latSign" = "X-" ]
then  # Delete minus from beginning
  lat=$(echo $lat | sed s/^-//)
  latRef="S"
fi
lonRef="E";
lonSign=$(echo $long | cut -c 1)
if [ "X$lonSign" = "X-" ]
then
  long=$(echo $long | sed s/^-//)
  lonRef="W"
fi

# Calculate latitude/longitude degrees and minutes
latDeg=$( echo "scale=0; $lat/1" | bc )
latMin=$( echo "scale=2; m=($lat-$latDeg) *100/ 0.016666;scale=0;m/1" | bc ) 
lonDeg=$( echo "scale=0; $long/1" | bc )
lonMin=$( echo "scale=2; m=($long-$lonDeg)*100/0.016666;scale=0;m/1" | bc )

echo Picture location will be: $latDeg $latMin\' $latRef , $lonDeg $lonMin\' $lonRef

for fil in *.jpg  # Also try *.JPG
do
  echo Updating $fil ....
  exiv2 -M"set Exif.GPSInfo.GPSLatitude $latDeg/1 $latMin/100 0/1" \
		-M"set Exif.GPSInfo.GPSLatitudeRef $latRef" \
          -M"set Exif.GPSInfo.GPSLongitude $lonDeg/1 $lonMin/100 0/1" \
		-M"set Exif.GPSInfo.GPSLongitudeRef $lonRef" \
         $fil
done
Load Disqus comments