Creating Maps by API Programming

In the following sections, I will discuss the APIs of various popular online services, specifically, Google, Yahoo!, and Microsoft. In the previous section, I discussed data formats with an eye to making maps without any (or much) programming. In the following sections, we will do a bit of programming.

I’ll now summarize what these maps can do in general. The four covered here all allow you to do the following:

With a bit of copying and pasting, you can get working examples of each of the maps. You can then modify them incrementally. Using the DOM Inspector and the JavaScript Shell, you can even make changes to live working examples within the browser. I will also use those mechanisms to highlight important capabilities and functions of the maps.

Google Maps API

Let’s look at the Google Maps API. We will start with how to embed a Google map using the Google Maps API. The online documentation on how to get started with the maps at the Google web site is good.[185]

We’ll set up a simple map and then use the JavaScript Shell to work with a live map so that you can invoke a command and see an immediate response. The intended effect is that you see the widgets as dynamic programs that respond to commands, whether that command comes in a program or from you entering the commands one by one.

[Note]Note

This tutorial on the Google Maps API is essentially the same as that in Chapter 8 and is repeated here for your convenience.

Getting Started with Google Maps and the JavaScript Shell

We will use the Google Maps API to make a simple map:

  1. Make sure you have a public web directory to host your map and know the URL of that directory. Any Google map that uses the free, public API needs to be publicly visible.

  2. Go to the sign-­up page for a key to access Google Maps.[186]

  3. Read the terms of service,[187]http://examples.mashupguide.net/ch13/. Note that key.

  4. Copy and paste the HTML code into your own page on your web-­hosting directory. You should get something like my own example:[188]

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
        <title>Google Maps JavaScript API Example</title>
        <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=<API_KEY>"
          type="text/javascript"></script>
        <script type="text/javascript">
    
        //<![CDATA[
    
        function load() {
          if (GBrowserIsCompatible()) {
            var map = new GMap2(document.getElementById("map"));
            map.setCenter(new GLatLng(37.4419, -122.1419), 13);
          }
        }
    
        //]]>
        </script>
      </head>
      <body onload="load()" onunload="GUnload()">
        <div id="map" style="width: 500px; height: 300px"></div>
      </body>
    </html>
                      
  5. Now make one modification to the example by removing the var keyword in front of map to make it a global variable that is thus accessible to the JavaScript Shell. That is, change this:

    var map = new GMap2(document.getElementById("map"));

    to the following:

    map = new GMap2(document.getElementById("map"));

    to expose the map object to the JavaScript Shell utility.[189]

  6. Invoke the JavaScript Shell for your map by hitting the JavaScript Shell bookmarklet in the context of your map. Type the code fragments in the following steps, and see what happens. (Note that another approach is to modify your code directly with these code fragments and reload your page.) These actions use version 2 of the Google Maps API.[190]

  7. To return the current zoom level of the map (which goes from 0 to 17, with 17 being the most detailed), type the following command (the response from the JavaScript Shell is shown right after the code):

    map.getZoom()

    13

  8. To obtain the latitude and longitude of the center of the map, do this:

    map.getCenter()

    (37.4419, -122.1419)

  9. To center the map around the Campanile for UC Berkeley, use this:

    map.setCenter(new GLatLng(37.872035,-122.257844), 13);

  10. You can pan to that location instead:

    map.panTo(new GLatLng(37.872035,-122.257844));

  11. To add a small map control (to control the zoom level), run these two commands:

    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
                      
  12. To turn GMap keyboard navigation on, use this:

    window.kh = new GKeyboardHandler(map);

    [object Object]

  13. To fully zoom out the map, use this:

    map.setZoom(0)

  14. To zoom in all the way (maximum zoom level may go from 15 to 17), do this:

    map.setZoom(17)

  15. To set the variable maptypes to an array holding three objects, use this:

    maptypes = map.getMapTypes()

    [object Object],[object Object],[object Object]

  16. To get the name of the first entry in maptypes, use this:

    map.getMapTypes()[0].getName()40

    Map

  17. To get the current map type, you can get the object and the name of that type object:

    map.getCurrentMapType()

    [object Object]

    map.getCurrentMapType().getName()

    Map

  18. To set maptype to satellite, do this:

    map.setMapType(maptypes[1]);

  19. You can zoom one level in and out if you are not already at the max or min zoom level:

    map.zoomIn(); 
    map.zoomOut();
                      
  20. To make an overlay, try this:

    point = new GLatLng (37.87309185260284, -122.25508689880371);

    (37.87309185260284, -122.25508689880371)

    marker = new GMarker(point);

    [object Object]

    map.addOverlay(marker);

  21. To make something happen when you click the marker, do this:

    GEvent.addListener(marker, 'click', function() { 
    marker.openInfoWindowHtml('hello'); });
                      

    [object Object]

  22. To add a new layer of pins from a GeoRSS feed, use this:

    map.addOverlay(new GGeoXml('http://api.flickr.com/services/feeds/geo/?id=48600101146@N01&lang=en-us&format=rss_200'));
                      

