A fast and simple async API for Google Mapplets

Michael Geary | Wed, 2007-06-06 16:18

Update 2007-06-22: Version 2 now supports portable code that runs as both a mapplet and a Maps API app. Read about the update.

If you’re building a Google Mapplet that responds to map movement and resizing, you will soon find yourself writing code like this recent gem of mine:

map.getSizeAsync( function( size ) {
    map.getBoundsAsync( function( bounds ) {
        map.getCenterAsync( function( center ) {
            search( size, bounds, center );
        });
    });
});

What is going on here? I have a search() function that takes the current map size, bounds and center, runs a search and displays pins on the map. In a normal Google Maps application I could have simply coded:

search( map.getSize(), map.getBounds(), map.getCenter() );

But a Google Mapplet lives in a strange and different world. To isolate mapplet code from the Google domain, Google runs the mapplet in an IFRAME loaded from the gmodules.com domain. Cross-domain browser security prevents your code from communicating directly with the Google Maps frame loaded from maps.google.com.

The mapplet API uses the iframe fragment hack to allow limited communication between the mapplet and the Google map. This has two consequences:

  • The communication is asynchronous. This doesn’t affect the API for functions that simply set map state—they operate on a “fire and forget” basis. But functions that return information can’t do it directly. You have to provide a callback function that receives the information when it is ready.

  • The communication is slow. Everything is serialized through the fragment identifier (hash) of a hidden IFRAME. The map page and the mapplet frame each have interval timers running to watch for changes to this hash. A single getSomethingAsync() function call requires all these steps:

    1. Mapplet frame sets the hash to represent the function call.
    2. Map page timer wakes up, makes the actual Maps API call, and sets the hash to represent the return value.
    3. Mapplet frame timer wakes up, gets the value from the hash, and calls the callback function.

My code listed above makes three of these round trips to the maps page one after the other, because the callback for each function triggers the next step in the series. That’s a lot of timeouts—enough to cause a noticeable delay.

What if we could somehow combine all three information requests into a single round trip? That should speed things up quite a bit. Imagine a different Mapplet async API where you provide a list of Maps API functions and get back all of their responses in a single callback with multiple arguments. My three nested function calls and callbacks could be reduced to:

GAsync( map, 'getSize', 'getBounds', 'getCenter',
    function( size, bounds, center ) {
        search( size, bounds, center );
    });

(The sharp-eyed reader will note that the search() function could be used directly as the callback because it takes the same arguments:

GAsync( map, 'getSize', 'getBounds', 'getCenter', search );

But we’ll stick with the longer form for this discussion, because it makes it clear what the function arguments are.)

While we’re at it, we can provide a way to retrieve information for more than one object in a single call:

// Get the map center and the location of a marker,
// and find out if the marker is hidden
GAsync(
    map, 'getCenter',
    marker, 'getPoint', 'isHidden'
    function( mapCenter, markerPoint, markerHidden ) {
        // ...
    });

And for functions such as map.fromContainerPixelToLatLngAsync() which take an additional argument, we can allow an optional arguments array after any function name:

// Get the map center, top left corner, and zoom level
GAsync(
    map,
        'getCenter',
        'fromContainerPixelToLatLng', [ new GPoint(0,0) ],
        'getZoom'
    function( center, topleft, zoom ) {
        // ...
    });

Compare that with the equivalent nested functions using the existing API, which would take about three times longer to run:

map.getCenterAsync( function( center ) {
    map.fromContainerPixelToLatLngAsync( new GPoint(0,0), function( topleft ) {
        map.getZoomAsync( function( zoom ) {
            // ...
        });
    });
});

Good news: We don’t have to wait for Google to implement this zippy GAsync API or something like it. Although the public API only exposes individual xyzAsync() functions, the underlying iframe fragment dispatcher can queue up multiple function calls and return values into a single round trip.

The Google Maps team was kind enough to provide me with a nifty makeBarrier() function that allows us to queue up a number of async calls and get a single callback when all their values are ready. Using this function, my first example can be written as:

function makeBarrier( numCalls, callback ) {
    return function() {
        if( ! --numCalls ) callback();
    };
}

var size, bounds, center;

// The 3 here refers to the 3 callbacks that we want to synchronize below
var barrier = makeBarrier( 3, function() {
    search( size, bounds, center );
});

// Fire the 3 callbacks
map.getSizeAsync( function( returnedSize ) {
    size = returnedSize;
    barrier();
});

