Automatically Switch Your Google Maps API Key To The Correct Environment Using PHP

Date June 26, 2007

The Google Maps API requires a unique key for each domain where maps will be rendered. This means the key you generate for your production environment won’t work on dev or qa (assuming your dev and qa environments are not served from within your production root).

I typically do my dev work locally, push changes to a qa server, and eventually push the final product to production.

In order to get my google maps to render across all three environments, I use a switcher that feeds the google maps API the correct key based on which server is asking for it.

Golden Gate Bridge

On a big site with many environment specific variables you’d probably want handle this in a per environment configuration file, but for smaller projects it works just fine.

The code to load up the mapkeys array is shown below:

<?php
$mapkeys = array("qa.server.com" => "qa key goes here",
"projectname.local" => "dev key goes here",
"server.com" => "prod key goes here",
"www.server.com" => "prod key also goes here"); // just in case

?>

When you call the script in the page header, instead of hardcoding the key value, you use the mapkeys array to render the dynamic value:

<script src="http://maps.google.com/maps?file=api&v=2&key=<? echo $mapkeys[$_SERVER["HTTP_HOST"]]; ?>"
type="text/javascript"></script>

$_SERVER[”HTTP_HOST”] is a predefined PHP variable containing the contents of the Host: header. For more information about PHP’s predefined variables, take a look at the php manual.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>