Using Bing Maps with Require.js

Recently I’ve been doing quite a lot of work with Bing Maps. Not every page on the site requires the map API so we’ve been attempting to use require.js, which we already have, to maintain that dependancy.

As usual it’s more complicated than we’d hoped. Bing Maps provides a callback hook that we can use with the async plugin of require.js, however the callback fires before the maps are actually ready to use. The Microsoft object is defined but the Maps and Location objects are not. This led us to implement polling to check for these properties before resolving a deferred.

Why this is bad: The require module is now returning a promise rather than the maps declaration that you might expect to be returned. In practice this is manageable because by using the deferred our code can continue regardless of the Maps loaded state.

I’ve created a sample Gist of how this can work, although for production you may also want to handle the failure case and reject the deferred.


Filed under: JavaScript