Lesson 2: Introduction to the Google Maps API

Overview

In Lesson 2, you'll be exposed to the "Hello World" page of the Google Maps API. Hello World programs [http://en.wikipedia.org/wiki/Hello_world] 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 [http://www.gnu.org/fun/jokes/helloworld.html] 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 be exposed to a number of web content authoring technologies, including:

  • Hypertext Markup Language (HTML)
  • Extensible Markup Language (XML)
  • Extensible Hypertext Markup Language (XHTML)
  • 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.

Objectives

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.
  • Create a basic Google map without programming.
  • Understand the basics of XML and XHTML.
  • Explain the difference between the strict and transitional dialects of XHTML.
  • Verify that a web page contains valid strict or transitional XHTML.
  • Insert JavaScript into a web page.
  • Understand the basics of the HTML Document Object Model (DOM).
  • 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 mashups.

 

Questions?

If you have any questions now or at any point during this week, please feel free to post them to the Lesson 2 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.)

Checklist

Lesson 2 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 2

Step Activity Access/Directions
1 Work through Lesson 2. You are in the Lesson 2 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 GIS mashup that catches your eye and write a short review of it in the Lesson 2 Discussion Forum.        

4 Take Quiz 2 after you read the online content. Go to the Quizzes folder and click on the "Lesson 2 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 http://maps.google.com/ so that you can follow along with the discussion below.

Those of you who are logged in with a Google account should see the "new" Google Maps, which debuted in Spring 2013.  If you are not logged in with a Google account, you're likely to see the "classic" Google Maps.  Custom maps created with the Maps API have a user interface (UI) that more closely resembles the classic Google Maps, so the discussion below will be based on that version of the site.  However, I do recommend you check out the new version, if you haven't used it already.  

