Finding Yourself Using Geolocation and the Google Maps API

I recently published an article titled “Finding Yourself Using Geolocation and the Google Maps API” in the Association for Computing Machinery’s Student Magazine, XRDS.  As the title implies, the article focuses on the geolocation API and Google’s Maps API.  I hope you enjoy it…

Today, many websites are able to access a visitor’s physical location and generate pages specifically tailored to their surroundings.  Some examples might include providing driving directions or locating nearby landmarks.  The process by which a site determines a user’s physical location is called geolocation.  The World Wide Web Consortium (W3C), a standards organization for the web, has created a geolocation API that defines a JavaScript interface which can be utilized in modern HTML5 capable browsers.

In this article an example web page is created which uses geolocation, in conjunction with Google’s Maps API, to generate and display driving directions on a map and in textual format.  When the page is loaded, the user’s current physical location is displayed on a map.  When the user clicks on the map, driving directions are generated starting from the current location and ending at the clicked location on the map.

Geolocation Prerequisites

The geolocation API is not yet supported by all browsers.  In order to run the example in this article, you will need a browser which supports geolocation.  This example uses Firefox 12.0, which can be downloaded for free from Mozilla.  Another thing to note is the issue of privacy arising from sharing a user’s physical location.  When the example page is loaded, you will notice that the browser must first get explicit consent from the user before sharing their location.  Figure 1 shows the dialog box used by Firefox to get the user’s consent.

Firefox Geolocation Permission Dialog Box

Figure 1: Firefox requesting permission to share the user's location.

Web Page Setup

First, we need to create the HTML file that will contain the map and directions.  Listing 1 shows the HTML source for our example page.  The DOCTYPE on line 1 instructs the browser to render the page according to HTML5 standards.  In the document’s head, two external JavaScript files are included.  The first file, included on lines 6-8, is the Google Maps API.  This is the file that provides the mapping functionality.  Luckily, Google has already done most of the hard work with this file.  Notice that the source URL takes a parameter named “sensor”.  For our purposes this is set to false.  Line 9 includes a second JavaScript file, helloWorld.js, which we will create later.  This is where our application’s functionality is going to be implemented.

Two <div> elements are defined in the page’s body on lines 12-15.  The element named “map_canvas” is where the map is going to be displayed, while the “dir_panel” element will show the corresponding text directions.  The “style” attributes of the <html>, <body>, and <div> elements ensure that the document is sized and displayed properly.

 1: <!DOCTYPE html>
 2: <html lang="en" style="height:100%; width:100%;">
 3:   <head>
 4:     <title>Geolocation and Google Maps Example</title>
 5:     <meta charset="UTF-8" />
 6:     <script
 7:       src="http://maps.googleapis.com/maps/api/js?sensor=false">
 8:     </script>
 9:     <script src="helloWorld.js"></script>
10:   </head>
11:   <body style="height:100%; width:100%; margin:0; padding:0;">
12:     <div id="map_canvas"
13:          style="float:left; width:75%; height:100%;"></div>
14:     <div id="dir_panel"
15:          style="float:right; width:25%; height:100%;"></div>
16:   </body>
17: </html> 

Listing 1:  HTML source for the example page.

Geolocation Lookup

The next step is to actually create the helloWorld.js file.  First, we need to add a function that will perform a geolocation lookup when the page is loaded.  Listing 2 shows the JavaScript code that implements this functionality.  On line 1, an anonymous function is attached to the page’s “load” event.  This ensures that our code is called each time the page is loaded.  The “if” statement on line 2 determines whether or not the browser supports geolocation by checking for the existence of the “navigator.geolocation” object.  If geolocation is not supported then the error message on line 8 is shown.

If the browser does support geolocation then the getCurrentPosition() function is called on line 3.  As the name implies, this function attempts to determine the user’s physical location.  The getCurrentPosition() function takes two callback functions as arguments.  The first argument is a function that is executed if the user’s location is determined successfully.  In this example, the success callback function is named showMap().  We’ll return to showMap() shortly.

During a geolocation lookup, any number of things can go wrong, resulting in a lookup failure.  The second callback function passed to getCurrentPosition() is used to handle lookup failures.  Lines 4-6 show the error callback function for the example page.  For this example, a simple error message is shown if the user cannot be located.

1:  window.addEventListener('load', function() {
2:    if (navigator.geolocation)
3:      navigator.geolocation.getCurrentPosition(showMap,
4:        function(error) {
5:          alert('Cannot determine your location!');
6:        });
7:    else
8:      alert('Your browser does not support geolocation!');
9:  }); 

