10.4. Yahoo! Maps API

The Yahoo! Maps API debuted around the same time as the Google Maps API, but with less fanfare. The folks at Yahoo! decided to take an interesting approach to their new mapping product, developing both Ajax and Flash APIs. The Ajax API (covered here) is composed of JavaScript objects used to implement maps on any web site. The Flash API, on the other hand, can be embedded within Flash movies or Flex applications as well as embedded in web sites. Both the Ajax and Flash APIs use the same data and image sources, so visually there is very little difference between the two.

10.4.1. Getting Started

To use the Yahoo! Maps API, you must have a Yahoo! ID. If you don't have one, go to http://edit.yahoo.com and click on the "Sign Up" link. After signing up, go to http://api.search.yahoo.com/webservices/register_application to request an application ID. This application ID can be used not only for the Yahoo! Maps API but also for the other public Yahoo! APIs.

There are some limitations on using the Yahoo! Maps API:

  • The API is for noncommercial use only. You can contact Yahoo! directly to inquire about a commercial license.

  • The attribution inside of the map must not be obscured.

  • You are limited to 50,000 requests per day. If you anticipate needing more than that, you'll need to discuss your needs with Yahoo! directly.

Once you have agreed to the terms of use and received an application ID, you'll need to include the Yahoo! Maps API JavaScript file in your page. This file resides on Yahoo! servers and must be accessed directly from there by providing the API version number and your application ID in the following format:

http://api.maps.yahoo.com/ajaxymap?v={api version}&appid={your application ID}

At the time of writing, the most recent version is 3.4, so the code can be included using a <script/> tag like this:

<script type="text/javascript"
        src="http://api.maps.yahoo.com/ajaxymap?v=3.4&appid={app ID}"></script>

This is the only file necessary to begin using Yahoo! Maps on your site.

10.4.2. Yahoo! Maps Basics

The map object in the Yahoo! Maps API is YMap. The constructor for a YMap object can accepts three arguments: the container element in which to create the map, an optional map type indicating which type of map to display (map, satellite, or hybrid), and an optional YSize object indicating the dimensions of the map container. Generally, the third argument isn't needed as long as the width and height of the container element are specified.

To create a map using a <div/> element with an ID of "divMap", use the following:

var oMap = new YMap(document.getElementById("divMap"));

This code initializes the map container element as a Yahoo! map control, but the map itself hasn't been drawn yet. To display the map, the drawZoomAndCenter() method must be called, passing in the coordinate on which to center and the zoom level. Map coordinates are represented by YGeoPoint objects in the Yahoo! Maps API, which store the decimal format latitude and longitude of a location. The zoom level is a number between 1 and 16, where 1 is zoomed all the way in and 16 is zoomed all the way out. To display a map that shows the entire United States, use the following code:

var oMap = new YMap(document.getElementById("divMap"));
oMap.drawZoomAndCenter(new YGeoPoint(32, −92), 14);

These two lines of code produce a basic map with a distance legend (see Figure 10-7).

Figure 10.7. Figure 10-7

It's possible to specify a different map type for the initial view of the map. The possible values are YAHOO_MAP_REG (the regular map), YAHOO_MAP_SAT (satellite photos), and YAHOO_MAP_HYB (hybrid combination of map and photos). One of these values can be passed in to the YMap constructor to set the initial map type:

var oMap = new YMap(document.getElementById("divMap"), YAHOO_MAP_SAT);
oMap.drawZoomAndCenter(new YGeoPoint(32, −92), 14);

This code creates the same basic view of the map but with satellite imagery. There's also a setMapType() method that can be used to change the map type at any time:

var oMap = new YMap(document.getElementById("divMap"));
oMap.drawZoomAndCenter(new YGeoPoint(32, −92), 14);
oMap.setMapType(YAHOO_MAP_SAT);

Since every map has a map type set either by default or by the developer, the map type can be retrieved using the getCurrentMapType() method, which returns one of the three constants used in the setMapType() method:

