7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

google maps api+geocoderの本番環境でGeocoder::RequestDenied

Last updated at Posted at 2018-12-02

住所から緯度経度を取得し、mapを表示しその位置にピンを立てたい
緯度経度取得時にrailsのgeocoderでGeocoder::RequestDeniedが出た時の対処法

  • geocoder 1.4.9
  • ruby 2.4.2p198
  • Rails 5.1.6

問題点

google maps apiのkeyを習得後
以下の様に本番環境用に設定
開発環境用は特に制限なし(公開しない方針で)

アプリケーションの制限
https://www.myapp.com/*
https://myapp.com/*

APIの制限
Maps JavaScript API
Geocoding API
Places API

geocoderを使うためにapi keyを渡します
gem configを使ってます

config/settings/production.local.yml
google:
  map_key: 'Your api key for production'
config/settings/development.local.yml
google:
  map_key: 'Your api key for development'

先頭に0をつけていないと、geocoder.rbを読み込む前にconfig.rbを読み込まない場合があります

config/initializer/0config.rb
Config.setup do |config|
  config.const_name = 'Settings'
end
config/initializer/geocoder.rb
if Rails.env.production? then
Geocoder.configure(
  lookup: :google,
  always_raise: [
    Geocoder::OverQueryLimitError,
    Geocoder::RequestDenied,
    Geocoder::InvalidRequest,
    Geocoder::InvalidApiKey
  ],
  api_key: Settings.google.map_key,
  use_https: true
)
else
Geocoder.configure(
  lookup: :google,
  always_raise: [
    Geocoder::OverQueryLimitError,
    Geocoder::RequestDenied,
    Geocoder::InvalidRequest,
    Geocoder::InvalidApiKey
  ],
  api_key: Settings.google.map_key
)
end
show.html.erb

<script type="text/javascript" src=<%= "https://maps.googleapis.com/maps/api/js?key="+Settings.google.map_key+"&libraries=places&callback=initMap" %> ></script>

表示はうまくいったことを確認し、本番環境で以下のコマンドを実行するとエラーが、、
開発環境ではうまくいくのになぜだとしばらく悩みました

geolocation = Geocoder.coordinates(`tokyo`)
Geocoder::RequestDenied

解決策

google mapの表示用のkeyはhttpリファラーで制限し、geocoderに渡す用のkeyはipアドレスで制限をする

よく考えたら当たり前のことでしたが妙に詰まったのでメモ

config/settings/production.local.yml
google:
  map_key: 'httpリファラーで制限をしたgoogle api key'
+ geocorder_key: 'サーバーのIPアドレスで制限をしたgoogle api key'
config/initializer/geocoder.rb
if Rails.env.production? then
...
- api_key: Settings.google.map_key,
+ api_key: Settings.google.geocorder_key,
...
else
...
end
console
geolocation = Geocoder.coordinates(`tokyo`)
=> [35.6894875, 139.6917064]

無事成功しました

7
5
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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?