As mentioned, you'll need a Google account to try the new Google Maps.  If you don't yet have a Google account, try clicking the Sign In link near the upper right of the page and follow the directions.  (You'll need an account to work with the Maps API later too.)

After playing with the new version of Google Maps, click on the Help & Feedback menu in the upper right of the map and click the Return to classic Google Maps link.  The left side of the page is probably covered by a panel encouraging you to try the new Google Maps.  Click the arrow in the upper right of that panel to hide it.

Navigating the map

The user can pan the map in a couple of different ways. The first way is to click and drag the map in the desired direction. The second way is to click on one of the arrows in the upper left corner of the map.

The user can also zoom in on the map in different ways. The first way is to double-click on the map in the area of interest. The second way is to use the zoom level control, also found in the upper left corner of the map, just below the panning controls. The zoom level handle can be dragged up to zoom in or dragged down to zoom out. The user may also click on the plus or minus sign to zoom in or out one level at a time.

In the lower right corner of the map is an overview map.  This map is hidden by default, so you'll need to click on the arrow icon to show it. The blue rectangle on this map depicts the area that is currently being displayed on the main map. The user can also pan the main map by dragging this blue rectangle to a new location on the overview map.

In the lower left corner of the map is a scale bar that reports distance in both English and metric units.

In the upper right corner of the map is an icon that allows the user to switch between two primary map types: Map and Satellite. The Map view displays a conventional reference map of political boundaries, place names, roads, railroads, water features, and landmarks. In North America, this imagery is provided by NavTeq. The Satellite view displays satellite imagery provided by NASA. Higher resolution imagery (for zoom levels 1-5) of North America is provided by DigitalGlobe and TerraMetrics. This imagery is generally available for only large population centers. By default, Satellite view includes reference map data overlain on top of the aerial imagery.  Clicking the Earth button to the left of the Map/Satellite button initiates a browser plug-in that displays 3-D imagery and behaves in much the same way as the popular Google Earth standalone application.

The collapsible menu beneath the Map/Satellite button offers a number of 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
  • Photos - from Panoramio
  • Webcams - from Webcams.travel
  • Videos - from YouTube
  • Wikipedia -  place descriptions from Wikipedia
  • 45o - oblique aerial photography available in limited urban areas
  • Bicycling - routes originally obtained from the Rails-to-Trails Conservancy and augmented with user contributions
  • Labels - an overlay of reference map labels that can be toggled on/off when in Satellite view
  • Transit - another overlay available in major cities that shows public transportation routes
  • 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.  You can tell whether Street View is available somewhere in the viewport if the "man" icon at the top of the zoom slider is colored orange.  If so, you can click on the man and drag him onto any blue line on the map to see street-level photography at that location.  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. The developer also can choose to use a simplified version of the zoom level control.  We'll come back to this later.

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.

Inside Google Maps URLs

After searching for a location/business or generating driving directions, you can click the "Link" button in the upper right of the info panel.  This provides access to a URL that can be used to generate the map you're currently viewing. If you examine this URL closely, it has a number of parameters that will vary depending on the map type. Here is the URL for a simple map of State College: http://maps.google.com/maps?q=state+college,pa&hl=en

Note that the space in "state college" is replaced by a + sign because spaces in URLs can create problems.

If you wanted to create a different map, you could simply replace "state+college, pa" with a different string, such as "90210" or "philadelphia+to+harrisburg" or "coffee+shops+near+chicago". Each of these examples involves modifying the URL's query string (q) parameter. The other parameter in this URL is the language (hl) parameter, which in this case is set to English (en). Google has not made public the various parameters used in their URLs, but here is a list that I first encountered in Google Maps Hacks:

  • t (map type, k for satellite with labels, h for satellite without labels, p for terrain, omit for a regular reference map)
  • ll (longitude and latitude of the map's center)
  • z (zoom level, which appears to range from 0 to 19 over most of the globe and up to 23 in select areas)
  • spn (degrees of longitude and latitude across the map)
  • sspn (search span, defines the area to conduct a local search for businesses)
  • sll (center point for a local search)

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 seen how Google developers have set up their own mapping site, let's discuss how you'd create your own map mashup without any programming.

Creating a Custom Web Map Without Programming

Both Google and Esri provide the means for non-programmers to create basic web maps without writing any code and the capabilities of these map authoring applications are increasing constantly.  In this part of the lesson, we will explore Google's Map Engine and Map Engine Lite, and Esri's ArcGIS Online.

Google Maps Engine Lite

This product is meant as a replacement for Google's My Maps.  My Maps allows users to add points, lines and polygons -- through hand digitizing -- and store those custom maps on Google's servers.  Google Maps Engine Lite builds on My Maps by enabling users to upload geocodable data from spreadsheets and delimited text files.  Let's have a look.

  1. Navigate to Google Maps Engine Lite [https://mapsengine.google.com/map/].
  2. On the opening splash screen, click New Map.

    You should see a blank map appear overlain by a small panel in the upper left.  This panel shows that you begin with a new blank layer (called "Untitled layer").

    Your goal in the next few steps will be to create a map showing the places you've lived during your life.  (If you have any qualms about sharing this information, you're welcome to create a different map, such as favorite vacation places, instead.)
  3. Open Microsoft Excel.  If you don't have Excel, you can instead use a plain text editor such as Notepad and enter values separated by commas.
  4. Add the following column headers in the first row: Timespan, Length, Location
  5. Fill in the spreadsheet with the Timespan value being the years you lived in the place (e.g., 1990-1992), Length being the number of years you lived there and Location being the town (e.g., Miami, FL).
  6. Save your spreadsheet (or text file).
  7. Return to Google Maps Engine Lite in your web browser and click on the Import button beneath the Untitled layer heading.
  8. Click and drag your spreadsheet into the dashed box or click Choose a file to upload and browse to it.

    After Maps Engine Lite scans your spreadsheet, you'll be prompted to specify the column(s) that should be used to position your placemarks.
  9. Check the Location column and click Continue.  

    Maps Engine Lite will pass the values in the Location column to a geocoder, which will determine the coordinates of the points you're adding to the map.  Note that we could have also uploaded a file containing actual latitude/longitude values.  In that scenario, you'd have one column labeled "X" or "Lon" and another labeled "Y" or "Lat."

    You're next asked to specify a column that will be used to title your markers. 
  10. Check the Timespan column and click Finish.

    After Maps Engine Lite processes all of your uploaded data, you should see all of the locations added to the map with a red teardrop-shaped symbol.  You should also see that the panel in the upper left lists each marker by its Timespan value.  Finally, note that the layer has taken on the name of your spreadsheet.

    Let's change the layer's name to something user friendly, like "Towns"
  11. Click on the layer's name, enter the new name and click Save.
  12. Hovering your mouse over the first marker in the panel, you should see a paint bucket icon.  Click on that icon to change the symbology of that marker.

    Note in the symbology dialog you can change the marker's color and its icon.  Available icons include basic shapes like circle, square, diamond and star, and more elaborate shapes (found by clicking More icons).
  13. Click on Style beneath your layer.  Your layer is currently set up so that you can style each marker individually. Note the other styling options:

    Uniform style - all markers are given the same symbology, 
    Sequence of color and letters - each marker gets its own color and letter, and
    Style by data column - markers can be symbolized based on ranges (for numeric columns) or categories (for text columns).
  14. The Sequence of color and letters option is not a bad choice for a map like this, so select that option.
  15. Click on Labels beneath your layer and change the map from having No labels to labels based on the Length column.
  16. At the bottom of the panel, you should see a Base map layer.  Click on the drop-down arrow to the right of the Base map layer and note the various base map styles that are available.  A light base map can be preferable for many mashups like this one as it allows the data you want the viewer to focus on to stand out.
  17. Click on the title (Untitled map), enter something appropriate, such as Where I've lived (your name), and click Save.
  18. Click on the Share button in the upper right of the map.  In the Who has access section of the dialog, you should see that the map is Private and that you are the owner.
  19. Click the Change link and on the next dialog, set the map's visibility to either Public on the web or Anyone with the link, whichever you prefer.  (The main difference between the two is that the Public option makes the map discoverable by search engines.)
  20. Click Save to commit your visibility selection.
  21. Note that the URL of your map can be found at the top of the Sharing settings dialog.  You'll need to provide a link to the map later as part of the lesson deliverables.  Here [https://mapsengine.google.com/map/edit?mid=zJSuQ4KMi644.kxjDn-h_k5Qc] is where the course author has lived.
  22. To confirm that others will be able to see your map, try opening the URL in another browser (e.g., use Chrome if you're currently working in Firefox, or vice versa).

With that, you've produced your first web map of the class!  Before moving on to Maps Engine, here are a few miscellaneous notes about Maps Engine Lite:

  • It's possible to view/edit the data associated with a layer by clicking the Data button.
  • You can have up to 3 layers per map.
  • It is possible to manually digitize points, lines or polygons using the tools just to the right of the main panel.  
  • Lines and polygons can only be added to a map using the digitizing tools.
  • Spreadsheet uploads are limited to 100 rows each.

Google Maps Engine

Waiting for our educational grant application to be accepted before we can try this out... frown

In a nutshell, Maps Engine does not have the same limitations imposed with Maps Engine Lite.  It provides tools for importing an unlimited amount of point, line and polygon vector data and raster data in a number of formats, including shapefiles.  Map authors can then mix and match layers to produce the desired map.  Maps Engine certainly appears to be Google's answer to Esri's ArcGIS Online -- which you will be working with in just a moment.

ArcGIS Online

As with Google's mapping engines discussed above, Esri's ArcGIS Online [http://arcgisonline.com] allows users to build multi-layer mashups without the need for programming.

  1. From the Penn State GIS home page at ArcGIS Online [http://pennstategis.maps.arcgis.com/], click on Map to begin work on a new map.

    If you completed GEOG 483, your first hands-on GIS project involved helping "Jen and Barry" find the best place to open an ice cream shop in a parallel universe where the cities and counties of Pennsylvania have different names.  smileyWe're going to work with the data from that scenario again here (and in Lesson 3), since it contains examples of each geometry type and some good attribute data for demonstration purposes.
  2. Download the Jen and Barry's data.

    This zip file contains a point shapefile (cities), a line shapefile (interstates) and two polygon shapefiles (recareas and counties).  You can check out these shapefiles if you haven't encountered this scenario before, but hang on to the zip file since we'll be uploading it to ArcGIS Online.
  3. In ArcGIS Online, click the Add menu, then select Add layer from file.  

    As explained in the dialog, this option enables you to upload zipped shapefiles, delimited text files and GPX (GPS interchange) files.
  4. Click the Browse button, then navigate to your copy of the Jen and Barry's data.
  5. Accept the default Generalize features option.  

    We're importing these data purely for display purposes, so it makes sense to take advantage of the improved drawing speed that generalization provides.  If we were conducting analysis that relied on feature geometries, we would select the Keep original features option instead.
  6. Click Import Layer to complete the upload process.  

    After ArcGIS Online has finished reading in the data, you should see the four Jen and Barry's layers drawn on top of a topographic base map.  You should also see a jb data entry under the Contents heading of the Details panel.
  7. Click on jb data to expand the list of layers.  (Our data layers are housed within the jb data group layer because we uploaded them all in one zip file.  If you wanted to avoid having the layers grouped in this way, you would need to upload each shapefile in its own zip file.)

    Now, let's take a few moments to explore the symbolization options available in ArcGIS Online.
  8. Click on the dropdown arrow next to the cities layer and select Change Symbols

    Note that the layer is currently being displayed using A Single Symbol and that it's also possible to display it using Unique Symbols (by category), Color (by range) and Size (also by range).  Let's stick with the Single Symbol option and simply change that single symbol.  
  9. Click Change Symbol and select any icon that grabs you.  Note that there are a number of icon categories, that it is possible to customize the icon's size and that you can also use your own icon.
  10. Click Done after you've finished selecting an icon.  
  11. Click Done Changing Symbols to return to the Details panel.
  12. Expand the list of layers in the jb data group again and select the Change Symbols option associated with the interstates layer.
  13. Choose options from the dropdown lists so that you UseUnique Symbols To show: TYPE.

    You should see a separate symbol for each of the two unique values in the TYPE field: State Route and Interstate.
  14. Modify the two symbols to your liking.  (A thicker line is intuitive for the Interstate features.)
  15. Again, click Done Changing Symbols to return to the Details panel when you're finished symbolizing the interstates layer.  
  16. Following the same sort of procedure, set the symbology of the counties layer so that the county features are drawn using a hollow fill.

    While thinking about symbolization, you may want to experiment with the Color and Size options, used to symbolize features based on a range of values in a numeric field.  Unfortunately, at the time of this writing, these options did not appear to work.

    Next, let's explore the pop-up windows that appear when the user clicks on a map feature.
  17. Click on one of the cities features to bring up a pop-up window.  

    Because the cities features overlap counties features, the pop-up results will include features from both layers.  You should see text at the top of the window like "1 of 2" or "1 of 3" indicating this.  
  18. Click on the right arrow to cycle through the pop-up results and note that the matching feature is highlighted on the map.

    There are a number of improvements that could be made to the information displayed in this pop-up.  
  19. Click the dropdown arrow next to the cities layer and select Configure Pop-ups.

    Values from columns in the layer's attribute table are displayed in the pop-up by enclosing the column within braces.  Thus, the Pop-up Title is set to display the value from the layer's NAME column using the expression {NAME}.
  20. Click on the Configure Attributes link just below the list of fields.
  21. Uncheck the checkboxes next to the FID, ID, X and Y fields to exclude those values from the pop-up content.
  22. Click on the TOTAL_CRIM field alias and give it a new alias that makes the pop-up more human friendly.  Do the same for CRIME_INDE.

    The POPULATION, TOTAL_CRIM and UNIVERSITY values display with two digits after the decimal point, but that is meaningless for those fields.  
  23. Click on the {POPULATION} field, then change the Format option from 2 decimal places to 0 decimal places.  Do the same for {TOTAL_CRIM} and {UNIVERSITY}.
  24. Click OK to dismiss the Configure Attributes dialog, then SAVE POP-UP.  

    Test your changes by clicking once again on a cities feature.

    Note that it is also possible to customize pop-ups further (e.g., to string together values from multiple columns) or to display media such as images and charts.

    As with Google's products, it's also possible to utilize a different base map.
  25. Click on the Basemap button and choose one of the options.  (Again, a light base map is often preferable to a dark one, since your layers will stand out better.)
  26. Save your work by going to Save > Save as.  
  27. To make it easy for me to find your map, please give it a Title of Jen and Barry - <your name>.
  28. Enter a logical Tag or two (e.g., 863) and an appropriate Summary (e.g., A map for GEOG 863, Project 2), then click SAVE MAP.
  29. Finally, make your map visible to others by clicking Share.
  30. Set the map's visibility to either Everyone (public) or Penn State Online Geospatial Education, whichever you prefer.  
  31. To confirm that others will be able to see your map, try opening the URL in another browser (e.g., use Chrome if you're currently working in Firefox, or vice versa).

    Note that other ways of publishing your map include embedding it in another web page and creating a web application.  Esri provides a number of web application templates that serve a number of end-use purposes.  For example, there is a template for creating an editing application, one for a filtering application and one for comparing multiple maps, among many others.

While these non-programming options may meet your needs in some situations, it's possible that they will lack the full functionality you're looking for in other situations. The Google Maps API (and Esri's web mapping APIs, which we'll explore later) make it possible to build applications that go beyond what can be done with the Maps Engine and ArcGIS Online. Let's begin by taking a look at the Google Maps API Reference.

Orientation to the Google Maps API Reference

Google provides web developers with a number of APIs (Application Programming Interfaces) for building geospatial web applications [https://developers.google.com/maps/?csw=1].  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: one for browser-based Google Earth pages, one for static, non-interactive maps, one for web services that can be used to retrieve useful geographic data (such as the coordinates of a street address), and one for retrieving information about places.

Before digging into the Maps API documentation, it is important to note that we will be working with Version 3 and not Version 2.  While it is still possible to build new map sites utilizing V2, that version is now listed as deprecated by Google.  This is basically an advance warning to switch to the new version.  V2 includes many classes whose names begin with the letter "G" (such as GMap and GMarker), so if you come across any code with such class names, you can be sure that it is V2 code.

The V3 documentation homepage [https://developers.google.com/maps/documentation/javascript/] explains that the Maps JavaScript API is free to any developers who want to create maps that are free to consumers. Those who wish to create maps for use on an intranet or for profit are directed to the Google Maps API for Business site  [https://developers.google.com/maps/documentation/business/guide].

The links in the upper-left corner of the free API page include a developer's guide, reference pages for the object classes that make up the API, code samples, and more resources, which include articles of interest to developers, known bugs in the API, a log of changes that have been made to the API and a utility library.  If you click on the Developer's Guide link, additional options appear in the navigation pane (why they're not available on the documentation homepage, I don't know).  These include links to the API blog, a forum for the developer community to help one another and an FAQ.  I highly recommend doing a search of the forum any time you have questions about some part of the API.

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 "Hello, World" section of the API Tutorial page [https://developers.google.com/maps/documentation/javascript/tutorial#HelloWorld].  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 [https://code.google.com/apis/console] 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 APIs Dashboard.  The first thing we'll do is specify that we're using the API key with the Maps API v3.
  3. Click on the Services link.
  4. Scroll down through the list of available services and set Google Maps API v3 to ON.  Now we can move on to obtaining an API key.
  5. Click on the API Access link.  
  6. Under the Simple API Access heading, click the Create new Browser key button.  You will be presented with a Configure Browser Key dialog box.
  7. 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/*

    note An API key was required in previous versions of the Google Maps API. You don't really need an API key when working with version 3 for personal use, 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).

     

  8. 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.

  9. Open Notepad or another plain text editor.
  10. Return to the tutorial page and copy and paste the "Hello, World" code into your text editor.
  11. Now go back to the console page and copy your API key.
  12. 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.
  13. Later in the script element, find the string sensor=SET_TO_TRUE_OR_FALSE.  Replace the SET_TO_TRUE_OR_FALSE text with the value false.  (According to the documentation, this parameter is used "to indicate whether this application uses a sensor to determine the user's location."  If you were developing a map application for use on a mobile GPS-equipped device such as an iPhone, you might set this parameter to true.)
  14. Save the file as lesson2.html.
  15. Upload your lesson2.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]/lesson2.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.

One page element that may be unfamiliar to you is the <meta> tag. This tag is used to specify metadata about the document. In the case of this start-up page from Google, the <meta> tag is being used to tell mobile devices that the page should be loaded at its default scale (i.e., not zoomed in or out at all) and that the user should not be able to change the page's scaling.  These settings are essentially ignored by desktop browsers.

For future reference, keep in mind that the <meta> tag can also be used to improve the document's visibility to search engines, to force the browser to automatically refresh the page after a given time interval, or to redirect the browser to a different URL (e.g., if a site's URL has changed).

The next block of code 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.

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.  We saw earlier in the lesson that how you set the sensor parameter at the end of this URL depends on whether the application will be expected to display real-time positions of a GPS-enabled device.

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 tutorial (http://www.w3schools.com/js/default.asp) that should do the job. Take a couple of hours to work through the topics in the JS Basic section of the tutorial and pay particular attention to the following points:
  • Ending statements with a semicolon is optional. (The start-up script from Google uses semicolons.)
  • 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.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 re-usable blocks of code with an optional return value (i.e., there is no separate Sub concept as in VB).
  • 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 three 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 LatLng.  If you wanted to, you could develop your own class named LatLng, but you need a way to distinguish between your class and Google's.  That's where namespaces come in.  To use Google's LatLng 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 name 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 three property/value pairs: a zoom property, which is set to a value of 8; a center property, which is set equal to an object of the LatLng class; and a mapTypeId property, which is set to display a road map.  The object literal is stored in a variable called mapOptions for use in the next line of the script.

Learn More To see the other properties, return to Google's Tutorial page and follow the API Reference link near the top of the page.  Under the Reference Table of Contents, click on the Map Options link and scan over the available properties.

That next line 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 and has been defined to take up 100% of its parent container (the body element) in both height and width using in-line CSS.

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 myOptions 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 tutorial (http://www.w3schools.com/htmldom/default.asp) on this topic. 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 [https://developers.google.com/maps/documentation/javascript/reference].  Clicking on an API element under the Reference Table of Contents will re-direct 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), 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 Samples [https://developers.google.com/maps/documentation/javascript/examples/] and Demo Gallery [https://developers.google.com/maps/documentation/javascript/demogallery] can be quite helpful.

With that, you should have a basic understanding of how Google's sample JavaScript code works. 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 later in the HTML document as part of the <body> tag. The HTML DOM defines a number of events that can be used by programmers to control a page's behavior. These events are listed at http://www.w3schools.com/jsref/dom_obj_event.asp.

This Hello World example specifies that the JavaScript initialize() function that we just dissected should be executed in response to the page's onload event being triggered.

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.

Challenge Before moving on to the next page, there are at least two examples of sloppy coding in the Hello World page. If you think you know what they are, post a message to the Lesson 2 Discussion Forum.

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 [https://developers.google.com/maps/documentation/javascript/reference] and follow the link to the Marker part of the page.  (Marker is the first class under the Overlays heading.)

    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.

    We saw the LatLng class used in the Hello World example to specify the map's center. Let's see what the documentation says about it.

  3. Follow the LatLng link to jump to its section.

    The LatLng class constructor lists two required parameters (lat and lng). As we've already seen, 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 lesson2.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 create two LatLng objects with the same coordinates, let's create the object once, store a reference to that object in a variable, then use the variable to set both the map's center and the marker's position.
  5. After the creation of the Map object, add the following line to create a new LatLng object and store a reference to it in a variable called latlng:

    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 marker = 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 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 myOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644),
    mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var myMap = new google.maps.Map(document.getElementById("map_canvas"),
    myOptions);

    var myLatLng = new google.maps.LatLng(-34.397, 150.644);
    var myMarkerOptions = {
    position: myLatLng,
    map: myMap
    }

    var marker = new google.maps.Marker(myMarkerOptions);
    }

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.

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 in residence), 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 [http://geonames.usgs.gov/] or the Getty Thesaurus of Geographic Names [http://www.getty.edu/research/tools/vocabulary/tgn/index.html] (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 lesson2.html page so that the map is centered on and a marker points to your hometown. In modifying the page, you'll need to alter two identical sets of coordinates. If you've done much programming, you should 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 script so that it no longer suffers from this deficiency. 

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

Deliverables

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. Include on your project page or your index page links to your Google Maps Engine Lite and ArcGIS Online maps. (20 of 100 points)
  4. Find a GIS mashup that catches your eye and write a short review of it in the Lesson 2 Discussion Forum. (20 of 100 points)
  5. Complete the Lesson 2 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.

Concept Gallery

A Brief History of HTML

As students in Penn State's online GIS program, you have been sharing your work in the program through hyper-text markup language (HTML) files. HTML is a language that enables document authors to specify the structure of a document's content so that it can be rendered appropriately in a browser. Though the earliest incarnation of HTML was semantic (i.e., focused on defining a document's structure and not its presentation details), before long a number of presentational elements were added so that authors could create more aesthetically pleasing documents for viewing on desktop computers in browsers like Netscape Navigator and Microsoft Internet Explorer. Examples of such presentational elements included the <font> tag and the align and size attributes. Unfortunately, mixing document content with presentational elements often causes problems when the document is viewed by user agents like handheld computers, mobile phones, and aural devices that read text aloud for the sight impaired.

For this and other reasons, the international organization that develops HTML standards - the World Wide Web Consortium (W3C) - now discourages the use of such elements in the current version of HTML (4.01). Instead, the W3C promotes separating content from presentation style through the use of Cascading Style Sheets (CSS). Using CSS, a document author can apply one style sheet for desktop display, a different one for printing, and still others for screen reading browsers, mobile phones, etc. You won't need to know more about CSS to succeed in this course. However, if you want to change font settings and text alignment in your pages according to W3C standards, you can learn more about CSS at the w3schools tutorial site [http://www.w3schools.com/css/default.asp].

Going beyond HTML with XML

While HTML is capable of displaying the majority of the content that is typically published online, it can't handle everything. For example, it does not provide adequate tags for displaying mathematical notations, chemical formulae, or musical scores. To address these shortcomings, the W3C could have attempted to add numerous tag sets to HTML. What they did instead was develop the Extensible Markup Language (XML). XML is actually a metalanguage, a language that can be used to define the rules of other languages. It enables anyone who understands XML syntax to create custom languages tailored to their content. Using XML, mathematicians developed MathML, a language that allows them to display formulae with familiar notations. For example, the <msqrt> tag can be used to specify a square root symbol. Likewise, musicians developed MusicXML with tags like <measure>, <note>, and <pitch> to enable them to share musical scores.

The rules that govern XML-derived languages can be found in the language's associated document type definition (DTD) file or in an XML schema definition (XSD) file. As with CSS, the creation and usage of these files is outside the scope of this course. Again, the w3schools site [http://www.w3schools.com/xml/default.asp] is a good place to learn more.

Whereas a DTD file defines the rules of an XML-based language, an XML document contains actual content organized according to those rules. For example, you might create a DTD file that defines a tag set for storing information about your music collection. Such tags might include <title>, <artist>, and <year>. You could then create an XML document based on your custom language that looks something like this: http://www.w3schools.com/xml/cd_catalog.xml

Reining in HTML with XHTML

One of the W3C's larger undertakings has been to use XML to develop a stricter version of HTML called XHTML. Years ago, when HTML documents were consumed almost exclusively by desktop web browsers, these web browsers were written to correct documents that contained errors. For example, a document author could omit the </p> tag at the end of a paragraph and the document would still be rendered correctly. Such flexibility is still written into browser software by vendors who don't want their browsers to be too "picky" in how they render web pages. Today, however, HTML content is being consumed by much more than desktop web browsers. User agents such as handheld computers and mobile phones have limited resources and cannot afford to expend those resources on interpreting and rendering poorly coded content. The stricter rules laid down by XHTML make it possible for vendors to build more efficient parsing software into their limited-resource devices.

The tag set used in XHTML is virtually identical to that found in the current version of HTML (4.01). However, the stricter rules that distinguish it from HTML include the following:

  • All elements must have end tags. If you've done much HTML coding, you've probably noticed that the </p>, </li>, </td>, and </tr> end tags can be omitted. In XHTML, you must include such end tags to produce a well-formed document.
  • Element attribute values must be quoted. For example, when setting a table element's rows attribute to 3, the 3 must be enclosed in quotes: <table rows="3">. The quotes can be either single or double.
  • Nested elements must be ordered correctly. If one element is found within another element, the inner element's end tag must appear before the outer element's end tag. This is one of the errors that web browsers typically correct when encountered in an HTML document.
  • Empty elements (i.e., those HTML elements that have just a start tag and no end tag, such as (<img> and <br>) must be closed explicitly. This can be done by adding a separate end tag (</img> or </br>) immediately after the start tag or by inserting a slash in the start tag (<img /> or <br />).
  • All tag and attribute names are case sensitive. In HTML, <a> and <A> are the same tag. In XHTML, they are different tags. XHTML uses lowercase for all of the tags and attributes defined in HTML.
  • All text and images should be contained inside a <p> or <div> element.

Creating an XHTML document

When creating an XHTML document, the first step is to specify the document type using the DOCTYPE directive. XHTML actually has three dialects that are defined in three separate DTD files: "strict", "transitional", and "frameset". The strict DTD excludes all of the elements that were deprecated with the release of HTML 4.0 (e.g., the <font> tag and align attribute), while the transitional DTD allows their use. The frameset DTD is for those who wish to write XHTML that includes frames.

To use the strict DTD, you begin with the following DOCTYPE directive:

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

 

To use the transitional DTD:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

And the frameset DTD:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-framset.dtd">

 

The string that appears after the keyword PUBLIC is an identifier for the DTD that the user agent parsing the document may or may not recognize. In case it doesn't recognize the identifier, the second text string is used to explicitly specify the URL of the DTD.

The second key step in creating an XHTML document is to specify the namespace that contains the tags you want to use in your document. Namespaces are used in XML to account for the possibility that a document may make use of multiple languages and that certain elements or attributes in those languages could be duplicated. For example, both XHTML and MathML contain a <div> tag. Document authors who want to use both the XHTML tag set and the MathML tag set in a document can specify the XHTML namespace when they want to use the XHTML version of the tag and the MathML namespace when they want to use the MathML version of the tag.

Namespaces are specified using the xmlns attribute. This attribute can be included within any tag in your document, but it is typically used with the <html> tag at the beginning. For example:

<html xmlns="http://www.w3.org/1999/xhtml">

 

If tags from another namespace are required, that namespace is typically referenced in the <html> tag also, along with a label that can be used to refer to that namespace throughout the document. For example, one could use both the XHTML tags and MathML tags as follows:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:math="http://www.w3.org/1998/Math/MathML">

 

In a document with this namespace definition, the "math" abbreviation could be used wherever a conflicting tag is required. For example, an author could ensure that the MathML <div> tag is used instead of the XHTML <div> tag as follows:

<math:div>x/y</div>

 

A basic XHTML document

Assuming one needs only the tags defined in the XHTML DTD, the basic skeleton of an XHTML document looks like this:

<!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>
<title>Your title here</title>
</head>
<body>
<p>
Your content here
</p>
</body>
</html>

 

As noted above, XML is a metalanguage that can be used to create new markup languages. MathML, MusicML, and XHTML are three examples of languages developed based on the XML standard. The rules that govern each of these languages are found in the language's associated document type definition (DTD) file. XHTML actually has three dialects that are defined in three separate DTD files: one that is strict, another that is transitional, and a third that is for using frames. For example, the strict XHTML DTD file can be found at http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd. (Open this file in a text editor like WordPad.) The syntax used in this file to define elements and their attributes in a DTD file is beyond the scope of this course. However, if you scroll about one-third to half-way down the document, you should see several familiar HTML tags defined, including the heading tags and the list tags.