LoginSignup
16
19

More than 5 years have passed since last update.

PHPでGoogleにジオコーディングをリクエストして緯度経度を取得する

Last updated at Posted at 2015-06-03

常にリクエストもとはプログラムを配置しているサーバーからとなるため、リクエスト数が閾値を超えてしまうと当然エラーになる。
一度取得したら、DBに書き込んでおくなどの工夫は必要です。

class GoogleGeocoding
{

    public static function getLatLng($strAddress = null)
    {
        if (!is_null($strAddress) && '' != $strAddress) {
            $strAddress = trim($strAddress);
            $strAddress = urlencode($strAddress);
            $url = "http://maps.google.com/maps/api/geocode/json?";
            $url .= "address={$strAddress}&sensor=false";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            $response = curl_exec($ch);
            curl_close($ch);
            $res = json_decode($response, true);
            if (isset($res['results'][0]['geometry']['location'])) {
                return $res['results'][0]['geometry']['location'];
            } else {
                throw new Exception('Cannot get lat and lon by geocoding.');
            }
        }
    }

}
16
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
19