There are many more things to explore, such as polylines and overlays and draggable points. To learn more, I certainly recommend the “Google Maps API: Introduction” document.[191]

Yahoo! Maps API

The Yahoo! Maps can be programmed with its API. You can find the core documentation, “Yahoo! Maps Web Services: Introducing the Yahoo! Maps APIs,” on the Yahoo! web site.[192][193]

[Note]Note

If you want to learn about the Flash APIs for Yahoo! Maps, which are outside the scope of this book, please refer to the official documentation at http://developer.yahoo.net/maps/flash/index.html.

Getting Started with Yahoo! Maps and the JavaScript Shell

In this exercise, I will present a step-­by-step introduction to the Ajax APIs for Yahoo! Maps:[194]

  1. Apply for a Yahoo! application key.[195]appid for the example code in the Yahoo! documentation (which is YahooDemo).

  2. Copy and paste the following code for your web site:[196]

    <html>
      <head>
        <script type="text/javascript" 
    src="http://api.maps.yahoo.com/ajaxymap?v=3.0&appid=<API_Key>"></script>
        <style type="text/css">
          #mapContainer {
          height: 500px;
          width: 80%;
          }
        </style>
      </head>
    <body>
      <div id="mapContainer"></div>
      <script type="text/javascript">
        // Create a lat/lon object
        var myPoint = new YGeoPoint(37.4041960114344,-122.008194923401);
        // Create a map object
        var map = new YMap(document.getElementById('mapContainer'));
        // Display the map centered on a latitude and longitude
        map.drawZoomAndCenter(myPoint, 3);
    
        // Add map type control
        map.addTypeControl();
    
        // Set map type to either of: YAHOO_MAP_SAT YAHOO_MAP_HYB YAHOO_MAP_REG
        map.setMapType(YAHOO_MAP_SAT);
    
        //Get valid map types, 
        //returns array [YAHOO_MAP_REG, YAHOO_MAP_SAT, YAHOO_MAP_HYB]
        var myMapTypes = map.getMapTypes();
      </script>
    </body>
    </html> 
                      
  3. Invoke the JavaScript Shell for your map by hitting the JavaScript Shell bookmarklet in the context of your map. Type the code fragments in the following steps, and see what happens. (If you don’t use your own map, try the JavaScript Shell on the example on the Yahoo! web site.)[197]

  4. To get the zoom level, use this:

    map.getZoomLevel()

    3

  5. To get the center location, specifically, the latitude and longitude, use this:

    map.getCenterLatLon()

    [object Object]

    props(map.getCenterLatLon())

    
    Fields: Lat, Lon
    Methods of prototype: distance, equal, getRad, greater, middle, pointDiff, 
    setgeobox, valid
    
                      

    map.getCenterLatLon().Lat

    37.4041960114344

    map.getCenterLatLon().Lon

    -122.008194923401

  6. To set the zoom level (15 for largest scale, 1 for most zoomed in), use this:

    map.setZoomLevel(15)
    map.setZoomLevel(1)
                      
  7. To move the map to a new center (in this case, the UC Berkeley campus), do this:

    p = new YGeoPoint(37.87309185260284, -122.25508689880371)

    [object Object]

    map.panToLatLon(p)

  8. To add some navigation and zoom controls, use this:

    map.addPanControl();
    map.addZoomLong();
                      
  9. To add a marker, labeled H, use the following:

    marker = new YMarker(p);

    [object Object]

                         marker.addLabel("H");
                         map.addOverlay(marker);
                      
  10. To make a click event invoke a pop-­up, use this:

    function onSmartWinEvent() {var words = "Yeah Yahoo maps!"; 
    marker.openSmartWindow(words); } 
    YEvent.Capture(marker, EventsList.MouseClick, onSmartWinEvent); 
                      
  11. To add a marker to a specific address, in this case, 2195 Hearst Ave, you can use either of the following three alternatives:

    map.addMarker("2855 Telegraph Ave, Berkeley, CA");

    or

    map.addOverlay(new YMarker("2855 Telegraph Ave, Berkeley, CA "));

    or

    marker = new YMarker("2855 Telegraph Ave, Berkeley, CA ");
    marker.addLabel("Apress");
    map.addOverlay(marker);
    marker.reLabel("<b>hello</b>");
                      
  12. To add a GeoRSS feed (that uses either the Yahoo! YMaps extensions or the Compact W3C Basic Geo encoding) to the map, use this:

    map.addOverlay(new YGeoRSS('http://examples.mashupguide.net/ch13/bookstores.georsss.xml'));
                      

