目次

PHPでGPS等で写真に付与された緯度経度を取り出す - ExifLatLng.php

GPS機能付きカメラで写真をとったりすると写真の画像ファイルのExifに緯度経度情報を入れることができる。(iPhoneでもできた気がする。)

このExifの緯度経度、度分秒になってたり分数だったりして取り出すのが意外に面倒。後で使いまわせるようにクラスにしてみた。

ライセンス

MITライセンスで。

ソースコード

<?php
/**
 *  ExifLatLng
 *  @see       http://0-oo.net/sbox/php-tool-box/exif-lat-lng
 *  @version   0.1.0
 *  @copyright 2010 dgbadmin@gmail.com
 *  @license   http://0-oo.net/pryn/MIT_license.txt (The MIT license)
 *
 *  Also see
 *  @see http://php.net/exif_read_data
 */
class ExifLatLng {
    public $data = null;
 
    public function __construct($filePath) {
        if (!is_file($filePath)) {
            throw new Exception('ファイルがありません');
        }
 
        $this->data = exif_read_data($filePath);
    }
 
    public function getLat() {
        $lat = $this->_getValue('緯度', 'GPSLatitude');
 
        if ($this->data['GPSLatitudeRef'] != 'N') {    //南緯の場合
            $lat *= -1;
        }
 
        return $lat;
    }
 
    public function getLng() {
        $lng = $this->_getValue('経度', 'GPSLongitude');
 
        if ($this->data['GPSLongitudeRef'] != 'E') {    //西経の場合
            $lng *= -1;
        }
 
        return $lng;
    }
 
    private function _getValue($name, $key) {
        $exif = $this->data;
 
        if (!$exif) {
            throw new Exception('Exifを取得できませんでした');
        } else if (!isset($exif[$key]) || !isset($exif[$key . 'Ref'])){
            throw new Exception($name . 'を取得できませんでした');
        }
 
        $arr = $exif[$key];
 
        $value = 0;
        for ($i = 0; $i < count($arr); $i++) {
            $str = $arr[$i];
 
            if (!preg_match('@^[0-9]+/[0-9]+$@', $str)) {
                throw new Exception($name . 'の値(' . $str . ')が対応外です');
            }
 
            list($num, $den) = explode('/', $str);
            $value += $num / $den / pow(60, $i);
        }
 
        return $value;
    }
}