Listing 2:  JavaScript function to perform geolocation lookup.

Displaying the Map

If geolocation succeeds, the showMap() function is called.  The code for showMap() is shown in Listing 3.  The first thing to point out is the “position” argument.  This is an object that contains the user’s physical location defined in terms of latitude and longitude.  The variable assignments on lines 2 and 3 are used to store the these coordinates.  The “latlng” variable, declared on line 4, is an object in the Google Maps API that represents the user’s location.

The variable “mapOpts”, declared on lines 5 and 6, is a JavaScript object literal.  The Maps API makes extensive use of JavaScript objects for passing arguments due to their simplicity and flexibility.  In our example, “mapOpts” is used to create a Hybrid style map (street names overlaid on satellite imagery) which is centered on the user’s coordinates and zoomed in by a factor of 15.  The “canvas” variable on line 7 corresponds to the <div> element where the map will be displayed.  The map is created on line 8.  Lines 9 and 10 create a marker on the map at the user’s location.  Since the map is centered on the user’s location, the marker appears in the middle of the map.

Next, we will allow the user to generate driving directions by clicking on the map.  First, we need to create two Maps API objects, a DirectionsService and a DirectionsRenderer.  The DirectionsService declared on line 11 provides routing directions, while the DirectionsRenderer on line 12 displays the directions on the map and in the directions panel.  On line 13, a reference to the “dir_panel” element is stored in the “panel” variable.  Lines 15 and 16 tell the DirectionsRenderer where to display the graphical and textual directions, respectively.

The final step in the example is to add an event listener to the showMap() function.  This will allow the directions to update automatically when the user clicks on the map.  To do this, the addListener() function is called on line 17.  The arguments passed to addListener() are the map object, the type of event (“click” in this case), and a function that processes the event.  On line 18, the event handler calls the route() function of the DirectionsService.  The first argument passed to route() is an object literal containing the user’s current location, the travel destination stored in the “latLng” field of the “event” argument, and the travel mode, which is driving in our example.  The second argument passed to route() is a function that handles the routing information returned by the DirectionsService.  On lines 21 and 22, this function checks that the directions were properly created and then tells the DirectionsRenderer to display them.

 1: function showMap(position) {
 2:   var latitude  = position.coords.latitude;
 3:   var longitude = position.coords.longitude;
 4:   var latlng    = new google.maps.LatLng(latitude, longitude);
 5:   var mapOpts   = {zoom: 15, center: latlng,
 6:                    mapTypeId: google.maps.MapTypeId.HYBRID};
 7:   var canvas    = document.getElementById('map_canvas');
 8:   var map       = new google.maps.Map(canvas, mapOpts);
 9:   var marker    = new google.maps.Marker({position: latlng,
10:                                           map: map});
11:   var dirServ   = new google.maps.DirectionsService();
12:   var dirDisp   = new google.maps.DirectionsRenderer();
13:   var panel     = document.getElementById('dir_panel');
14:
15:   dirDisp.setMap(map);
16:   dirDisp.setPanel(panel);
17:   google.maps.event.addListener(map, 'click', function(event) {
18:     dirServ.route({origin: latlng, destination: event.latLng,
19:                    travelMode: google.maps.TravelMode.DRIVING},
20:       function(result, status) {
21:         if (status === google.maps.DirectionsStatus.OK)
22:           dirDisp.setDirections(result);
23:       });
24:     });
25: } 

Listing 3:  JavaScript function to display a map and driving directions.

Conclusion

By following the steps outlined in this article you have just created a non-trivial, location aware web page.  By utilizing Google’s Maps API, we were able to create the page in approximately 50 lines of HTML and JavaScript code.  Figure 2 shows the example page being used to navigate downtown Pittsburgh, Pennsylvania.  If you would like to use the example page while on the go, it is available online at http://www.cjihrig.com/development/html5/map.htm.

Geolocation and Google Maps Example Page

Figure 2: Example of the finished web page.

Legal Disclaimer

© ACM, 2012.  This is the author’s version of the work.  It is posted here by permission of ACM for your personal use.  Not for redistribution.  The definitive version was published in XRDS:  Crossroads, The ACM Magazine for Students, Volume 19, Issue 1, Fall 2012, http://doi.acm.org/10.1145/2331042.2331065.


Comments are closed.