switch(oMap.getCurrentMapType()) {
    case YAHOO_MAP_REG:
        alert("Regular map");
        break;
    case YAHOO_MAP_SAT:
        alert("Satellite map");
        break;
    case YAHOO_MAP_HYB:
        alert("Hybrid map");
        break;
}

Although it's possible to set the map type programmatically, it's also helpful to allow the user to decide how to display the map. To allow more fine-grained user control of the map, you'll need to use controls.

10.4.3. Controls

Controls allow users to manipulate the view of the map directly. The Yahoo! Maps API provides several built-in controls that can be added to the map individually depending on your specific needs. These built-in controls are added using one of the following methods on the YMap object:

  • addPanControl(): Adds a pan control containing arrows pointing north, south, east, and west; clicking on any of these buttons pans the map in the specified direction. This control is placed in the upper-right corner of the map. The control can be removed by using removePanControl().

  • addTypeControl(): Adds a map type control containing buttons for each of the three map types. Clicking on a button changes the map's view to that of the specified map type. This control is placed in the upper-left corner of the map. The control can be removed by using removeTypeControl().

  • addZoomLong(): Adds a large zoom control to the map made up of plus and minus buttons, as well as a zoom scale. This control is placed in the upper-right corner of the map. The control can be removed by using removeZoomControl().

  • addZoomScale(): Adds a zoom scale control to the map indicating the measurements being used in the current map view. This control is added by default and is placed in the lower-left corner of the map. The control can be removed by using removeZoomScale().

  • addZoomShort(): Adds a small zoom control to the map made up of only a plus and minus button. This control is placed in the upper-right corner of the map. The control can be removed using removeZoomControl().

To create a map with a pan control, map type control, and long zoom control, use the following code:

var oMap = new YMap(document.getElementById("divMap"));
oMap.addPanControl();
oMap.addTypeControl();
oMap.addZoomLong();
oMap.drawZoomAndCenter(new YGeoPoint(32, −92), 14);

This code creates the map displayed in Figure 10-8.

Note that the zoom scale control is in the lower-left corner by default, since removeZoomScale() wasn't called. It's best to call these methods before the call to drawZoomAndCenter().

Figure 10.8. Figure 10-8

10.4.4. Moving the Map

By default, a map created using the Yahoo! Maps API can be dragged by the user to pan the view. Adding a pan control to the map gives users another way to scroll the viewport of the map. The view can also be panned programmatically using a couple of methods available on the YMap object.

The first method, panToLatLon(), pans the map to a specific location given by latitude and longitude. This method accepts a single argument, which is a YGeoPoint, indicating where the map should be panned to. When the map is panned, this method uses animation to move the map to that position, providing a smooth scrolling effect that is similar to the panning animation used in the Google Maps API. Panning via latitude/longitude can be accomplished like this:

oMap.panToLatLon(new YGeoPoint(50, −80));

This method pans the map to a specific location, meaning that subsequent calls using the same data won't move the map at all. It is possible to move the map relative to the current view, by pixels, using the panToXY() method. This method accepts a single argument, a YCoordPoint object, which represents the x and y coordinates in pixels. The map is panned so that the center is the location that was represented at those coordinates. To pan the map to the location 20 pixels from the top and left of the map, use the following code:

oMap.panToXY(new YCoordPoint(20, 20));

Because the information is relative to the current view of the map, this line of code can be executed repeatedly and will cause the map to move each time until the end of the map is reached.

10.4.5. Smart Windows

To display information about a location the map, Yahoo! Maps uses a smart window. Smart windows are small, white bubbles that point to a specific location with a small triangle and display text or some other HTML code. All smart windows are also created with a close button, a small "X" in the upper-right corner (see Figure 10-9).

Figure 10.9. Figure 10-9

Smart windows are opened using the showSmartWindow() method of the YMap object. This method accepts two arguments: a YGeoPoint to anchor to and the content for the smart window. The content can be an HTML string or a DOM text node. The following code opens a smart window at the center of the map with a simple message:

