MyMap: A Portable API for Maps

This API lets you switch from one map provider (like Google, Yahoo, or Microsoft) to another with minimum changes to your source code.


February 05, 2007
URL:http://www.drdobbs.com/web-development/mymap-a-portable-api-for-maps/197003355

Lionel is a software architect at C2S, a software company based in France and a subsidiary of the Bouygues group. Lionel is also the author of Liogo, an open-source Logo compiler for .NET. Lionel can be contacted at [email protected].


A client who sells real estate wanted us to add interactive maps to his web site to showcase his listings. We immediately thought of using Google Maps. This seemed to be a good choice because it's free and popular. But for how long? Or what if Google decides to add advertisements on its maps? Of course, our client could always switch to another map provider, Yahoo Maps or Microsoft Virtual Earth, for instance, but at what cost?

Because Google, Yahoo, and Microsoft come with similar features, it occurred to us that a "portable" layer would let a web site switch from one map provider to another with a minimum change to source code. This is what I discuss in this article.

Most web sites that support interactive maps have similar features. If we want our portable layer to handle them, it should be able to:

MyMap

MyMap is the portable API I created to display maps in a web site with either Google Maps, Yahoo Maps, or Microsoft Virtual Earth. Here is the pseudointerface of this API in JavaScript. Each function matches one of the aforementioned features.

void MyMapGeocode(address, callback);
void MyMapInitialize
    (mapname, lat, lng, zoom, mode);
Object MyMapAddMarker
    (lat, lng, markertype, info);
void MyMapRemoveMarker(marker);
void MyMapSetZoom(zoom);
void MyMapGoto(lat, lng);
void MyMapTerminate();

Table 1 shows the provider-specific object to use and the methods to call for each feature.

Google Maps Yahoo Maps Virtual Earth
MyMapGeocode GClientGeocoder.getLatLng YMap.geoCodeAddress VEMap.Find
MyInitialize GMap2.setCenter YMap.drawZoomAndCenter VEMap.LoadMap
MyMapAddMarker GMarker YMarker VEPushPin
GMap2.addOverlay YMap.addOverlay VEMap.AddPushPin
MyMapRemoveMarker GMap2.removeOverlay YMap.removeOverlay VEMap.DeletePushPin
MyMapSetZoom GMap2.setZoom YMap.setZoomLevel VEMap.SetZoomLevel
MyMapGoto GMap2.panTo YMap.panToLatLon VEMap.SetCenter
MyMapTerminate GUnload
Table 1: MyMap functions for each map provider.

I've implemented this interface for each provider in the respective files mymap_google.js, mymap_yahoo.js, and mymap_vearth.js. (These files are available electronically; see "Resource Center," page 5). Your web application needs to include the appropriate file depending on your map provider.

Callbacks

Because interactive maps involve user events and asynchronous processing, all map providers make extensive use of callbacks. MyMapGeocode uses a callback to get the geocoding result.

Google and Yahoo let you handle callbacks using a dedicated class (GEvent or YEvent). This class is responsible for registering all callbacks for an object like a map or a marker.

Example 1(a) shows how to create a callback with Google Maps. The method GEvent.addListener is used to associate an object, an event name, and a function to call for that event. Google Maps calls at runtime the registered function of the appropriate object when this event is raised.

(a)
GEvent.addListener(object, eventname, callback);

(b)
YEvent.Capture(object, EventsLists.value, callback);

Example 1: (a) Callback registering in Google Maps; (b) Callback registering in Yahoo Maps.

Example 1(b) shows callback creation in Yahoo Maps. The process is similar to the Google one except that we use an event enumeration instead of an event name.

There is no concept of callback registration in Virtual Earth. Each function directly takes a callback as a parameter when needed. The drawback is that you can't choose which event to use—you are limited to the event the designer of the method chose.

Markers

Again, Google Maps and Yahoo Maps are similar for markers creation. You create an icon object (GIcon/YImage), and then create a marker object (GMarker/YMarker) to hold the marker data. If you want a tooltip to be displayed when the marker is clicked, you simply register a callback on the click event as previously explained.

