Lesson 3: Introduction to the Google Maps API


In Lesson 3, you'll be exposed to the "Hello, World" page of the Google Maps JavaScript API. Hello World programs have been encountered by computer programming students learning a new language for many years. The folks who developed the GNU operating system have a funny list of Hello World programs written by people of different ages and occupations. Perhaps you can find one that matches you.

To make sense of the Google Maps Hello, World page, you'll need to recall the web content authoring technologies covered in the previous lesson:

  • Hypertext Markup Language (HTML)
  • Cascading Style Sheets (CSS)
  • HTML Document Object Model (DOM)
  • JavaScript

After dissecting the various parts of the Google Maps Hello, World page, you'll finish the lesson by modifying the page to include a marker that depicts the location of your hometown.


At the successful completion of this lesson, students should be able to:

  • use the Google Maps website to locate places by various search methods;
  • manually construct a URL that will load a desired Google Map;
  • insert JavaScript into a web page;
  • use JavaScript and the Google Maps API to add a custom map to a web page;
  • set the initial extent parameters of a custom map;
  • obtain information on how to work with objects defined in the API through the API Reference;
  • add markers (points) to a map;
  • cite examples of well-known Google Maps API apps.


If you have any questions now or at any point during this week, please feel free to post them to the Lesson 3 Discussion Forum. (That forum can be accessed at any time by clicking on the Communicate tab and then scrolling down to the Discussion Forums section.)


Lesson 3 is one week in length. (See the Calendar in ANGEL for specific due dates.) To finish this lesson, you must complete the actvities listed below. You may find it useful to print this page out first so that you can follow along with the directions.

Steps to Completing Lesson 3
Step Activity Access/Directions
1 Work through Lesson 3. You are in the Lesson 3 online content now. The Overview page is previous to this page, and you are on the Checklist page right now.
2 Complete "Plot Your Hometown" project. You will be working on this throughout the lesson.

  • Post the map of your hometown to your e-portfolio.
  • Below the map, include some reflection on what you learned from the lesson and/or any concepts that you found to be confusing (minimum 200 words).
Follow the directions throughout the lesson and on the "Plot Your Hometown" page.
3 Review a GIS mashup after you read the online content. Find a Google Maps API mashup that catches your eye and write a short review of it in the Lesson 3 Discussion Forum.
4 Take Quiz 3 after you read the online content. Go to the Quizzes folder and click on the "Lesson 3 Quiz" link to begin the quiz.


Introduction to Google Maps

Before we build our own Google Maps pages, we'll begin by taking a look at how Google's own mapping site works. Even if you've used this site before, you are likely to learn something from this section.

Please open a browser window to Google Maps so that you can follow along with the discussion below.

Navigating the map

The user can pan the map to see what's just off the screen by clicking and dragging in the desired direction.

The user has multiple options for zooming in on the map.  The first is to double-click on the map in the area of interest. The second is to click on the plus sign in the lower right of the map (or minus sign to zoom out).

Also in the lower right corner of the map is a scale bar; clicking on it toggles between English and metric units.

In the lower left corner of the map is an icon that allows the user to switch between two primary map types: Map and Earth. The Map view displays a conventional reference map of political boundaries, place names, roads, railroads, water features, and landmarks. The Earth view displays satellite imagery or aerial photography, depending on the zoom level, with higher resolution data often available for major cities.

When in Earth view, a couple of additional controls appear above the zoom controls.  The first enables rotating the view 90o, 180o or 270o.  The red arrow will point north.  The second control allows for applying two levels of tilt. 