oMap.showSmartWindow(oMap.getCenterLatLon(), "Hello world!");

This code uses the getCenterLatLon() method to retrieve a YGeoPoint object for the center of the map so that the smart window can be opened in the exact location. The second argument is plain text, though it could just as easily have contained HTML:

oMap.showSmartWindow(oMap.getCenterLatLon(), "<strong>Hello</strong> world!");

If you need output characters that are part of HTML syntax, such as less than (<), then creating a text node is the way to go:

oMap.showSmartWindow(oMap.getCenterLatLon(), document.createTextNode("5 < 10"));

10.4.6. Events

Most of the objects in the Yahoo! Maps API support events that can be handled to provide an increased level of interaction. The YEvent object publishes a single method called Capture() that is used to assign event handlers. The Capture() method accepts four arguments: the target object, the name of the event, a function to call when the event occurs, and an optional scope object (used if the function to call is a method of another object). All supported Yahoo! Maps events are contained in the EventsList object, which has properties corresponding to specific events that can be managed. For the YMap object, the following events are supported:

  • EventsList.changeZoom: Occurs when the zoom level changes.

  • EventsList.endAutoPan: Occurs when an "auto" pan occurs (pan to a specific point as opposed to the map being dragged around arbitrarily).

  • EventsList.endMapDraw: Occurs when the drawing of the map is finished.

  • EventsList.endPan: Occurs when the panning of the map stops.

  • EventsList.KeyDown: Occurs when a key is pressed.

  • EventsList.KeyUp: Occurs when a key is released.

  • EventsList.MouseClick: Occurs when the mouse is clicked on the map.

  • EventsList.MouseDown: Occurs when the mouse button is pressed down when the cursor is on the map.

  • EventsList.MouseDoubleClick: Occurs when the mouse is double-clicked on the map.

  • EventsList.MouseOut: Occurs when the mouse leaves the map area.

  • EventsList.MouseOver: Occurs when the mouse first enters the map area.

  • EventsList.MouseUp: Occurs when a mouse button is released when the cursor is over the map.

  • EventsList.onPan: Occurs repeatedly as the map is panned.

  • EventsList.onEndGeoCode: Occurs when a geocode request returns.

  • EventsList.onEndLocalSearch: Occurs when a local search request returns.

  • EventsList.onEndTrafficSearch: Occurs when a traffic search request returns.

  • EventsList.polylineAdded: Occurs when a polyline has been added to the map.

  • EventsList.polylineRemoved: Occurs when a polyline has been removed from the map.

  • EventsList.startAutoPan: Occurs when an auto-pan is started.

  • EventsList.startPan: Occurs when a pan is started.

To handle the EventsList.changeZoom event, for example, the following code can be used:

YEvent.Capture(oMap, EventsList.changeZoom, function () {
    alert("Zoom level changed.");
});

Or, if the event handler function is a method of an object, the code can be changed to this:

var oCustom = {
    handleZoom : function () {
        alert("Zoom level changed.");
    }
};

YEvent.Capture(oMap, EventsList.changeZoom, oCustom.handleZoom, oCustom);

Here, the object oCustom has a method called handleZoom() that should be called when the map's zoom level has changed. The third argument is a pointer to the handleZoom() method on the oCustom object, and the fourth argument passes in the oCustom object itself, which tells the event handler that the function is actually a method of this object.

10.4.7. Map Overlays

To add an overlay to a Yahoo! map, use the addOverlay() method. All available overlays can be added using this method, including markers, customer markers, and polylines. Unlike the Google Maps API, overlays in Yahoo! Maps can be created relative to a geographic location (YGeoPoint) or a point on the map container (YCoordPoint). The latter makes it possible place an overlay on the map that remains in the same spot no matter how the map is panned or zoomed.

10.4.7.1. Markers

