Decoding GPS latitude and longitude from EXIF in Ruby
Most camera phones have GPS sensors built in. So do new cameras. What's this mean? Well, every picture taken with one of these devices has the latitude and longitude of the location that the picture was taken at. But how to get this out? And what's this funky format that the numbers are coming out as? What's Rational?
The short answers: use a gem; sexagesimal (yes it is a real word); a way of representing numbers in Ruby.
The long answers:
You'll need to install a gem to read EXIF data from the image:
gem install exifr
Here's the code:
require 'exifr'
a = EXIFR::JPEG.new(photo_path)
lat = a.exif[0].gps_latitude[0].to_f + (a.exif[0].gps_latitude[1].to_f / 60) + (a.exif[0].gps_latitude[2].to_f / 3600)
long = a.exif[0].gps_longitude[0].to_f + (a.exif[0].gps_longitude[1].to_f / 60) + (a.exif[0].gps_longitude[2].to_f / 3600)
long = long * -1 if a.exif[0].gps_longitude_ref == "W" # (W is -, E is +)
lat = lat * -1 if a.exif[0].gps_latitude_ref == "S" # (N is +, S is -)
The strangest part of this is probably the lines where lat and long are assigned. Basically, this is the conversion from sexagesimal into decimal. Otherwise, you're getting 3 Rational numbers out of Ruby, and these are the
- hours
- minutes
- seconds
that you might sometimes hear coordinates talked about. The conversion will put it into a format that's easily read by something like Google Maps.
To convert from sexagesimal to decimal, you'll use a simple formula for converting sexagesimal into decimal. If you want to check your results, you can use a Google Map that shows lat-long info.
Tight!