HOW TO: configure Google map application to select and use a valid API key when hosted behind multiple domains?

I had a client that had a .com and a .co.uk domain name both pointing to a single hosted website. Having previously only had the .co.uk domain name I had only included an api key for that domain.

When the site was displayed using the .com domain it threw up an invalid api key error.

Here is the fix:

Some applications may be hosted on multiple domains. For example, many content management systems push the same content to different domains (e.g.example.com and example.net) and wish to have that content single-sourced. Since Google Maps API keys are generated per domain, you’ll need to generate separate keys for each domain and configure your application to use the correct one. The easiest way to do this in JavaScript is to dynamically generate the 

<script>

tag using 

document.write

and assigning the correct domain-specific key within the src attribute’s URL as a parameter. In doing so, you’ll need to pre-generate and hardcode the list of keys within your application.

Create an object which contains a mapping between domain names and its corresponding Google Maps API keys. Use 

window.location.host

to retrieve the domain name your application is running against, and pass it into the object to select the appropriate key.

Below is a JavaScript snippet you can copy and paste into your application. Replace property names labeled 

domain*.com

on the left with your list of domains and assign to each entry its corresponding and unique Google Maps API key.

document.write([
  ‘<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=’, {
    ‘domain1.com’: ‘apikey1′,
    ‘domain2.com’: ‘apikey2′,
    ‘domain3.com’: ‘apikey3′,
    ‘domainN.com’: ‘apikeyN’
  }[window.location.host],
  ‘" type="text/javascript"><\/script>’
].join());

When using the snippet above, be sure to include it within your HTML document above any script tags or JavaScript containing references to Google Maps API objects.

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

One Response to “HOW TO: configure Google map application to select and use a valid API key when hosted behind multiple domains?”

  1. found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later