My favorites | English | Sign in

More personalization in Google Friend Connect New!

Google Mapplets

Mapplet Services

Services Overview

The Google Mapplets API is regularly extended, adding new functionality and features that are often released on maps.google.com first. This section covers these services. Note: because the definition of a "service" is somewhat elusive, this section is somewhat of a catch-all. Basically, this section is where we put all of those neat things that we couldn't put anywhere else.

Storing User Preferences

The setprefs feature of the Google Gadgets API allows you store user state in-between sessions. To use it, your Mapplet should include:

  • A <Require feature="setprefs"/> tag (under <ModulePrefs>) to tell the gadget to load the setprefs library.
  • A <UserPref> tag inside the Mapplet spec whose value you want to set programmatically and store persistently. If you give this userpref a datatype of hidden, then the user will not be allowed to directly edit it.
  • A call to the _IG_Prefs(__MODULE_ID__) constructor. This object has methods for getting and setting preferences.

For more information on manipulating user preferences, see the Working with Userpref Data Types section of the Google Gadgets API documentation.

The following example has buttons for incrementing a counter and resetting the counter. If you reload the Mapplet, you'll notice that the value of the counter persists between sessions for that user.

<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs
    title="Set Userprefs Demo">
    <Require feature="sharedmap" />
    <Require feature="setprefs" />
  </ModulePrefs>
  <UserPref
    name="counter"
    default_value="0"
    datatype="hidden"/>
  <Content type="html">
  <![CDATA[
    <input type=button value="Increment Counter" onClick="incrementCounter();">
    <input type=button value="Reset Counter" onClick="resetCounter();">
    <div id="message" style="margin-top:1em"></span>

    <script>
     // Get user preferences
     var prefs = new _IG_Prefs(__MODULE_ID__);
     var message = document.getElementById("message");
     showCounter();

     // Show the current value of the counter
     function showCounter() {
       var counter = prefs.getInt("counter");
       message.innerHTML = "The counter value is " + counter;
     }

     // Increment value of "counter" user preference
     function incrementCounter() {
       var counter = prefs.getInt("counter");
       prefs.set("counter", counter + 1);
       showCounter();
     }

     // Reset value of "counter" userpref to 0
     function resetCounter(){
       prefs.set("counter", 0);
       showCounter();
     }
    </script>
  ]]>
  </Content>
</Module>

Run this example (setprefs.xml)

Geocoding

Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.

The Geocoding Object

You can access the Mapplets API geocoder via the GClientGeocoder object. Use GClientGeocoder.getLatLng() to convert a string address into a GLatLng. This method takes as parameters a string address to convert, and a callback function to execute upon retrieval of the address. The callback function is necessary since geocoding involves sending a request to Google's servers and can take some time.

In this example, we geocode an address, add a marker at that point, and open an info window displaying the address. Note that the callback is passed as a function literal.

var map = new GMap2();
var geocoder = new GClientGeocoder();
showAddress("76 9th ave new york");

function showAddress(address) {
  geocoder.getLatLngAsync(
    address,
    function(latlng) {
      if (!latlng) {
        alert(address + " not found");
      } else {
        map.setCenter(latlng, 15);
        var marker = new GMarker(latlng);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(address);
      }
    }
  );
}

Run this example (geocoding-simple.xml)

If you need to access the geocoder from outside a Mapplet, then please see the Geocoding via HTTP section of the standard Google Maps API.

Extracting Structured Addresses