These examples do not exhaust the Yahoo! Ajax API, which has features such as polylines and more complete overlay functionality.

Microsoft’s Live Search Maps/Virtual Earth

Microsoft’s Live Search Maps, the company’s latest offering in online maps, has gone by quite a few other names (Windows Live Map and Windows Live Local). The name of the service is also not to be confused with Virtual Earth, the name Microsoft has given to the technology that “powers” Live Search Maps. None of this technology is to be confused with MSN Maps, also run by Microsoft.[198]

The Virtual Earth Map control is an Ajax widget, well documented at the following locations:

  • The official central place for the Microsoft Virtual Earth docs.[199]

  • The Virtual Earth Interactive SDK[200]

Getting Started with Virtual Earth and the JavaScript Shell

  1. Copy and paste the following code (this is the simplest piece of code given at the Virtual Earth Interactive SDK):[201]

    <html>
       <head>
          <title>ve.map.1.html</title>
          <meta ?http-?equiv="Content-Type" content="text/html; charset=utf-8">
          <script src="http://dev.virtualearth.net/mapcontrol/v5/mapcontrol.js">
          </script>
          <script>
          var map = null;
                
          function GetMap()
          {
             map = new VEMap('myMap');
             map.LoadMap();
          }   
          </script>
       </head>
       <body onload="GetMap();">
          <div id="myMap" 
               style="position:relative; width:400px; height:400px;"></div>
       </body>
    </html>
                      
  2. Invoke the JavaScript Shell for your map by hitting the JavaScript Shell bookmarklet in the context of your map. Type the code fragments in the following steps, and see what happens.

  3. To get the zoom level, use this:

    map.GetZoomLevel()

    4

  4. To zoom in and out, use this:

    map.ZoomIn(); 
    map.ZoomOut();
                      
  5. To get the style of the map, use this:

    map.GetMapStyle()

    r

  6. To set the map style (a = aerial, r = road, h = hybrid, and o = bird’s-eye), use this:

    map.SetMapStyle('a');

3D Aspects of Virtual Earth

One cool distinguishing feature of the Virtual Earth is its 3D mode, accessible via JavaScript. This 3D mode is akin to wrapping Google Earth functionality into Google Maps. The 3D mode is available if you are running Firefox or Internet Explorer version 6 or 7 on Windows and have the appropriate 3D add-­ons installed. The requirements are documented here:

http://msdn2.microsoft.com/en-us/library/bb429547.aspx

Continuing the exercise, you can put the map into 3D mode with the following command in the JavaScript Shell:

map.SetMapMode(VEMapMode.Mode3D);

Remember to use the Virtual Earth Interactive SDK (http://dev.live.com/virtualearth/sdk/) to learn about the other capabilities in Virtual Earth, including working with shapes and driving directions.



[195] https://developer.yahoo.com/wsregapp/index.php