LoginSignup
6
6

More than 5 years have passed since last update.

RailsとGoogle Maps API / Turbolinksでマップが読み込まれない時の対処法

Posted at

またまたTurbolinkネタ。
よくつまづくからメモが多いのです。

結論。ドキュメント通りにやる。
これです…。
https://developers.google.com/maps/documentation/javascript/tutorial

非同期に読み込むにはこんなコード。ドキュメントより。

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
      'callback=initialize';
  document.body.appendChild(script);
}

  
普通に読み込む時はapiキーが必要なので、必要だろうと思って付け加えるとダメです。

//こうすると…
script.src = 'https://maps.googleapis.com/maps/api/js?' +
        'key=XxxxxyC9HPscInexxxxxlYsUCekQLkHOK06ST3c'

//こんなエラーがでます。
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. 

  
あと、コールバックで何もやらないやといってcallback=initializeを省略してもダメです。
APIはpage:loadのタイミングで読み込みたいけど使うのは後、みたいな時。

initialize = ->
  # do nothing

  
とかやってコールバック用の関数を用意してください。
  

Turbolinksなので、
$(document).on('page:load', ready)のタイミングで実行するんですが、
何回も読み込んでしまってもダメなので、下のようになりました。

window.initializeMap = ->
    # do nothing

#Google maps apiの動的読み込み
getGoogleMapApi = ->
    if window.google == undefined
        script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
                            'callback=initializeMap'
        script.async = true
        document.body.appendChild(script)

ready = ->
    getGoogleMapApi()
    #他のいろんなこと…

# For turbolinks
$(document).ready(ready)
$(document).on('page:load', ready)

以上です。

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