If you would like to access structured information about an address, GClientGeocoder also provides a getLocations() method that returns a JSON object consisting of the following information:

  • Status
    • request -- The request type. In this case, it is always geocode.
    • code -- A response code (similar to HTTP status codes) indicating whether the geocode request was successful or not. See the full list of status codes.
  • Placemark -- Multiple placemarks may be returned if the geocoder finds multiple matches.
    • address -- A nicely formatted and properly capitalized version of the address.
    • AddressDetails -- The address formatted as xAL, or eXtensible Address Language, an international standard for address formatting.
    • Accuracy -- An attribute indicating how accurately we were able to geocode the given address. See a list of possible values.
    • Point -- A point in 3D space, consisting of a coordinates value -- The longitude, latitude, and altitude of the address. In this case, the altitude is always set to 0.

    Here we show the JSON object returned by the geocoder for the address of Google's headquarters:

    {
      "name": "1600 Amphitheatre Parkway, Mountain View, CA, USA",
      "Status": {
        "code": 200,
        "request": "geocode"
      },
      "Placemark": [
        {
          "address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
          "AddressDetails": {
            "Country": {
              "CountryNameCode": "US",
              "AdministrativeArea": {
                "AdministrativeAreaName": "CA",
                "SubAdministrativeArea": {
                  "SubAdministrativeAreaName": "Santa Clara",
                  "Locality": {
                    "LocalityName": "Mountain View",
                    "Thoroughfare": {
                      "ThoroughfareName": "1600 Amphitheatre Pkwy"
                    },
                    "PostalCode": {
                      "PostalCodeNumber": "94043"
                    }
                  }
                }
              }
            },
            "Accuracy": 8
          },
          "Point": {
            "coordinates": [-122.083739, 37.423021, 0]
          }
        }
      ]
    }
    

    In this example, we use the getLocations() method to geocode addresses, and extract the nicely formatted version of the address and the two-letter country from the JSON and display it in the info window.

    var map = new GMap2();;
    map.setCenter(new GLatLng(34, 0), 1);
    var geocoder = new GClientGeocoder();;
    
    function addAddressToMap(response) {
      map.clearOverlays();
      if (!response || response.Status.code != 200) {
        alert("\"" + address + "\" not found");
      } else {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
        place.Point.coordinates[0]);
        marker = new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindowHtml(place.address + '<br>' +
          '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
      }
    }
    
    // showLocation() is called when you click on the Search button
    // in the form.  It geocodes the address entered into the form
    // and adds a marker to the map at that location.
    function showLocation() {
      var address = document.forms[0].q.value;
      geocoder.getLocationsAsync(address, addAddressToMap);
    }
    
    // findLocation() is used to enter the sample addresses into the form.
    function findLocation(address) {
      document.forms[0].q.value = address;
      showLocation();
    }
    

    Run this example (geocoding-extraction.xml)

    Retrieving External Content

    All the calls in the Working with Remote Content section of the Gadgets API documentation work inside Mapplets:

    • _IG_FetchContent(url, callback) -- Returns the content at url as text. Use this function to fetch HTML or plain text content.
    • _IG_FetchXmlContent(url, callback) -- Returns and operates on the XML content at url as a DOM object. Use this function to fetch XML content which must be parsed.

    Suppose you had the following XML file (located at http://mapgadgets.googlepages.com/cta_red.xml) which lists the coordinates of the Chicago Transit Authority red train line. The points that have names are where stations are located.

    <?xml version="1.0" encoding="UTF-8" ?> 
    <points>
      <point lng="-87.67283499240875" lat="42.019110918045044">Howard</point> 
      <point lng="-87.66907453536987" lat="42.01585473134908">Jarvis</point> 
      <point lng="-87.66744375228882" lat="42.014483688722116" /> 
      <point lng="-87.66716480255127" lat="42.014228607763144" /> 
      <point lng="-87.66695022583008" lat="42.01400541108485" /> 
      <point lng="-87.66682147979736" lat="42.01379815632509" /> 
      <point lng="-87.66662836074829" lat="42.01357495813621" /> 
      <point lng="-87.66645669937134" lat="42.0133198735327" /> 
      <point lng="-87.66634941101074" lat="42.013080730787806" /> 
      <point lng="-87.66611337661743" lat="42.01263432859157" /> 
      <point lng="-87.6660704612732" lat="42.012283581810934" /> 
      <point lng="-87.66602754592896" lat="42.01188500357604" /> 
      <point lng="-87.66602754592896" lat="42.008010693009815">Morse</point> 
      <!-- ... -->
    </points>
    

    The following example uses _IG_FetchXmlContent() to download and parse the XML file, and then draws the train line and adds markers for each station.

    var map = new GMap2();
    
    // Go to Chicago
    map.setCenter(new GLatLng(41.882853, -87.642059), 11);   
    
    // Render the red train line and stations from a remote XML file
    var url = "http://mapgadgets.googlepages.com/cta_red.xml";
    _IG_FetchXmlContent(url, function(response) {
      var trainline = [];
      var points = response.getElementsByTagName("point");
    
      for (var i = 0; i < points.length; i++) {
        var point = points.item(i);
        var lat  = point.getAttribute("lat");
        var lng  = point.getAttribute("lng");
        var latlng = new GLatLng(lat, lng);
    
        trainline.push(latlng);
        if (point.firstChild) {
          var station = point.firstChild.nodeValue;
          var marker = createMarker(latlng, station);
          map.addOverlay(marker);
        }
      }
    
      var polyline = new GPolyline(trainline, "#ff0000", 3, 1);
      map.addOverlay(polyline);
    });
    
    // Creates a marker at the given point with the given name
    function createMarker(point, name) {
      var marker = new GMarker(point);
      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(name);
      });
      return marker;
    }
    

    Run this example (remotecontent.xml)

    Note: The _IG_FetchContent and _IG_FetchXmlContent calls automatically cache the content to reduce the load on your servers. See the Refreshing the Cache section of the Gadgets API documentation for information on how to change the cache duration or disable caching.

    KML/GeoRSS Overlays

    Rather than adding points using Javascript, we recommend that you instead store your data in the KML or GeoRSS data formats. These data formats are added to a map using the GGeoXml object, whose constructor takes the URL of a publicly accessible XML file. GGeoXml placemarks are rendered as GMarkers, while GGeoXml polylines and polygons are rendered as Google Maps API polylines and polygons. <GroundOverlay> elements within KML files are rendered as GGroundOverlay elements on the map.

    GGeoXml objects are added to a map using the addOverlay() method. (You can remove them from the map using removeOverlay().) Both KML and GeoRSS XML files are supported.

    The following example displays all the Chicago Transit Authority train lines from http://mapgadgets.googlepages.com/cta.kml (view in Google Maps). Notice how much simpler this is than the above example which uses _IG_FetchXmlContent.

    var map = new GMap2();
    var geoXml = new GGeoXml("http://mapgadgets.googlepages.com/cta.kml");
    
    map.setCenter(new GLatLng(41.882853, -87.642059), 11);
    map.addOverlay(geoXml);
    

    Run this example (ggeoxml.xml)

    Driving Directions

    You can add driving directions to your Mapplets by using the GDirections object. The GDirections objects requests and receives direction results using either query strings (e.g. "New York, NY to Chicago, IL") or provided textual lat/lons (e.g. "40.712882, -73.967257 to 41.943181,-87.770677"). The GDirections object also supports multi-part driving directions using a series of points. Directions may be displayed as either a polyline drawing the route on a map or retrieved as a JSON structure.

    To use directions in the Google Maps API, create an object of type GDirections and designate a GMap2 object to receive and display results. By default, the map is centered and bounded by the returned route(s) (though you can change this with parameters within a GDirectionOptions object).

    Driving directions are requested using the GDirections.load() method. This method takes a query string and a set of optional GDirectionsOptions parameters. If the GDirections object was constructed with a supplied GMap2 object, then the returned directions will contain a polyline overlay.

    Note that the directions object is not populated with this return information immediately. For this reason, the GDirections object defines a "load" event which you can intercept to determine this state.

    Once directions are returned, the GDirections object will internally store results which you can retrieve using GDirections.getPolyline() and/or GDirections.getRoute(i:Number) methods. Steps within a route can be retrieved using the GRoute.getStep(i:Number) method and the HTML summary of that step can be retrieved using GStep.getDescriptionHtml().

    // Create a directions object and register a map to hold the 
    // resulting computed directions
    
    var map;
    var directions;
    
    function initialize() {
      map = new GMap2();
      map.setCenter(new GLatLng(49.496675,-102.65625), 3);
      directions = new GDirections(map);
      directions.load("New York, NY to Chicago, IL");
    }
    

    The GDirections object also supports multi-point directions, which can be constructed using the GDirections.loadFromWaypoints() method. This method takes an array of textual input addresses or textual lat/lon points. The directions from each sequence of waypoints is computed as a separate route and returned in a separate GRoute object, each of which contains a series of GStep objects.

    GRoute objects store the number of steps (of type GStep) for that route, the starting and ending geocode for that route, and other computed information such as distance, duration, and exact lat/lon of the endpoint (which may be different than the ending geocode if the geocode does not lie on a road segment). Each GStep object also contains the description for that text (e.g. "Merge onto US-101 S via the ramp to San Jose") plus computed information including the distance, duration, and exact lat/lon as well.

    The GDirections object fires three events which you can intercept:

    • "load": This event is triggered when a directions result successfully returns, but before any overlay elements are added to the map.
    • "addoverlay": This event is triggered after the polyline directions components are added to the map.
    • "error": This event is triggered if a directions request results in an error. Callers can use GDirections.getStatus() to get more information about the error.

    For full documentation of the various objects, methods and events in the Directions API package, consult the API Reference.

    Run this example (directions-simple.xml)