kopongo.com

home

deploying with google maps API keys

02 Dec 2007

If you are using google maps in your apps, you get special key from them that works for the URL where you want to use the maps (ie www.yoursite.com). Since you probably test your code on localhost before you deploy it, you have a problem. The key they give you only works at that URL. What you need to do is get another key that works with your testing on your localhost, for example for localhost:3000.

What this means that when you deploy, you have to switch them. Of course, you do not want to do this by hand.

Here's a simple way to do this with capistrano:

    task :after_update_code, :roles => [:app, :db, :web] do

       layout_file = File.read('app/views/layouts/standard.rhtml')
       google_map_key = File.read("config/google_map_key.txt")
       layout_file.sub!(/file=api&v=2&key=(\w+)/, "file=api&v=2&key=#{google_map_key}")
       put(layout_file,
           "#{release_path}/app/views/layouts/standard.rhtml",
           :mode => 0444)
    end 

So, what's going on?

First, save the production key on some file, like config/googlemapkey.txt. Don't think that is is like saving database passwords in SVN, since this key appears on all your webpages anyway.

I put my key in the site layout I use, standard.rhtml. By default, you want to keep development version of the key in there. When we deploy, we read the key from googlemapkey.txt, use a regexp to switch the development key with the production key. Then we send that file over with the put command.

You could be more clever by changing the file that's already on the server, instead of changing the local file and sending it over, but this works well enough.