map.getBoundsAsync( function( returnedBounds ) {
    bounds = returnedBounds;
    barrier();
});

map.getCenterAsync( function( returnedCenter ) {
    center = returnedCenter;
    barrier();
});

As you can see, it’s up to us to count the functions and keep track of the values, but having done that, we can get all three values in a single round trip through the API. It’s literally three times faster than the nested API calls.

Armed with that information, could we code GAsync() as a layer on top of the existing mapplet async APIs? Indeed we can!

You can try out the code right now and see the speed difference with my test mapplet. Go to the Google Maps Developer Preview page, log into your Google account, and click the Add Content link under the Mapplets tab (or click the Browse Content button if that is what is there).

The next page will show a number of existing mapplets. Click the tiny Add by URL link next to the search button at the top of the page, and paste this URL into the URL box that opens up. You can also click this link to see the mapplet source code:

https://mg.to/mapplet/async/async.xml

(When you paste the link, make sure the https:// isn’t duplicated because of the text already in the box.)

Click the Add button and click OK on the confirmation dialog. Then click Back to Google Maps at the top left corner of the page, and you should see a new entry titled A fast simple mapplet async API. Click it to load the mapplet.

An info window should open in the map, displaying several items of information about the map, and the time it required to collect the information using the GAsync() API. Then try the Slow Async API radio button to see the performance using nested async calls.

The GAsync code used in the test mapplet is:

GAsync(
    map, 'getZoom', 'getSize', 'getBounds', 'getCenter',
        'fromContainerPixelToLatLng', [ new GPoint(0,0) ],
    marker, 'getPoint', 'getIcon',
    function info( zoom, size, bounds, center, topleft, point, icon ) {
        // ...
    });

and the corresponding nested async code is:

map.getZoomAsync( function( zoom ) {
    map.getSizeAsync( function( size ) {
        map.getBoundsAsync( function( bounds ) {
            map.getCenterAsync( function( center ) {
                map.fromContainerPixelToLatLngAsync( new GPoint(0,0), function( topleft ) {
                    marker.getPointAsync( function( point ) {
                        marker.getIconAsync( function( icon ) {
                            // ...
                        });
                    });
                });
            });
        });
    });
});
}

Finally, here is the GAsync source code. First, a compact version suitable for pasting into your own mapplet (or download async.js):

// GAsync v2 by Michael Geary
// Commented version and description at:
// https://mg.to/2007/06/22/write-the-same-code-for-google-mapplets-and-maps-api
// Free beer and free speech license. Enjoy!

function GAsync( obj ) {

    function callback() {
        args[nArgs].apply( null, results );
    }

    function queue( iResult, name, next ) {

        function ready( value ) {
            results[iResult] = value;
            if( ! --nCalls )
                callback();
        }

        var a = [];
        if( next.join )
            a = a.concat(next), ++iArg;
        if( mapplet ) {
            a.push( ready );
            obj[ name+'Async' ].apply( obj, a );
        }
        else {
            results[iResult] = obj[name].apply( obj, a );
        }
    }

    var mapplet = ! window.GBrowserIsCompatible;
    var args = arguments, nArgs = args.length - 1;
    var results = [], nCalls = 0;

    for( var iArg = 1;  iArg < nArgs;  ++iArg ) {
        var name = args[iArg];
        if( typeof name == 'object' )
            obj = name;
        else
            queue( nCalls++, name, args[iArg+1] );
    }

    if( ! mapplet )
        callback();
}

And a heavily commented version that explains how it works:

// GAsync v2 by Michael Geary
// https://mg.to/2007/06/22/write-the-same-code-for-google-mapplets-and-maps-api
// Free beer and free speech license. Enjoy!
//
// Call one or more xyzAsync() functions from the Google
// Mapplet API, with a single callback that receives the
// values from all of the called functions. The first argument
// to GAsync is the object to be used. The next arguments
// are each of the function names, without the 'Async'
// suffix. The last argument is the callback function.
// To call xyzAsync() functions for more than one object,
// list another object in the argument list and the function
// names after that will use that object.
// To call an xyzAsync() function that takes arguments of
// its own (other than the callback argument), place an
// array of those arguments after the function name in
// GAsync's argument list.