The simplest type of overlay is a marker. A marker on a Yahoo! Map looks almost like a small smart window without any text that points to a specific location. There are two ways to add a marker to the map. The first is to use the addMarker() method, which accepts a YGeoPoint and an ID string as arguments (the ID can be used later to retrieve information about the marker if necessary). For example, to add a marker at the center of the map, the following code can be used:

oMap.addMarker(oMap.getCenterLatLon(), "marker1");

This is the fastest way to add a marker to the map when there's no additional information necessary. A more verbose way is to create a YMarker object and add it to the map using the addOverlay() method. A YMarker object is created by simply passing in a YGeoPoint object indicating where the marker should be placed:

var oMarker = new YMarker(oMap.getCenterLatLon());
oMap.addOverlay(oMarker);

A YMarker object can be retrieved for markers added via addMarker() using the getMarkerObject() method and passing in the ID:

var oMarker = oMap.getMarkerObject("marker1");

In either case, a YMarker object can be further augmented to customize the marker.

10.4.7.1.1. Working with Labels

Markers can display small labels on top of the image. These labels are best left to one or two characters due to the limited amount of space available on the marker. A label is added to a marker using the addLabel() method, which accepts an HTML string as an argument. This method can be called anytime after a marker has been created:

var oMarker = new YMarker(oMap.getCenterLatLon());
oMarker.addLabel("1");
oMap.addOverlay(oMarker);

This code adds a label of "1" to the given marker before adding it to the map. This produces a marker such as the one displayed in Figure 10-10.

It's important to note that addLabel() can be called only once per marker. After that point, the label can be changed by calling reLabel():

var oMarker = new YMarker(oMap.getCenterLatLon());
oMarker.addLabel("1");
oMap.addOverlay(oMarker);

//other code

oMarker.reLabel("2");

Calls to reLabel() erase any previous label and replace it with the specified HTML string.

Figure 10.10. Figure 10-10

10.4.7.1.2. Auto-Expand Windows

Closely related to the concept of labels are auto-expand windows. Auto-expand windows appear automatically when the mouse cursor is moved over a marker, and they disappear when the cursor moves away from the marker. The purpose of auto-expand windows is to show small additional amounts of information about a particular location. Visually, auto-expand windows look like smaller versions of smart windows without a close button (see Figure 10-11).

Figure 10.11. Figure 10-11

To define an auto-expand window, use the addAutoExpand() method, which accepts an HTML string as its only argument:

var oMarker = new YMarker(oMap.getCenterLatLon());
oMarker.addLabel("1");
oMarker.addAutoExpand("The first marker.");
oMap.addOverlay(oMarker);

The call to addAutoExpand() automatically assigns all of the relevant event-handling code for the marker. It is also possible to open and close the auto-expand window programmatically instead of waiting for a user action using openAutoExpand() and closeAutoExpand(). Calls to these methods don't interfere with the event handling assigned to the marker, so auto-expand windows opened using openAutoExpand() will still close if the cursor is moved over the marker and then away from it.

10.4.7.1.3. Specifying a Custom Image

There may be a case when a marker should have a custom image (instead of the default marker image). An image can be specified when a YMarker object is created as the second argument in the constructor. This argument is a YImage object whose constructor accepts four arguments: the source URL for the image to use, an optional YSize object indicating the width and height to use instead of the default values, a optional YCoordPoint giving the offset for a smart window from the image, and an optional YCoordPoint specifying where the image should be placed relative to the lower-left corner of the image. In most cases, only the first argument is necessary:

var oImage = new YImage("flag.gif");
var oMarker = new YMarker(oMap.getCenterLatLon(), oImage);
oMap.addOverlay(oMarker);

Because the flag icon used in this example has its flagpole on the left of the image, the flag is anchored exactly at the specific coordinates on the map. Suppose that you wanted to use a smiley face image with a width and height of 29 pixels that had its center at an exact coordinate on the map; you would need to specify the fourth argument of the YImage constructor:

