GCPのGeocoding APIをPHP(Guzzle)を使って呼び出してみます。
APIキーを用意する
https://console.cloud.google.com/apis/library/geocoding-backend.googleapis.com
課金アカウント設定済みのGCPプロジェクトでGeocoding APIを有効化し、APIキーを発行します。
PHPからAPIを呼び出す
Guzzleをインストール
HTTPクライアントのGuzzleをインストールします。
composer require guzzlehttp/guzzle
APIを呼び出す
$api_key
には発行したAPIキーの文字列を設定します。
geocode.php
<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; $http_client = new Client(); $url = 'https://maps.googleapis.com/maps/api/geocode/json'; $api_key = '**********************************'; /* Geocoding (latitude/longitude lookup) 住所から緯度経度を取得 */ $address = '東京都北区赤羽'; try { $response = $http_client->request('GET', $url, [ 'headers' => [ 'Accept' => 'application/json', ], 'query' => [ 'key' => $api_key, 'language' => 'ja', 'address' => $address, ], 'verify' => false, ]); } catch (ClientException $e) { throw $e; } $body = $response->getBody(); echo $body . PHP_EOL; /* Reverse geocoding (address lookup) 緯度経度から住所を取得 */ $latitude = '35.7799638'; $longitude = '139.723053'; $latlng = $latitude . ',' . $longitude; try { $response = $http_client->request('GET', $url, [ 'headers' => [ 'Accept' => 'application/json', ], 'query' => [ 'key' => $api_key, 'language' => 'ja', 'latlng' => $latlng, ], 'verify' => false, ]); } catch (ClientException $e) { throw $e; } $body = $response->getBody(); $json = json_decode($body); echo $json->results[0]->formatted_address;
実行結果は次のようになります。
>php geocode.php { "results" : [ { "address_components" : [ { "long_name" : "赤羽", "short_name" : "赤羽", "types" : [ "political", "sublocality", "sublocality_level_2" ] }, { "long_name" : "北区", "short_name" : "北区", "types" : [ "locality", "political" ] }, { "long_name" : "東京都", "short_name" : "東京都",