// Example calls, given existing map and marker objects
/*
    // Get the size, bounds, and center of the map
    GAsync( map, 'getSize', 'getBounds', 'getCenter',
        function( size, bounds, center ) {
            // ...
        });

    // Get the zoom level, size, bounds, and center for
    // the map, as well as the lat/long of the top left
    // corner of the map. Also get the point and icon
    // for marker.
    GAsync(
        map, 'getZoom', 'getSize', 'getBounds', 'getCenter',
            'fromContainerPixelToLatLng', [ new GPoint(0,0) ],
        marker, 'getPoint', 'getIcon',
        function( zoom, size, bounds, center, topleft, point, icon ) {
            // ...
        });

    // Equivalent code using nested xyzAsync calls:
    map.getSizeAsync( function( size ) {
        map.getBoundsAsync( function( bounds ) {
            map.getCenterAsync( function( center ) {
                // ...
            });
        });
    });

    map.getZoomAsync( function( zoom ) {
        map.getSizeAsync( function( size ) {
            map.getBoundsAsync( function( bounds ) {
                map.getCenterAsync( function( center ) {
                    map.fromContainerPixelToLatLngAsync( new GPoint(0,0), function( topleft ) {
                        marker.getPointAsync( function( point ) {
                            marker.getIconAsync( function( icon ) {
                                // ...
                            });
                        });
                    });
                });
            });
        });
    });
*/

function GAsync( obj ) {

    // Call the callback function provided in the GAsync() call
    function callback() {
        args[nArgs].apply( null, results );
    }

    // Queue a single xyzAsync() function call.
    // 'iResult' is the index into the final results array.
    // 'name' is the name of the Maps API function without
    // the Async suffix.
    // 'next' is the next argument to GAsync following name;
    // If next is an array, it contains the arguments to be
    // passed to xyzAsync().
    function queue( iResult, name, next ) {

        // Callback for the xyzAsync() function that was called
        // by this invocation of the queue() function.
        // value is the return value from the Maps API.
        function ready( value ) {

            // Save the result in the final results array
            results[iResult] = value;

            // If every async function has completed, call the
            // GAsync callback (in the last argument to GAsync)
            // with the final results array as its arguments.
            if( ! --nCalls )
                callback();
        }

        // Arguments array for the xyzAsync() call
        var a = [];

        // If 'next' is an array, it contains arguments to
        // be passed to xyzAsync()
        if( next.join )  // Arrays have .join, strings do not
            a = a.concat(next), ++iArg;  // append and skip

        // Call xyzAsync() in a mapplet or xyz() in the Maps API
        if( mapplet ) {
            // The callback for xyzAsync is its last argument
            a.push( ready );

            // Call xyzAsync() with arguments in 'a'
            obj[ name+'Async' ].apply( obj, a );
        }
        else {
            // Maps API, call xyz() and save its return value
            results[iResult] = obj[name].apply( obj, a );
        }
    }

    // Is this is a mapplet or the Maps API?
    var mapplet = ! window.GBrowserIsCompatible;

    // 'args' is a reference to GAsync's arguments array
    // that can be used in the nested functions.
    // 'nArgs' is is the number of arguments, not counting
    // the callback function at the end. (Thus, args[nArgs]
    // is a reference to the callback function.)
    var args = arguments, nArgs = args.length - 1;

    // 'results' is the final results array for the callback. It
    // will be populated from the individual ready() callbacks.
    // 'nCalls' is the total number of xyzAsync() calls. It is
    // incremented as those calls are queued, and then
    // decremented to discover when all the calls are done.
    var results = [], nCalls = 0;

    // Loop through GAsync()'s arguments, starting at
    // the first function name (after 'obj'), and ending
    // before the callback function.
    for( var iArg = 1;  iArg < nArgs;  ++iArg ) {

        // Get the name of the function to be called
        var name = args[iArg];

        // If the argument is an object, not a name,
        // switch to that object for subsequent calls.
        // If it is a name, count and queue the function.
        if( typeof name == 'object' )
            obj = name// change object
        else
            queue( nCalls++, name, args[iArg+1] );
    }

    // If using the Maps API, call the callback now
    if( ! mapplet )
        callback();
}

Of course, there are still cases where you will have to run one async call after another one. If you need one piece of information as input to a subsequent call, nested async functions are the way to do it. Even then, it may be possible to combine some other async calls into a single GAsync call, wherever they don’t depend on each other’s results. You’ll shave about a quarter second off your mapplet’s response time for every call you combine using GAsync.

Enjoy your simpler and faster mapplet code!

Thanks to Ben A. of Google for mapplet design and coding tips.