var oImage = new YImage("smiley.gif", null, null, new YCoordPoint(-15, 15));
var oMarker = new YMarker(oMap.getCenterLatLon(), oImage);
oMap.addOverlay(oMarker);

The fourth argument to the YImage constructor is a YCoordPoint specifying how the image should be offset when it's placed. Since the center of the image is 15 pixels from the top and 15 pixels from the left, the YCoordPoint is created with −15 as an x-offset (moving the image 15 pixels to the left) and 15 as a y-offset (moving the image 15 pixels down).

10.4.7.1.4. Marker Smart Windows

Smart windows can be opened directly from marker objects, ensuring that the smart window is anchored at the same location as the marker. The openSmartWindow() method accepts only one argument, which is the content to display in the smart window. As with the YMap method of the same name, the content can be an HTML string or a DOM text node. Typically, marker smart windows are assigned to appear when a marker is clicked, such as:

YEvent.Capture(oMarker, EventsList.MouseClick, function () {
    oMarker.openSmartWindow("Information about the marker.");
});

This code displays a smart window over the marker when it is clicked by using the Yahoo! Maps API event-handling capabilities. Once a smart window is open, its contents can be changed by using the updateSmartWindow() method:

oMarker.updateSmartWindow("Updated information about the marker.");

It's also possible to close the marker's smart window programmatically using the closeSmartWindow() method:

oMarker.closeSmartWindow();

Both the openSmartWindow() and closeSmartWindow() methods fire events of the same name. For example, to listen for a marker smart window to be closed, use the following code:

YEvent.Capture(oMarker, EventsList.closeSmartWindow, function () {
    alert("Closed smart window.");
});

The EventsList.closeSmartWindow event fires both when the user clicks the close button on the smart window and when the closeSmartWindow() method is called.

10.4.7.2. Polylines

Polylines in the Yahoo! Maps API are implemented the same way regardless of the browser being used, so unlike with the Google Maps API, there is no need to include extra namespaces or CSS code to use this feature. All that is necessary is to create a YPolyline object and add it to the map using addOverlay(). The constructor for YPolyline accepts four arguments: an array of YGeoPoint objects indicating where the vertices are, an optional color string indicating the color of the polyline, an optional width (integer) specifying how thick the polyline should be, and an optional alpha setting (floating point value between 0 and 1). For example:

var oPolyline = new YPolyline([
    new YGeoPoint(40.758224, −73.917404),
    new YGeoPoint(34.101509, −118.32691)
], "#f00", 10);

oMap.addOverlay(oPolyline);

This recreation of the Google Maps example creates a red line that is 10 pixels wide spanning from New York to Los Angeles.

A polyline can be removed by using the removeOverlay() method and passing in the YPolyline object:

oMap.removeOverlay(oPolyline);

Both adding and removing polylines cause events to fire on the YMap object. To listen to both events, use the EventsList.polylineAdded and EventsList.polylineRemoved events:

YEvent.Capture(oMap, EventsList.polylineAdded, function () {
    alert("Polyline added.");
});

YEvent.Capture(oMap, EventsList.polylineRemoved, function () {
    alert("Polyline removed.");
});

These events can come in handy if your application creates and removes polylines based on user data.

10.4.7.3. Custom Overlays

Yahoo! Maps makes it easy to add custom overlays to a map using the YCustomOverlay object. The constructor for YCustomOverlay accepts two arguments: a point to place the overlay at and a DOM node to place at that point. The first argument can be either a YGeoPoint, to create a location-specific overlay, or a YCoordPoint, to create an overlay that remains at the same position on the map no matter the zoom level or movement of the underlying map.

As an example, consider placing a small blue box at the center of the map. This can be accomplished by creating a <div/> element, sizing it appropriately, setting its background color to blue, and then passing it into the YCustomOverlay constructor:

var oDiv = document.createElement("div");
oDiv.style.width = "16px";
oDiv.style.height = "16px";
oDiv.style.backgroundColor = "blue";

