Harvard Extension School
CSCI E-12 Fundamentals of Web Site Development | Fall 2019

## Google Maps JavaScript API

There is extensive documentation for the Google Maps JavaScript API, at
https://developers.google.com/maps/documentation/javascript/tutorial that you can consult. But for now, it will be enough to walk through some examples.

We'll learn by example with a

- basic map
- map with a marker
- map with a marker with an information window
- map with several markers

### Basic Map

So first, we'll start with a map that is centered on the John Harvard statue in Harvard Yard.

To use the Google Maps JavaScript API, we'll need to load the Google Map JavaScript via a `script` element, and then we'll need to configure the map and then place it on the page.

Load the JavaScript:

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"> </script>

Use the JavaScript:

    var map;
    /* John Harvard Statue
       42.374474,-71.117207 */
    var mylat = 42.374474;
    var mylng = -71.117207;
    function initialize_map() {
        var mapOptions = {
            zoom: 17,
            center: new google.maps.LatLng(mylat, mylng)
        };
        map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);
    }
    google.maps.event.addDomListener(window, 'load', initialize_map);

- Latitude and Longitude of the John Harvard statue is (42.374474,-71.117207)
- `google.maps.event.addDomListener` is the Google Maps way of adding an event handler.
  In this case, the event is the "load" event of the "window", and the handler is the function `initialize_map`
- In the `initialize_map` function:
  - `mapOptions` is a JS data structure. `zoom` level is how close (larger is closer)
  - `google.maps.LatLng` is the method that creates a Google Maps LatLng object. In this case, we are setting the center of the map to the location of the John Harvard statue
  - `google.maps.Map` is the method to create a Google Map. We pass in as parameters where to place it on the page (note the DOM method, `document.getElementById`), and the second parameter is the data structure of map options

Full example:

Basic Map working examples:

- Basic Map - Live example
- Basic Map - JS Fiddle

Copyright © David Heitmeyer