Virtual Earth uses a single object for the whole process. You need to build a VEPushPin object with an image and some text for the tooltip. It's not possible to choose the triggering event. You can also call custom code neither before nor after the tooltip is displayed.

To avoid icon file handling, MyMap uses the same image for all map providers. You just need to specify a "marker type" constant, which is mapped to a specific icon.

Because all providers support HTML tags in the tooltip text, you can customize your description using formatting, images, or links.

Zoom

Hopefully, zoom levels for all map providers have nearly the same range:

Furthermore, the same zoom level gives the same map scale for all providers. It can't be luck!

A slight difference for Yahoo Maps is that zoom levels are inverted: 1 is the higher zoom, 16 is the lower. The MyMapSetZoom function in mymap_yahoo.js does a difference to 18 on its parameter, so you can keep the same function call regardless of which provider you use.

MyMap In Action

Listing One is a basic HTML page using MyMap. This example just displays a map at zoom level 6, in "road mode." A marker is placed in the center of the map. To choose the map provider Google Maps, Yahoo Maps, or Virtual Earth, you just need to remove the JavaScript comment around the appropriate include statements. Two include statements are needed—one for the JavaScript of the map provider, and another for the corresponding MyMap API. A better way could be to include the JavaScript for the provider in the MyMap API file, but a simple task such as including a file in another file is not trivial in JavaScript. Furthermore, most of the AJAX frameworks provide one such implementation and a real application could dynamically generate these includes in the web server logic.


<!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>MyMap Sample 1</title>
 <!— Google Maps
 —>
 <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAor5up_1nM9SKM8pR     _DseXBSbhcvIRagSHGG9ZRIE7qvWjC5W0hSk4CSCk-m47NJODtlk_qUex2ZeRw" type="text/javascript"></script>
 <script src="scripts/mymap_google.js" type="text/javascript"></script>

 <!— Yahoo Maps
 <script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.0&appid=YahooDemo"></script>
 <script src="scripts/mymap_yahoo.js"></script>
 —>

 <!— Virtual Earth
 <script src="http://dev.virtualearth.net/mapcontrol/v3/mapcontrol.js"></script>
 <script src="scripts/mymap_vearth.js"></script>
 —>

 <script type="text/javascript">
 function load() {
 MyMapInitialize("map", 48.786290, 2.057517, 6, MYMODE_MAP);
 MyMapAddMarker(48.786290, 2.057517, MYMARKER_TYPE1, "<B>I'm here!</B><BR/>");
 }
 function unload() {
 MyMapTerminate();
 }
 </script>
</head>>
<body onload="load()" onunload="unload()">>
 <div id="map" style="position:relative; width: 600px; height: 400px"></div>
</body>>
</html>
Listing One

Google Maps not only references a JavaScript file, but also an encrypted value named "key." This value must be generated by filling in a form on the Google Maps web site. To get this value, you must provide the URL of your web site so that the Google Maps JavaScript checks whether the URL is only used from your web site (or from a local file; for example, "file://..."). Yahoo Maps uses a similar registration process with an "appid" but does not check from where access comes. Registration is not needed for Microsoft Virtual Earth.

Figure 1 is MyMap in a real application. This sample shows JavaScript interaction between the map and the HTML form's radio button and listbox. Moreover, this sample gives a way to dynamically switch between map providers. The application is the official roadmap Santa Claus visits on December 25, 2006. The map shows markers for some famous good and bad boys all around the world. Of course, only good boys were visited by Santa Claus. Listing Two is the JavaScript source code linked to the HTML page. It uses MyMap functions only (no provider-specific function calls).


