CANR CLEAR
CLEAR Research

Maps on the Web

Google Maps API Code Cheatsheet

There are several ways to get code "snippets" for enhancing your API. One way is to search the API's documentation for examples. Another way is to open an example in your web browser, click "View" on the top menu bar, and select "Source" or "Page Source" on the drop down menu. This will open a new window with the page's code, pending the page's privacy settings. But even once you have the coding verbiage, how can you be certain you know where to copy and paste it into your own code? Here are two examples to help: a quick overview example and a more customized example below.

Overview Example

You have visited the Google Maps API web site and registered for a key. After registering, you receive a block of code to copy, paste and save in a text document.

Click here for the word document for copying code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>TITLE</title>

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA8XCCQd9GZwItDDvrduY9FRSoDOc-FS6y1FruaTqLS7t9z2rGLxRRT6cPLB9FVQx547VLCVG8Nr9kMQ"
type="text/javascript"></script>
</script>
</head>
<body>
<div id="map" style="width: 700px; height: 500px"></div>
<script type="text/javascript">
//<![CDATA[

var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(41.607228, -72.734985),9);


//]]>
</script>
</body>
</html>

This block of code needs to then be copy-and-pasted into your web page to add the Google Maps API to your web page. This is simple embedding. Here's what the web page now looks like:

Basic Map

Alright, that's a Google Map on your webpage! But what on earth does all this code that you copy-and-pasted even mean?

<DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/1999/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml>
This portion of the code tells the web browser that your page and code are compliant with web standards. This only has to appear once on your page, so you do not have to copy and paste this portion if you using a pre-created page that already has similar code.
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
The "head" refers to the page start of the web page and what is associated with it. This tells the browser a page is starting, and what format the content of the page is. In this case, the coding language is HTML format with UTF-8 characters.
<title>TITLE</title>
You can type in a title in place of the word TITLE and this is displayed when the page is loaded in a web browser (Note: in the image above, we have not changed TITLE, so the page loads with TITLE on the tab. When you change this, the words on the tab will change.)
<script
src="http://maps.google.com/maps?file=api&v=2&
key=ABQIAAAA8XCCQd9GZwItDDvrduY9FRSoDOc-FS6y1FruaTqLS7t9z2rGLxRRT6cPLB9FVQx547VLCV
G8Nr9kMQ"
"script" begins the content portion of the code - what is displayed on the page.
"src" stands for source. In this case, the source is an API file from Google Maps. "v=2" means you are calling version 2 of Google Maps API. "key=" is where your registration key is listed, unlocking the API.
type="text/javascript"></script>
    <script type="text/javascript">   
Here, the code is telling the browser that the code that follows is in javascript.
<div id="map" style="width: 700px; height: 500px"></div>
The "div" creates the map "canvas", or area where the map will be displayed on the page. The ID attribute is assigend a value of "map" that is called when loading an instance of GMap2, or the embedded map. Also, the size and placement of the map is specified and is based on pixels (not inches). If you want a bigger or smaller map, this is where you would change that setting.
//<![CDATA[
"CDATA", for coding purposes, means that what follows should not be interpreted by the browser the same way as the rest of the page.
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(41.607228, -72.734985), 9);     

"var map" is calling the Google map from Google - this is the bit of code that actually displays the map on your page. The "GMap2" object creates an instance of Google Maps and references version 2 of the API and is placed inside the div container.

"setCenter" sets the center of the map to a latitude and longitude (in Decimal Degrees) and the zoom level (0-21). In this case, we center it on Connecticut and set the zoom level to 9.

}
    }
    //]]>
    </script>
  </head>
 
Here the code is telling the browser that the CDATA, script and head are done. (Like a mathematical equation, we have to balance our parenthesis, brackets and tags!)
  </body>
</html>
Finally, the body of the page and the HTML code that was started at the beginning is ended, telling the browser to stop looking for more code.

For more, visit Google Maps' API code documentation.

Customized Example

So the above overview of the block of code kind of made sense, and you now have a map on your website. But how on earth do you copy and paste more code into that block to customize your map and make it an actual mashup? (Note: the map on your webpage has no zoom options, scale bar, map toggle options, anything! You've got to add what you want.) Here's an example of one customized code block and where those code snippets go.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps JavaScript API Example</title>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAA8XCCQd9GZwItDDvrduY9FRTFSJL-tJSO37QcC2RbGf38kby-CxRn1_A62ZzymJ57PsXA5q58qS5fvg"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map" style="width: 800px; height: 600px"></div>


<div id="control"><b><img src="images\Natl-NEMO-color-logo.png" alt="NatlNemo" width="67" height="101" /></b></div>
<div id="legend"><b><img src="images\legend.png" alt="legend" width="173" height="247" /></b></div>

<p>
<script type="text/javascript">
//<![CDATA[
if (GBrowserIsCompatible()) {

var gx = new GGeoXml ("http://clear.uconn.edu/tools/lid/NationalNemoLID.kml");

var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(36.949892, -97.470703), 4);
map.enableScrollWheelZoom();
map.addMapType(G_PHYSICAL_MAP);
map.setMapType(G_PHYSICAL_MAP);
map.addMapType(G_SATELLITE_MAP);
map.addControl(new GHierarchicalMapTypeControl());
map.addControl(new GSmallMapControl());
map.addControl(new GScaleControl());
map.addControl(new GOverviewMapControl());

map.addControl(new GMapTypeControl());
map.addControl(new GMapTypeControl());
map.addOverlay(gx);
var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(50,5));
pos.apply(document.getElementById("control"));
map.getContainer().appendChild(document.getElementById("control"));

