Google Maps APIのキーを動的に付加する方法
異なる領域では異なるキーが必要で、設置する場所によって書き換えるのは面倒だと思い、
var google_maps_keys = {'http://localhost/' : '...KeyA...' ,'http://localhost:3000/' : '...KeyB...' ,'http://localhost:8080/' : '...KeyC...' }; var directory = location.protocol + '//' + location.host + '/'; script.src = 'http://maps.google.com/maps?file=api&v=2&key=' + google_maps_keys[directory]; document.body.appendChild(script);
のようなことをしたかったが、うまくいかない。つД`) タスケレ !!
追記
document.writeすればいいみたい。(head要素にappendChild(script)してもダメなのはなんでだろう?)
↓のようにすれば設置場所を変えたときにkeyを書き換えなくても動きます。google_maps_key.jsみたいな名前で外部スクリプト化しておくといいかも。
(function() { var google_maps_keys = {'http://localhost/' : 'Key1' ,'http://localhost:3000/' : 'Key2' ,'http://localhost:8080/' : 'Key3' }; var directory = location.protocol + '//' + location.host + '/'; document.write('<script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=' + google_maps_keys[directory] + '">'); })();