var guys = [
 { "lat": 48.786290, "lng": 2.057517, "is": "Good", "name":"Lionel Lask\351", "company":"C2S" },
 { "lat": 43.578394, "lng": 1.495859, "is": "Bad", "name":"Sami Jaber", "company":"Valtech" },
 { "lat": 44.261882, "lng": 4.199038, "is": "Bad", "name":"Yacine Chahrour", "company":"Lygue" },
 { "lat": 37.53736, "lng": -122.326571, "is": "Good", "name":"Jon Erickson", "company":"Dr. Dobb's Journal" },
 { "lat": 47.639557, "lng": -122.128336, "is": "Good", "name":"Bill Gates", "company":"Microsoft" },
 { "lat": 37.416987, "lng": -122.025135, "is": "Bad", "name":"Terry Semel", "company":"Yahoo!" },
 { "lat": 37.421690, "lng": -122.084594, "is": "Good", "name":"Larry Page", "company":"Google" }
];
function load() {
 MyMapInitialize("map",42.81152174509788, -49.5703125, 2, MYMODE_MAP);
 for (i=0; i<guys.length; i++) {
 guys[i].marker = null;
 print(i);
 var newopt = document.createElement('option');
 newopt.text = guys[i].name;
 newopt.value = i;
 try {
 document.getElementById("list").add(newopt);
 }
 catch(e) {
 document.getElementById("list").add(newopt, null);
 }
 }
}
function unload() {
 MyMapTerminate();
}
function filter(is) {
 for (i=0; i<guys.length; i++) {
 if (guys[i].is == is)
 hide(i);
 else
 print(i);
 }
}
function print(index) {
 var person = guys[index];
 if (person.marker != null)
 return;
 var markertype = MYMARKER_TYPE1;
 if (person.is == "Bad")
 markertype = MYMARKER_TYPE2;
 guys[index].marker = 
    MyMapAddMarker(person.lat, person.lng, markertype, "<B>"+person.name+"</B><BR/>"+person.company);
}
function hide(index) {
 var person = guys[index];
 if (person.marker != null) {
 MyMapRemoveMarker(person.marker);
 person.marker = null;
 }
}
function gotoselected() {
 goto(document.getElementById("list").value);
}
function goto(index) {
 var person = guys[index];
 MyMapSetZoom(12);
 MyMapGoto(person.lat, person.lng);
}
Listing Two

[Click image to view at full size]

Figure 1: A sample application using MyMap.

As you can see at the beginning of the program, all markers are stored as objects in an array named "guys." The "guy" object is initialized at startup with all existing guys described in JSON (JavaScript Object Notation). The sample has just a few HTML and JavaScript pages so it could work without a web server. But of course, it's possible to replace the JSON initialization directly in the script by something like a web service call (it's precisely what JSON was created for).

The MyMap API is initialized in the load function, then a marker is created with MyMapAddMarker for each person. These are all added to the HTML list for which we handle the selected item event.

MyMapRemoveMarker and MyMapAddMarker are used when filtering the persons to display on the map.

Finally, when the selected item event is raised by the listbox, MyMapSetZoom and MyMapGoto are used to move the map to the chosen boy.

This sample was tested on Google Maps, Yahoo Maps, and Microsoft Virtual Earth both on Internet Explorer and Firefox.

Lessons Learned

The MyMap API shows that Google Maps, Yahoo Maps, and Microsoft Virtual Earth provide similar features and similar ways of working. Displaying markers, geocoding, zooming, and moving the map are handled by similar methods in similar classes. Of course, we don't use all the features provided by these APIs. Each provider comes with some specific features; for example, Yahoo provides a great flash API, Microsoft offer a unique bird's eye view, and Google allows several tooltip customizations (including tabs).

Another difference between these APIs is the satellite and road-map coverage. Map details change from one country to the next depending on which map provider you choose. It's clearly a major difference when deploying markers outside major cities.

MyMap API shows that it's possible and not so complex to write a portable layer working either with Google Maps, Yahoo Maps, or Microsoft Virtual Earth. Using such an API, your mash-up application could take advantage of the best provider according to your own criteria (price, features, support, and the like), then take advantage from the intense competition between Google, Yahoo, and Microsoft.

The MyMap API presented here is licensed under LGPL, so you can use it freely on any open source or legacy project.

Acknowledgments

Thanks to Yacine Chahrour and Lisa Cree for giving me the official flight plan of Santa Claus and for their thorough reading and criticism of this article.

Terms of Service | Privacy Statement | Copyright © 2025 UBM Tech, All rights reserved.