Showing a map on your page

As you learned in your first tutorial about Google Maps, there are three steps to putting a map on your page:

    • In the HTML file, add a <script> tag that refers to the API (it contains your API key as well).
    • Add an element div with an attribute id.
  1. In the CSS file, write a rule for the id of the map and set the width and height properties. You can use % to have the map shrink with the page, or pixels, to have the map with a fixed size.
  2. In the Javascript file:
    • Create a global variable map, so that you can refer to it everywhere in the code.
    • Have a function initialize that first creates an object to specify options for the map (zoom level, map center, map type), and then invoke the constructor method that creats the map and places it on the div of the HTML page.
    • Register the function initialize to be invoked when the window is loaded:
      google.maps.event.addDomListener(window, 'load', initialize);

Finding the geo-coordinates of a location

To show markers on a map, we need to know their position, e.g., the latitude and longitude. While we can find these values by consulting web resources manually, we want an automatic way that does it for us in the context of an application. For this, we will use the google.maps.Geocoder object of the Google Maps Javascript API. Below is an example for how to use it.

  // Step 1: create a global variable
  var geocoder;
  
  // invoke the constructor inside "initialize", because we need the API to have been loaded
  function initialize(){
    // ...
    geocoder = new google.maps.Geocoder();
    // ...
  }
  
  // define a function that will call the "geocode" method with some arguments
  // and specify the callback function
  function findLocation(aName){
    geocoder.geocode( { 'address': aName}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        console.log("Result: ", results[0].geometry.location);
      }
    });
  }

You can find a live example of the geocoding service in this jsFiddle I created. Open the console to see the result value, which is an google.maps.LatLngobject. Try out the example with different location names, cities, countries, institutions.

You can read about the parameters of the .geocode() method and the information contained in the response in the Geocoding service in Javascript.

Calculating distances between locations

With the newest version of the Google Maps Javascript API it is very easy to calculate distances between multiple points at once. We will use the object google.maps.DistanceMatrixService and its dedicated method .service(). This method takes as parameters a list of origins, a list of destinations, and some other optional parameters and returns distances between all pairs of origins and destinations. Below is an example of how to invoke this method:

var service = new google.maps.DistanceMatrixService();

service.getDistanceMatrix({
    origins: originsList, // an array of locations
    destinations: destinationsList, // an array of locations
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.IMPERIAL}, callbackFunctionName);

The locations in the arrays can be string addresses or LatLng objects.

See a demo in the Google Maps documentation.

Consult the documentation for the DistanceMatrix service.

Finding a user's location

HTML5 has a Javascript API that can be used to find the current location of a user.

Try out this demo to see how accurately this API finds your current location and then shows it on a Google Maps, using the Google Maps API.

The most important piece of code that makes this possible, if the following method invocation:

 navigator.geolocation.getCurrentPosition(function(pos){console.log(pos);})      
       

If you copy the following piece of code on your console, allow the browser to access your location (see message under location bar), you should be able to get a response like the screenshot below (I have blanked out the details of my exact location).

Once we have the lat/long value for a location, we can then display that on the map.

Contribution Challenge: Track a user movement

You could use the setInterval method that we explained in the AM3 Divide and Conquer notes, to poll the location of a user as they move (if they have a mobile device).

Chapter 5 of the book HF HTML5 Programming can give you more details on this.

Challenge yourself and contribute to the class by writing a simple app that shows the places where a user has been within 30 minutes.

A greater challenge would be to store the values of their path and send them to a server for future reference. For example, if you want to show a shortcut to a location, by following a path suggested by someone else. You can use a POST Ajax method (or $.postJSON()) to store the data on a server (where you have a simple PHP script) and then $.getJSON() to retrieve the data and draw a path on the map.