var pos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5,15));
pos.apply(document.getElementById("legend"));
map.getContainer().appendChild(document.getElementById("legend"));
}

else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
// This Javascript is based on code provided by the
// Blackpool Community Church Javascript Team
// http://www.commchurch.freeserve.co.uk/
// http://econym.googlepages.com/index.htm
//]]>
</script>
<p>Return to <a href="index.htm">NEMO LID Inventory</a> or visit the <a href="http://extension.ucdavis.edu/cwlu" target="_blank">Center for Water and Land Use</a> at UC Davis</p>
</body>
</html>
APImap

Pretty nice map! But again let's break that block of code down into it's pieces and try to understand what's going on without becoming a coding expert.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8"/>
<title>Google Maps JavaScript API Example</title>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;
key=ABQIAAAA8XCCQd9GZwItDDvrduY9FRTFSJL-tJSO37
QcC2RbGf38kby-CxRn1_A62ZzymJ57PsXA5q58qS5fvg"
type="text/javascript">
</script>
</head>
Here, nothing has changed from the overview above, except for the title. It's been personalized: Google Maps JavaScript API Example. Note: the script and the head have both been ended.
<body onunload="GUnload()">
<div id="map" style="width: 800px; height: 600px"></div>
This portion was moved up from the bottom of the code, which makes no difference here.
<div id="logo"><b><img src="images\Natl-NEMO-color-logo.png" alt="NatlNemo" width="67" height="101" /></b></div>
<div id="legend"><b><img src="images\legend.png" alt="legend" width="173" height="247" /></b></div>
Here we are adding 2 more objects to the body of the page (previously it was just the map), a logo and a legend. Just as the map size was set above, the logo and legend sizes are set here.
<script type="text/javascript">
//<![CDATA[
if (GBrowserIsCompatible()) {
Nothing has changed here and we begin the CDATA part of the code to further customize the map. A new "script" is started.
var gx = new GGeoXml ("http://clear.uconn.edu/tools/lid/NationalNemoLID.kml");
Here we tell the browser to look for a KML file that we have put online and we will later ask the browser to display this KML as an overlay on the Google Map, mapping our data online. Note: "var gx" means that the KML will from here on out be called "gx".
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(36.949892, -97.470703), 4);
map.enableScrollWheelZoom();
map.addMapType(G_PHYSICAL_MAP);
map.setMapType(G_PHYSICAL_MAP);
map.addMapType(G_SATELLITE_MAP);
map.addControl(new GHierarchicalMapTypeControl());
map.addControl(new GSmallMapControl());
map.addControl(new GScaleControl());
Now the map is added and customized. First the map is centered and a zoom layer is set.
"enableScrollWheelZoom" will add the ability to use the scroll on the mouse to zoom in and out of the map
"addMapType(G_PHYSICAL_MAP)" and "setMapType" will add and then set the base map to a Terrain map
addMapType(G_SATELLITE_MAP) will add a satellite image basemap option
"addControl(new GHierarchicalMapTypeControl());" will add buttons for each basemap option so the user can toggle between them.
"addControl(new GSmallMapControl());" will make the zoom/pan tool small.
"addControl(new GScaleControl());" will add a scale bar
This section is where you would add any other "controls" to the map directly. Most of these are terms found on the Google Maps API website and need no further coding.
map.addControl(new GMapTypeControl());
map.addControl(new GMapTypeControl());
map.addOverlay(gx);
Here we add the logo and the legend as two new "Controls" and we add the "gx" KML to the map as an "Overlay".
var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(50,5));
pos.apply(document.getElementById("logo"));
map.getContainer().appendChild(document.getElementById("logo"));

var pos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5,15));
pos.apply(document.getElementById("legend"));
map.getContainer().appendChild(document.getElementById("legend"));
}
Above we added the logo and legend to the body of the page, then we asked for them to be added to the map as overlays. Now we tell the browser where on the map to put them. The positions are set relative to the sides of the map as "anchors" (so they never move as the map is zoomed and panned).
"GSize" sets how many pixels in from the sides of the map the image is anchored (we have already set the actually size of the image above in the "div" code).
"pos.apply..." then gets that image and positions it accordingly.
else {
alert("Sorry, the Google Maps API is not compatible with this browser");
}
This code describes what to do if the browser is not compatible - it will display the message "Sorry..." if the browser and the code are not compatible.
// This Javascript is based on code provided by the
// Blackpool Community Church Javascript Team
// http://www.commchurch.freeserve.co.uk/
// http://econym.googlepages.com/index.htm
Here we add text to attribute pieces of the code to certain sources. In this case, some of the code was found, copied and pasted from a commchurch.freeserve website. The double dashes in front of the text tell the browser that what follows is not to be interpreted as code. Therefore, this can go anywhere.
//]]>
</script>
Then the CDATA and script are ended.
Return to <a href="index.htm">NEMO LID Inventory</a> or visit the <a href="http://extension.ucdavis.edu/cwlu" target="_blank">Center for Water and Land Use</a> at UC Davis
Here the code adds text and links to the webpage itself, not to the map directly. The body of the page is still "open", so you can add any additional information to the page still. This could also be typed above the CDATA, with the "div" codes, without a difference.
</body>
</html>
Here the body and HTML code is ended, telling the browser not to look for anymore code.

Use these examples as helpers when thinking about copying and pasting code snippets. The examples are not intended to make you a prolific coder, though!