oMap.addOverlay(new YCustomOverlay(oMap.getCenterLatLon(), oDiv));

The blue <div/> created in this example moves as the map moves so that it's upper-left corner is located at the geographic point specified in the YCustomOverlay constructor. To create the same small blue square at a specific position within the map container, just replace the first argument with a YCoordPoint:

var oDiv = document.createElement("div");
oDiv.style.width = "16px";
oDiv.style.height = "16px";
oDiv.style.backgroundColor = "blue";

oMap.addOverlay(new YCustomOverlay(new YCoordPoint(200, 20), oDiv));

This code places the blue square 200 pixels from the left and 20 pixels from the top of the map container. It will remain in that exact location regardless of zooming and panning. This type of custom overlay is helpful when making custom controls for the map.

10.4.7.4. GeoRSS Support

GeoRSS is an XML-based language designed to describe geographic information. The Yahoo! Maps API can make use of GeoRSS information for various purposes. For example, if you have set up a number of markers or other overlay information on a map that you want to save and be able to call up at any time, you can export the map data to GeoRSS code using YMap object's exportFormat() method:

var sGeoRSS = oMap.exportFormat("GEORSS");

This code returns a GeoRSS string that representing all of the data contained in the map. The argument "GEORSS" is required even though the exportFormat() method doesn't currently support any other data formats.

GeoRSS text can also be stored in external files and loaded into a map using the YGeoRSS object, which is another type of map overlay. A YGeoRSS object is created by passing in a URL to a file containing GeoRSS information. This information is then read by the API and transformed into a series of markers, overlays, etc., representing the data contained in the file. The Yahoo! Maps developer site offers a sample GeoRSS file at http://developer.yahoo.com/maps/sample.xml. To load this file, use the following JavaScript code:

oMap.addOverlay(new YGeoRSS("http://developer.yahoo.com/maps/sample.xml"));

This creates markers for various locations around the Sunnyvale, California, area, complete with smart windows containing more information when each marker is clicked.

Using GeoRSS files can significantly reduce the amount of coding necessary to add a large amount of markers to a map. It's worth noting that the Yahoo! Maps API adds some of its own custom elements to the standard GeoRSS format to support features like smart windows.

10.4.8. Address Lookup

The Yahoo! Maps API supports address lookup, meaning that it can locate a plain-text address on the map. For example, suppose that you wanted to center the map on your favorite zip code; just pass the zip code into the drawZoomAndCenter() method:

oMap.drawZoomAndCenter("90210", 12);

This code centers the map on Beverly Hills, California, at a zoom level of 12. Address determination can deal with full addresses as well, so it's possible to center on a specific address, such as:

oMap.drawZoomAndCenter("701 First Avenue, Sunnyvale, CA", 12);

Of course, centering on a specific address has limited usefulness, which is why it's possible to place markers at specific addresses as well:

oMap.addMarker("701 First Avenue, Sunnyvale, CA");

This code adds a marker at the address specified. Behind the scenes of each of these calls is a geocoding request that takes the address and returns the geographic location as a YGeoPoint. However, that detail is abstracted away, making the API even more powerful due to its simplicity.

NOTE

Note that address lookup does require an extra request to the server for the geocode information, so it may slow down the redrawing/placing of markers on the map compared to using latitude and longitude coordinates.

10.4.9. Additional Information

As with many APIs, the Yahoo! Maps API is quite large, and it's beyond the scope of this book to cover every feature in depth. There are, however, some excellent resources available online at http://developer.yahoo.com/maps/ajax/, including numerous examples exploring custom functionality. The complete class reference is located at http://developer.yahoo.com/maps/ajax/V3.4/reference.html (the URL changes for each new version of the API, so make sure to check the version you are using).

There is also another Wrox book, Yahoo! Maps Mashups (Wiley 2007), that contains examples that mash up data from multiple locations, including Flickr and Upcoming.org. Additionally, this book explores uses of the Yahoo! Maps Flash API along with the Ajax API.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset