In Lesson 3, you'll be exposed to the "Hello, World" page of the Google Maps JavaScript API. Hello World programs [1] 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 [2] 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:
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:
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 Discussions tab within Canvas.)
Lesson 3 is one week in length. (See the Calendar in Canvas for specific due dates.) To finish this lesson, you must complete the activities listed below. You may find it useful to print this page out first so that you can follow along with the directions.
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.
|
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 Canvas Homepage and click on the "Lesson 3 Quiz" link to begin the quiz. |
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 [3] so that you can follow along with the discussion below.
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:
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.
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 [4] [https://www.google.com/maps/place/State+College,+PA/ [5]@40.7880144,-77.8525714,14z/data=!3m1!4b1!4m2!3m1!1s0x89cea899c13bdb73:0x9ce1c6c2833c8091].
Looking closely at this URL, here are some points to note:
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 [6]
Stop Worrying About the New Google Maps; These URL Parameters Are Gold [7]
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.
Google provides web developers with a number of APIs [8] (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 [9] [https://developers.google.com/maps/documentation/javascript/] [10] is composed of 5 tabs:
Now that we've seen where Google Maps developers go for information about the API, let's begin developing our own maps.
The best way to build your first Google Map page is probably to use their "Hello, World" page as a starting point.
*.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).
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.
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.
After defining the page's title (Simple Map), the <head> of the document contains two <meta> elements. The first of these is concerned with rendering the document in a user-friendly way across a variety of devices (part of the larger CSS topic of responsive web design [13] [http://www.w3schools.com/css/css_rwd_viewport.asp]. [14] This is not critical for you to dive into now, but you may want to return to this topic if you are developing for mobile phones or tablets). The second meta element specifies that your document is encoded in the UTF-8 character set, one that supports all of the world's major languages. It's a good idea to include this line verbatim in all of your map pages. If you're an insomniac, you may want to read more about character encoding [15] [http://www.w3schools.com/charsets/default.asp] [16].
The next 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" has its height set to 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 soon see, 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. 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.
At this point, you should familiarize yourself with the syntax of JavaScript (JS). The w3schools site offers a good hands-on JavaScript tutorial [17] 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:
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 [18] in a new tab. The API Reference is a large page containing documentation on all of the entities built into the API. The Contents section at the top of the page (collapsed by default) provides links to the part of the page that deals with the associated entity (class, object specification or constant). For example, if you click on the Map class, you'll be redirected 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 [19] 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).
Once again, the w3schools site offers a good JavaScript HTML DOM tutorial [20]. 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:
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.
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.
Insert the following line to the end of the initMap() function:
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myMarkerOptions = { position: latlng, map: map }
var myMarker = new google.maps.Marker(myMarkerOptions);
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.
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 [23] or the Getty Thesaurus of Geographic Names [24] (for students outside the U.S.). If you have not taken that course, use those tools or any other resources at your disposal to find this information. (One handy way to get a location's coordinates is to pull it up in Google Maps, right-click on the location and select What's Here?)
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, in Canvas, for the due date.
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.
Links
[1] http://en.wikipedia.org/wiki/Hello_world
[2] http://www.gnu.org/fun/jokes/helloworld.html
[3] http://www.google.com/maps
[4] https://www.google.com/maps/place/State+College,+PA/@40.7880144,-77.8525714,14z/data=!3m1!4b1!4m2!3m1!1s0x89cea899c13bdb73:0x9ce1c6c2833c8091
[5] https://www.google.com/maps/place/State+College,+PA/
[6] https://mstickles.wordpress.com/2015/06/12/gmaps-urls-intro/
[7] https://moz.com/blog/new-google-maps-url-parameters
[8] https://developers.google.com/maps/?csw=1
[9] https://developers.google.com/maps/documentation/javascript/
[10] https://developers.google.com/maps/documentation/javascript/]
[11] https://developers.google.com/maps/documentation/javascript/tutorial
[12] https://console.developers.google.com
[13] http://www.w3schools.com/css/css_rwd_viewport.asp
[14] http://www.w3schools.com/css/css_rwd_viewport.asp].
[15] http://www.w3schools.com/charsets/default.asp
[16] http://www.w3schools.com/charsets/default.asp]
[17] http://www.w3schools.com/js/default.asp
[18] http://developers.google.com/maps/documentation/javascript/3.exp/reference
[19] https://developers.google.com/maps/documentation/javascript/examples/
[20] http://www.w3schools.com/js/js_htmldom.asp
[21] http://www.codeproject.com/Articles/307720/The-async-and-defer-Script-Attributes-in-HTML
[22] https://developers.google.com/maps/documentation/javascript/3.exp/reference
[23] http://geonames.usgs.gov/
[24] http://www.getty.edu/research/tools/vocabulary/tgn/index.html