Scripting languages in webcartography - Google Maps JS API

How does a usual "slippy web map" work?

Most zoomable-pannable web maps (including Google Maps JavaScript API, OpenStreetMap, etc.) based on a set of previously generated, tiled raster map images. These maps use the Web Mercator (EPSG:3857) projection. As poles are in infinite distance in this projection, the extent of maps is limited to approx. 85° North/South. This way the whole Earth can be mapped into a square.

Resolution of the map is determinde by the zoom value (z). At the smallest zoom (z = 0) the whole Earth fits into a single 256*256px square:

x=0 y=0 z=0

In higher zooms the world map consists of 2z * 2z tiles of 256*256px size. For example, if z = 1:

x=0 y=0 z=1 x=1 y=0 z=1
x=0 y=1 z=1 x=1 y=1 z=1

This map indicates the zoom numbe and tile numbers.

Using the API

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Google Maps JS API - Embedding the map</title>
        <script src="http://maps.google.com/maps/api/js"></script>
    </head>
    <body>
        <h1>Google Maps JS API - Embedding the map</h1>
        <div id="map_div" style="width:700px; height:500px"></div>
        <script>
            var mapOpts={
                center: new google.maps.LatLng(47.475, 19.062),
                zoom: 13
            }
            var map=new google.maps.Map(document.getElementById("map_div"), mapOpts);
        </script>
    </body>
</html>
        
Example 1: Embedding the map

Obtaining an API key

You are required to get an API key from Google to use Google Maps in your application. This key should be placed in the URL of the JavaScript API:

        <script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>
        
Obtaining an API key

As the new rules at Google require users to register a credit card to have the API key working, you can use the key of this tutorial during classes:

        <script src="http://maps.google.com/maps/api/js?key=AIzaSyAeuhKmbUK1bzmM_VGLIljqoHpCRoLa5iE"></script>
        

Customizing your map

The map interface can be customized by setting various map options when creating the map object. See possible map options in the reference.

The following settings will enable/disable a handful of map controls and limit the available map types to street map and relief map.

            var mapOpts={
                center: new google.maps.LatLng(47.475, 19.062),
                zoom: 13,
                streetViewControl: false,
                mapTypeControl: true,
                mapTypeControlOptions:
                 { mapTypeIds: [google.maps.MapTypeId.ROADMAP,google.maps.MapTypeId.TERRAIN] },
                zoomControl: true,
                scaleControl: true,
                mapTypeId: google.maps.MapTypeId.ROADMAP 
            }
            var map=new google.maps.Map(document.getElementById("map_div"), mapOpts);
        
Example 2: Customizing the map

Possible values of mapTypeId:

Localising a map

You can localise the map using the &language=LANG_CODE extension in the URL of the library. For example:

        <script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY&language=ar"></script>
        
Example 3: Localising the map

Handling mouse events

Event handlers can be defined using the google.maps.event.addListener() function. The first parameter is the object we want to listen - e. g. the Map object if we want to detect events of the map. The second parameter is the event type, e. g. 'click'. The third one is the listener function.

...
    google.maps.event.addListener(map, 'click', function(event) {
        // event handler code comes here. The 'event' object contains information about the event.
    });
...        
        

Your task is...

Add a mouse click event handler to your map, which sends the event object to the browser console. Observe the content of the event object.

Adding markers

Markers can be created using the google.maps.Marker() constructor. The minimum information required is the position and the map property. All the possible settings can be found in the reference.

...
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(47.475, 19.062), 
        map: map,
        title: "There is something here."
    });
...        
        

Your task is...

Add markers to your map by clicking on it: the mouse click event handler should create a marker at the click position.

Example 4: Click event and adding markers

InfoWindow

google.maps.InfoWindow objects can be used for creating "information bubbles" on the map. Properties can be set in an object that are handed as parameter to the constructor. An Infoindow can be opened and displayed using its open() method. InfoWindows are usually connected to markers.