If you are a regular Google Maps user, you are probably aware that the search box at the top of the page can be used to locate places using full street addresses, just a city and state name, or even just a city name or zip code. However, it is also possible to locate places using airport codes (e.g., "LAX" for Los Angeles International) or latitude/longitude pairs (e.g., 40.8, -77.86 for Penn State's University Park campus). In addition, driving directions can be generated by separating any set of locations by the word "to" (e.g., "phl to state college, pa" to get directions from Philadelphia International Airport to State College). Businesses in close proximity to a location can be found by using the word "near" (e.g., "pizza near state college, pa") or by simply searching for a business type (e.g., "restaurants") when already zoomed in to the area of interest.

A collapsible control beneath the search box provides access to other background layer/overlay options. These include:

  • Traffic - an overlay available in major cities that color codes highways based on the amount of congestion: red for heavy traffic, yellow for slow traffic, and green for normal-speed traffic
  • Bicycling - routes originally obtained from the Rails-to-Trails Conservancy and augmented with user contributions
  • Terrain - a layer that depicts the area using shaded relief

One last viewing option that warrants a mention is the Street View layer, which enables the user to view 360-degree panoramic photos taken at street level.  Switching to Street View can be done by clicking on the "orange man" icon in the lower left and dropping him onto any blue line on the map.  If the man icon is colored gray, then Street View is not available anywhere in the viewport.

Most of the site features discussed above are also available to third-party Google Maps developers. They can be arranged differently and unwanted controls can be left off the interface altogether. We'll come back to this later.

Inside Google Maps URLs

After searching for a location/business or generating driving directions, you can copy the URL in the browser's address bar to save it for later use, for example, to e-mail it to a friend. If you examine this URL closely, it has a number of parameters that will vary depending on the map type. Here is a simple Google map of State College [https://www.google.com/maps/place/State+College,+PA/@40.7880144,-77.8525714,14z/data=!3m1!4b1!4m2!3m1!1s0x89cea899c13bdb73:0x9ce1c6c2833c8091].

Looking closely at this URL, here are some points to note:

  • the spaces in "State College, PA" are replaced by + signs since spaces in URLs can create problems,
  • the word "place" will be replaced by "search" or "directions" depending on the entry made in the search box (e.g., "coffee shops" or "philadelphia to harrisburg"),
  • after the search term (in this case "State+College,+PA") comes the latitude/longitude at which the map should be centered (preceded by the @ symbol),
  • after the map's center comes the zoom level ranging from 3z to 21z.

The URL often ends with a data parameter set to a long character string.  Google has not made public how this string is constructed, though some bloggers have published some observations.  It's a bit complicated, so I'll just point you toward the blog posts if you're interested in learning more:
New Google Maps URLs - Introduction from Sticklesville
Stop Worrying About the New Google Maps; These URL Parameters Are Gold

Knowledge of constructing URLs that can be parsed by the Google Maps servers has a lot of potential value. For example, if you had an Excel spreadsheet of addresses, you could generate a list of links that would open up a Google Map of each address. Excel's SUBSTITUTE function could be used to replace spaces in the addresses with + signs and the CONCATENATE function could be used to merge the address with the other required parts of the URL.

Now that you've gotten a brief tour of Google Maps, let's dive into creating your own custom mashup using the Google Maps API.

Orientation to the Google Maps API Reference

Google provides web developers with a number of APIs (Application Programming Interfaces) for building geospatial applications. The most commonly used API (the JavaScript-based Maps API) is the one that we'll be learning about during this course. However, you should make a mental note of the other APIs that are available: two for developing native apps on mobile devices (one for Android phones and the other for iOS), and a set of location-based web services (e.g., the Elevation and Time Zone APIs).

The Google Maps JavaScript API home page [https://developers.google.com/maps/documentation/javascript/] is composed of 5 tabs:

  • Home: shows demos of the API's capabilities
  • Guides: provides a high-level overview of various API concepts.  This course will cover a lot of these same concepts, though you may find it worthwhile to use Google's Guide pages as a supplement to what you read here or to explore topics we don't cover. 
  • Reference: the place to go to obtain detailed information on the usage of the object classes built into the API. 
  • Samples: go here to find code examples in categories such as Basics, Controls, Drawing on the Map, etc.
  • Support: provides a link to Stack Overflow's questions related to the Google Maps API and to a list of known API bugs

Now that we've seen where Google Maps developers go for information about the API, let's begin developing our own maps.

Building Your First Google Map Customization

The best way to build your first Google Map page is probably to use their "Hello, World" page as a starting point.

  1. Head over to the "Getting Started" section of the API documentation. As the tutorial says, the first step in building a map page is to browse to the Google APIs Console to obtain an API key.
  2. Open the link to the Console page in a new window or tab. We'll want to work with both the tutorial and console pages. If you don't yet have a Google account, sign up for one now. Then, log in to your account. You're likely to be asked how you can be contacted should you ever forget your password and to accept the terms of service. After going through all that, you should be looking at the Google Project Dashboard. The first thing we'll do is specify that we want to work with the Maps JavaScript API.
  3. Click on the API button on the Project Dashboard page.
  4. Under the Google Maps API heading, click on Google Maps JavaScript API, then on the Enable API button. Now we can move on to obtaining an API key.
  5. In the left-hand pane, under the APIs & auth heading, click on the Credentials link.
  6. Under the Public API Access heading, click the Create new Key button. You will be presented with a Create a new key dialog box.
  7. Select Browser key.
  8. In the text box beneath the Accept requests from these HTTP referers... heading, enter the following:

    *.personal.psu.edu/[your PSU access account ID]/*

    For example, I entered *.personal.psu.edu/jed124/*


    It turns out that you don't really need an API key when working with the Maps API, but it's good to know how to obtain and use one in case you build a production application. If the API key gets in your way while testing (for example, when double-clicking your .html file on your local file system), you can remove the key. Just remove the text:
    key=AIzaSyD1PO2RgLOjIXNSd3_OSQ_UTFJV4sQocBE (your actual key will differ).

  9. Click Create to complete the creation of the key. We'll come back to the console page in a moment, so be sure to leave it open.
  10. Open Notepad or another plain text editor.
  11. Return to the Getting Started page, scroll down to the Hello, World section and copy and paste the code there into your text editor.
  12. Now go back to the console page and copy your API key.
  13. In your text editor, locate the first script element and replace the YOUR_API_KEY text with the key you just copied from the console page.
  14. Save the file as lesson3.html.
  15. Upload your lesson3.html file to your personal web space and confirm that you see a map of Sydney, Australia. (If you upload the file to your root web space, it will be available at the address http://www.personal.psu.edu/[your PSU access account ID]/lesson3.html.)

Now, unless you live in Sydney, this map probably won't be particularly useful to you. In the next section, we'll spend a good deal of time dissecting the various pieces of the code you just copied so that you are able to understand what each piece contributes to the page.

Dissecting the Google Maps Hello World Page

Let's examine this start-up page and discuss its various pieces. Now that you are familiar with HTML, you should recognize the <html>, <head> and <body> tags. You should also recognize that the <!DOCTYPE> directive declares that the document is written as HTML5.

The first block of code within the head is a style element containing a few CSS settings. The basic idea behind these settings is to produce the best consistency in the rendering of the document by different browsers. The document as a whole (i.e., the html element) should take up 100% of the available space in the browser window. The body element, in turn, should take up 100% of its parent container, the html element. The body's margin and padding are also set to 0px, which in effect specifies that there should be no whitespace added to either the exterior or interior of the body element's boundary. Finally, the element with the ID of "map-canvas" is set to take up 100% of its parent container and also have its margin and padding set to 0px.

This brings us to the <script> tag. This tag is used to enclose scripts written in either JavaScript or VBScript. There are a couple occurrences of <script> in this page. The first simply sets a reference to the current version of the Google Maps API by setting the element's src attribute equal to a Google URL. It also supplies an API key which is required by Google. Including this script element is critical to building a working application. Without it, the browser won't know what to make of the JavaScript code that comes later in the page.

The second <script> tag signals the beginning of a block of actual JavaScript code.

Learn More

At this point, you should familiarize yourself with the syntax of JavaScript (JS). The w3schools site offers a good hands-on JavaScript tutorial that should do the job. Take a couple of hours to work through the topics listed under the JS Tutorial heading and pay particular attention to the following points:

  • Ending statements with a semicolon is optional. (The start-up script from Google uses semicolons.)
  • Note the difference between placing scripts inside the page's head section and its body section.
  • JavaScript is a dynamically typed language; you do not need to specify a data type when declaring a variable.
  • JavaScript variables are case sensitive.
  • Variables can be initialized on the same line that they are declared.
  • Code associated with a conditional statement (if or else statements) or a loop (for or while) must be enclosed in braces.
  • Alert boxes can be used to debug scripts that aren't working properly.
  • JS functions are reusable blocks of code with an optional return value.
  • The backslash (\) can be used to insert special characters in a string (e.g., if you want a string enclosed in double quotes to contain a double quote).
  • Comments are signaled in JS using two slashes (//).

Now that you've learned a bit about JavaScript, we can examine the part of the file that loads the map onto the page. The <script> section is composed of a single function called initialize(). Before discussing what's going on in this function, first scan through it, and note the two occurrences of the string "google.maps". This is an example of a namespace. The usage of namespaces is deserving of a lesson in itself, but you can get by with the basic knowledge that namespaces are used to prevent confusion when multiple classes share the same name. For example, the Hello, World page that we're discussing here references (or sources) a JavaScript code library stored on a Google server. One of the classes defined in that library is called Map. If you wanted to, you could develop your own class named Map, but you need a way to distinguish between your class and Google's. That's where namespaces come in. To use Google's Map class, we add the prefix "google.maps." to the class name.

Getting back to the script, it begins by storing some map property settings in a variable called mapOptions. The properties are specified using a JavaScript object literal, a term that may seem intimidating, but is actually not too difficult to grasp. Object literals are basically a list of property/value pairs, in which the list is enclosed in curly braces and the property/value pairs are separated by commas. In this case, the object literal consists of two property/value pairs: a zoom property, which is set to a value of 8; and a center property, which is itself set equal to an object literal defined as a lat/lng pair.  The center/zoom object literal  is stored in a variable called mapOptions for use in the next line of the script.

Learn More

To see the other MapOptions properties, return to the API documentation and click on the Reference tab near the top of the page. Under the Contents heading on the right side of the page, click on the MapOptions object specification link and scan over the available properties.

That next line of the script is where the map is actually created. When creating an object of the Map class, you must specify the container in the HTML document that will hold it. This is typically a div element. (div elements are used to create divisions, or sections, in a document.)

If you scan down towards the bottom of the document, you should see a <div> tag on the third line from the bottom. This div element has had the name map-canvas assigned to its id attribute.

Returning to where we left off, the script specifies that the new Map object should be associated with the page element whose ID is map-canvas and should take on the property settings stored in the mapOptions variable. Attaching the Map object to the map-canvas div is done using the HTML Document Object Model (DOM).

Learn More

Once again, the w3schools site offers a good JavaScript HTML DOM tutorial. This short tutorial should only take you 30-60 minutes to complete. Pay particular attention to the usage of the getElementById() and getElementsByTagName() methods.

All of the classes defined by the API (such as Map and LatLng) are documented in the API Reference. Clicking on an API element under the Reference Contents heading will redirect the browser further down on the page to the section that describes that element. For example, if you click on the Map class, you'll be taken to the section that describes that class's constructor (i.e., information on the parameters that are specified when creating a Map object), its methods (actions that the Map class is programmed to perform), its properties (characteristics that uniquely define Map objects) and its events (interactions with the Map that are triggered by the user and can be programmed against by you the developer).

Method parameters (pieces of information the method uses in performing its action) are listed in parentheses after the name. If a parameter is optional, it will be listed with a question mark next to it. If a method returns a value when it is called, the type of return value will be listed next to the method name and parameters. Finally, there is a brief description listed for each method.

Note that some methods return a basic data type like a Number, String or Boolean, while others return an object (anything presented as a link). Following one of these object name links will jump you to that object's section of the documentation.

The class reference is good for getting a sense of everything that you can do as a developer with the API. However, it is not always easy to translate the information found in the class reference into a working custom map application. That is where the code Samples page can be quite helpful.

Returning to the code, the end of the initialize() function comes with the } character on the line after the 'var map' statement. However, because this function was written in the document's head section, it will not be executed automatically. The instruction to the browser to execute the script comes on the next line.  That line specifies that the initialize() function that we just dissected should be executed in response to the window's load event being triggered.  Refer to the HTML DOM to learn more about events that can be used by programmers to control a page's behavior.

Now that you understand the workings of the Google Maps Hello, World page, you'll see how to add a marker to your map in the next section.


Adding Markers to a Google Map

The Google Maps API allows developers to add points, lines and polygons to the map as overlays. Point overlays are the most common and are represented in the API as Marker objects. We'll use the API Reference as a guide to adding a marker to our map.

  1. Open the API reference page and search the page (Ctrl-F) for the Marker class.  (You'll probably find the class's entry in the Contents list first, so click on that entry to jump down to the desired section of the documentation.)

    Like many other classes in the API, the Marker class's listing in the API Reference includes a Constructor section. This indicates that an object of this class can be created using the new keyword followed by the class name (new Marker). Inside the parentheses is a listing of the parameters that the developer must/can supply when creating the object. In the case of the Marker class, it has just one parameter called opts that is supplied using an object of the MarkerOptions class. The opts parameter has a ? beside it to indicate that it is an optional parameter.
  2. Follow the MarkerOptions link to view its part of the page.

    Note that this class does not have a Constructor section in its documentation. This indicates that creating an object of this class involves using the object literal notation that we encountered earlier when we created a MapOptions object. Of the roughly dozen properties listed beneath MapOptions, two are particularly important:
    • position: set using a LatLng object defining the point where you want the marker to appear, and
    • map: set using a reference to the Map object on which the marker should be added. 
  3. Follow the LatLng link to jump to its section.

    The LatLng class constructor lists two required parameters (lat and lng). As implied by their names, these parameters are specified using numbers representing the desired point's latitude and longitude. The third, optional, parameter can be set to True to allow for lat/lng values outside -90/+90 and -180/+180.

    So, with the information we've gathered from the API reference, we know that the steps for adding a marker to the map are to create a LatLng object, use that object to create a MarkerOptions object, then create a Marker object using the MarkerOptions object as an argument to the Marker class constructor.
  4. Open your lesson3.html file in any text editor. We're going to add our marker in the same location that's being used for the map's center. Rather than specify the marker's position using an object literal as the Hello, World example specifies the map's center, let's create a LatLng object, store a reference to that object in a variable, then use the variable to set the marker's position.
  5. Insert the following line to the end of the initialize() function:

    var latlng = new google.maps.LatLng(-34.397, 150.644);
  6. Next, create a MarkerOptions object and set its position and map properties:

    var myMarkerOptions = {
       position: latlng,
       map: map
  7. Finally, create the Marker and add it to the map:

    var myMarker = new google.maps.Marker(myMarkerOptions);
  8. Save the page and test it in your web browser.

    You may have noticed (and been confused) that latlng appears in the script as both the name of a variable and a class. The same goes for map and mapOptions. It's actually OK if this happens, but let's rename these variables to make the script a bit easier to follow.
  9. Change the name of the variable that references the LatLng object from latlng to myLatLng. Note that changing this name requires updating the position property of the MarkerOptions object.
  10. Change the name of the variable that references the MapOptions object from mapOptions to myMapOptions.  This requires updating the second argument to the Map class constructor.
  11. Change the name of the variable that references the Map object from map to myMap. This requires updating the map property of the MarkerOptions object. Here is the complete Initialize function if you'd like to confirm that you wrote it correctly:

    function initialize() {
      var myMapOptions = {
        center: { lat: -34.397, lng: 150.644},
        zoom: 8
      var myMap = new google.maps.Map(document.getElementById('map-canvas'),
      var myLatLng = new google.maps.LatLng(-34.397, 150.644);
      var myMarkerOptions = {
        position: myLatLng,
        map: myMap
      var myMarker = new google.maps.Marker(myMarkerOptions);

Going forward, you will not be expected to preface your variable names with "my" as we've done here.  My rationale for doing it here is to help clarify what's a variable (changeable) and what's a property or class (not changeable). 

Now that you've seen how to add a marker to a map, you're ready to modify your page so that it displays your hometown.  If you see problems with the way the initialize() function was written above, that's good because I'll be expecting you to write the code more efficiently as part of your assignment. laugh

Assignment: Plot Your Hometown

Given the large dose of conceptual material you were introduced to in this lesson, the project that you'll submit for grading will be rather short. Here are some instructions for completing the assignment.

If you completed GEOG 482 (or GEOG 160 for those on campus), you should have located the latitude/longitude coordinates of your hometown in Project 1 using the United States Geological Survey's Geographic Names Information System or the Getty Thesaurus of Geographic Names (for students outside the U.S.). If you have not taken that course, use those tools or any other resources at your disposal (e.g., ArcMap) to find this information.

Modify your lesson3.html page so that the map is centered on and a marker points to your hometown. The easiest approach to this problem would be to alter the two identical sets of coordinates left over from the lesson. However, I hope you'll recognize that repeating values in different parts of a program is generally a bad practice because of situations like this where you end up having to make revisions in multiple places. So, while you're changing the location displayed on the map, revise the code so that it is as efficient as possible.

Also, be sure that your page passes successfully through the W3C validator without errors. (You will probably receive 2 warnings, which are OK to ignore.)


This project is one week in length. Please refer to the course Calendar tab, in ANGEL, for the due date.

  1. Post the map of your hometown to your e-portfolio. (40 of 100 points)
  2. Below the map, include some reflection on what you learned from the lesson and/or any concepts that you found to be confusing (minimum 200 words). (20 of 100 points)
  3. Find a map built using the Google Maps API that catches your eye, and write a short review of it in the Lesson 3 Discussion Forum. (20 of 100 points)
  4. Complete the Lesson 3 quiz.

Summary and Final Tasks

In this lesson, you built your first Google Maps customization. Even the simple map that you created involves a number of different technologies (HTML, XML, XHTML, the HTML Document Object Model, and JavaScript) and it is important that you have a firm understanding of this material before moving on. If you skipped over the w3schools tutorials referenced in the lesson, be sure to go back and complete them.

In Lesson 3, you'll see how to spice up the rather dull product of Lesson 2 by adding navigation and map type controls, opening info windows when the user clicks on a marker, using a custom marker icon, and adding line and polygon overlays.