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, including double-clicking on the map in the area of interest, clicking on the plus sign in the lower right of the map (or minus sign to zoom out), or using the scroll wheel on the mouse (if available).

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 right 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 Developers Console. The first thing we'll do is specify that we want to work with the Maps JavaScript API.
  3. Click on the API Project link.
  4. Under the APIs & auth heading, click on APIs.
  5. In the list of APIs that appears on the right, click on Google Maps JavaScript API under the Google Maps APIs heading, then on the Enable API button. Now we can move on to obtaining an API key.
  6. In the left-hand pane, under the APIs & auth heading, click on the Credentials link.
  7. Select Add credentials > API key.  You will be presented with a Create a new key dialog box.
  8. Select Browser key.
  9. 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).

  10. 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.
  11. Open Notepad or another plain text editor.
  12. Return to the Getting Started page, scroll down to the Hello, World section and copy and paste the code there into your text editor.
  13. Now go back to the console page and copy your API key.
  14. In your text editor, locate the second script element and replace the API_KEY text with the key you just copied from the console page.
  15. Save the file as lesson3.html.
  16. 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" is set to take up 100% of its parent container.

Next comes the body of the document, in which the first thing you'll find is a div element.  div elements are used to create divisions, or sections, in a document.  In a Google Maps API context, a div is typically used as the container for the page's map.  Note that this div is assigned an id of map.  This is consistent with the style setting mentioned a moment ago and, as we'll see soon, with the creation of the Map object in the JavaScript code.

After the map div, you'll find two <script> elements, which are used to define scripts written in JavaScript.  The first of these elements specifies how to create the map to be inserted on the page (more on this later), while the second sets up 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's found in the first script element.

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 first <script> element declares a variable called map, then defines a function called initMap().  Because the map variable is declared outside of the function, it has a global scope.  In other words, if there were a second function -- say, loadData() -- the map variable could be used in that second function, whereas if the variable had been declared within initMap(), it would not be usable in a different function. 

Before discussing what's going on in initMap(), first scan through it, and note the occurrence 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'd need a way to distinguish between your class and Google's. That's where namespaces come in. To use Google's Map class with no chance of confusion, we add the prefix "google.maps." to the class name.

To understand what's going on in initMap(), open the API Reference in a new tab.  Clicking on an item under the Contents heading on the right side of the window will redirect the browser further down on the page to the section that describes that item. 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 API 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 API Reference into a working custom map application. That is where the code Samples page can be quite helpful.

Getting back to initMap(), it creates an object of the Map class, so we'll want to look at the constructor for that class.  The documentation tells us that when creating a new Map object, we need to specify a container that will hold the Map.  As we saw earlier, a div was created for this purpose and assigned an id of map.  Getting a reference to that div element within your JavaScript code 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.

Returning to the documentation of the Map class constructor, note that we can optionally specify a MapOptions object when creating a Map.  Following the MapOptions link takes you to a section of the API Reference labeled "MapOptions Object Specification."  The wording of this header indicates that we're dealing with 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. Unlike a class such as Map, an object literal has no class constructor, methods or events.  In this case, the object literal is specified using two property/value pairs: a center property, which is itself set equal to an object literal defined as a lat/lng pair, and a zoom property, which is set to a value of 8.  Note that it is possible to store an object literal in a variable.  For example, an alternative to the syntax seen in the Hello, World script would look like this:

var myMapOptions = {
  center: {lat: -34.397, lng: 150.644},
  zoom: 8

map = new google.maps.Map(document.getElementById('map'), myMapOptions);

Finally, here are a couple of important points to note:

  • The second script element uses two attributes to control the loading and execution of the Google Maps API code.  The default behavior for browsers is to pause the rendering of other HTML elements when they encounter a script element.  The async attribute (introduced in HTML5) tells the browser to continue rendering the HTML and to load and execute the JavaScript code at the same time.  The defer attribute (which has been around longer than async) similarly tells the browser to continue rendering the HTML while it loads the JavaScript code.  The difference with defer is that it instructs the browser to wait to execute the JavaScript until the HTML is fully rendered.  The two attributes can be used together to still get the "don't-stop-rendering" behavior even in older browsers that don't support HTML5 (and async).  You can find further discussion of these attributes in this blog post, if you're interested.  I wouldn't be too concerned if you're a bit fuzzy on the topic though, as it's not critical for a novice developer to understand.
  • What is critical to understand are the key and callback parameters appended to the API URL.  If you're adapting this example to create a page of your own, you'll want to replace the "API_KEY" value with the one that you obtained earlier in the lesson.  Likewise, the value assigned to the callback parameter (the name of the function to execute when the API is done loading) may need modification depending on how you name your initialization function.  For example, if you name your function initialize rather than initMap, you'll need to change the callback parameter accordingly.

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 initMap() 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. 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 Map object from map to myMap. This requires updating the lines where the variable is declared, where it's initialized and where name the map property of the MarkerOptions object is set. Here is the complete script if you'd like to confirm that you wrote it correctly:

    var myMap;
    function initMap() {
      myMap = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 8
      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 initMap() 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. (60 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 4, you'll see how to spice up the rather dull product of Lesson 3 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.