Your task is...

Create a marker with an InfoWindow howing the position of the university campus (latitude: 47.4744°, longitude: 19.0621°).

Geocoding

We can send geocoding requests to Google using a google.maps.Geocoder object. Geocoding is done asynchronously: we send a request and set up a callback function that will be called with the results once they will have arrived.

        <h1>Google Maps JS API - Geocoding</h1>
        Enter an address: <input type="text" id="addrBox" />
        <input type="button" value="Find it!" onclick="findit()" />
        <hr/>
        <div id="map_div" style="width:700px; height:500px"></div>
        <script>
            var mapOpts={
                center: new google.maps.LatLng(47.475, 19.062),
                zoom: 13
            }
            var map=new google.maps.Map(document.getElementById("map_div"), mapOpts);
            var gc=new google.maps.Geocoder();
            
            // find an address
            function findit() {
                var addr=document.getElementById('addrBox').value;
                // sending geocoding request
                gc.geocode({address: addr},function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);
                        var marker = new google.maps.Marker({
                            map: map, 
                            position: results[0].geometry.location,
                            title: results[0].formatted_address
                        });
                    } else {
                        alert("Geocoding failed: " + status);
                    }
                });
            }
        </script>
        
Example 5: Geocoding

Your task is...

Observe the possible settings of a geocoder request and create a reverse geocoder: send the coordinates of the mouse click and display the address returned by the geocoder.

Elevation service

To use Google's elevation service we need to create a google.maps.ElevationService object. It has two different methods to use: the getElevationForLocations() method can be used to retrieve the elevation of standalone points while the getElevationAlongPath() method gives a series of elevation values along a given path.

        ...
            // create elevation service object
            var elev=new google.maps.ElevationService();
            // add click event listener
            google.maps.event.addListener(map, 'click', function(event) {
                // send elevation request
                elev.getElevationForLocations({locations:[event.latLng]}, function(results,status) {
                    if (status=='OK') {
                        // add a new marker at click position
                        var marker = new google.maps.Marker({
                            position: event.latLng, 
                            map: map,
                            title: results[0].elevation+"m"
                        });
                        // also add infowindow 
                        var iw=new google.maps.InfoWindow({content: results[0].elevation+"m"});
                        iw.open(map,marker);
                        // clicking on marker opens its infowindow
                        google.maps.event.addListener(marker, 'click', function() {
                            iw.open(map,marker);
                        });
                    }
                });
            });
        ...    
        
Example 6: Get elevations by clicking on the map

Your task is...

Create a web map that displays an elevation profile along a line using the getElevationAlongPath() method of the elevation service.

Hints:

Directions service

Google Maps also have a routing service. To use it we need to create a google.maps.DirectionsService object. Routing requests are sent by calling its route() method with an object containing routing parameters and a callback function. The minimum required settings are:

The parameters of the callback function are similar to the ones used for geocoding: a results array and a status string. If status is "OK", results is a google.maps.DirectionsResult object. The simplest way to display it is to use a google.maps.DirectionsRenderer object.

Your task is...

Create a route planner website.

Hints:

Example 7: Route planner

Ground Overlays

A ground overlay is an image stretched to a rectangular area of the map. Ground overlay can be added to Google Maps using the google.maps.GroundOverlay() constructor. The image can be in JPEG, PNG, GIF or SVG format. The opacity of the overlay can be adjusted by using the object's setOpacity() method.

Your task is...

Place this old map as a ground overlay between the 47.3456°, 47.8550° latitudes and 18.6086°, 19.2015° longitudes. Add a slider ( <input type="range" /> ) which adjusts the opacity of the overlay.

Example 8: Ground overlay

KML/KMZ overlays

It's also possible to add a KML or KMZ file to the map using the google.maps.KmlLayer class. The parsing of these files are done server-side, therefore the KML/KMZ file has to be specified with an absolute URL.

Example 9: KML overlay