Bing Maps Ajax 7: Add Custom Navigation Bar Buttons using jQuery

The Bing Maps Ajax v7 control does not include support for adding custom buttons to the navigation bar (where the zoom, pan and map style buttons are). There may be times when you will want to add a custom button or two, and this post contains some simple code that will help you do so.
Here’s a screenshot of this in action. The ‘Click Me’ link in the navigation bar is a custom button that the below code adds.

Code

First, here’s the code that I came up with to add custom navigation bar buttons:

// Simple Method to Add a Custom Button to the NavBar using jQuery
var addNavButton = function (mapElement, content, onclick) {
    $(mapElement).find('.NavBar_typeButtonContainer').append(
        // Add a Separator between this button and any existing buttons
        $('').addClass('NavBar_separator')
    ).append(
        // Add the Custom Button itself
        $('<a>').attr('href', '#').addClass('NavBar_button').
            append($('').html(content).click(onclick))
    );
};
// Use setTimeout to load Custom NavBar button if you are adding
// the button immediatly after instantiating the map.
// Timeout is needed since Bing Maps 7 doesn't currently have
// any kind of "onload" event to handle.
window.setTimeout(function () {
    // Add Custom Button to NavBar
    addNavButton(
        document.getElementById('myMap'), // <- Maps DIV
        'Click Me', // <- Content of Button - You can put HTML in here if you want
        function () { // <- Method to call during buttons Click event
            alert('You Clicked Me!');
        }
    );
}, 100);</pre>


## Explanations

The above code does require the jQuery library, which is how this code is so short and simple.

If you call the ‘addNavButton’ function immediately after instantiating the Bing Map, then you will need to include a ‘window.setTimeout’ (as in the code above) to make sure that the Map has finished loading before you try to add the custom button. This is necessary because the Bing Maps Ajax v7 control doesn’t include any kind of ‘onload’ event to be handled.