LoginSignup
15
12

More than 5 years have passed since last update.

[Google API] 無料版だとgeocodeが取得できないので修正した

Last updated at Posted at 2018-09-28
/**
 * 住所からgooglemapデータを取得する
 * */
function get_google_map_data_by_address(address){
    var api_url = "https://maps.googleapis.com/maps/api/geocode/json?address="+address+"&language=ja&sensor=false";
    var result;
    var json = $.ajax({
        type: 'GET',
        url: api_url,
        async: false,
    }).responseText;
    result = JSON.parse(json).results[0];
    return result;
}

最初は順調に動いていたのに突然取得できなくなったorz

{
   "error_message" : "Keyless access to Google Maps Platform is deprecated. Please use an API key with all your API calls to avoid service interruption. For further details please refer to http://g.co/dev/maps-no-account",
   "results" : [],
   "status" : "OVER_QUERY_LIMIT"
}

無課金は5件/日しか取得できない模様(少なっ!!

じゃあ、キーを付けてみよう

    var api_url = "https://maps.googleapis.com/maps/api/geocode/json?address="+address+"&language=ja&sensor=false&key=[API_KEY]";
API keys with referer restrictions cannot be used with this API

リファラ制限付きのAPIキーはこのAPIでは使用できません

仕方ないのでHTTPリファラ制限のないAPIキーを新規作成しよう。

とりあえず開発環境のIPだけを通して実行。

{
   "error_message" : "This IP, site or mobile application is not authorized to use this API key. Request received from IP address [知らないIPアドレス], with referer: [リファラ]",
   "results" : [],
   "status" : "REQUEST_DENIED"
}

知らないIPアドレスは会社のIPアドレスだった。
javascriptで実行する際にはIP addressがブラウザのIPアドレスになるらしい。

phpに変更しよう。

$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($address)."&language=ja&sensor=false&key=[API_KEY];
$json = file_get_contents($url);
echo json_decode($json, true);
/**
 * 住所からgooglemapデータを取得する
 * */
function get_google_map_data_by_address(address){
    var api_url = '/get_geocode.php?address='+address;
    var result;
    var json = $.ajax({
        type: 'GET',
        url: api_url,
        async: false,
    }).responseText;
    result = JSON.parse(json).results[0];
    return result;
}

取れた取れた♪

リファラ問題は色々と難しいな…。

15
12
1

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
15
12