Bing Maps Routing using AJAX SDK

One of the most common tasks implemented by a mapping application is routing, which essentially involves calculating directions between two locations. The route information is then visually presented on a map. In Bing Maps there are a lot of different options around routing generated by different modes of transportation; driving, walking, or transit.

The most common way of carrying out routing in Bing Maps is via the Bing Maps REST service API, which can be invoked from practically any programming language. The JavaScript SDK however wraps the REST service and exposes its functionality as simple to use JavaScript methods.

The Bing Maps V7 AJAX control is designed as a modular framework allowing users to load only the features and functionalities they need, rather than loading everything up when the application starts. In this example, we shall be using the Search module for geocoding and Directions module for routing.

Geocoding

The Bing Maps AJAX Control does not have built in functionality to return find results, but we can easily use the Bing Maps REST Services to geocode locations. The idea is that the user will provide location names for both the starting point and destination. We then call the Bing Maps REST service to geocode the location names for us.

The Bing Maps REST Services can return an XML or JSON response object. For JavaScript code, JSON is more natural, so we set output to JSON. For us to handle the response, it means that we need to also set a callback function, which in this case is the GeocodeCallback function. We need to geocode both locations which will be passed on to our DirectionsManager class for routing purposes.

JSApp-Pic-2

JSApp-Pic-3

Routing

The Microsoft.Maps.Directions API contains types that allow us to calculate route directions and display them on our map. By default, the route generated is draggable for easier customization and the route instructions are nicely formatted for easy implementation.

Before using this API reference, we must first load this module using the loadModule method. This method is part of the Bing Maps AJAX API that allow us to register and load modules for use by the map control.

JSApp-Pic-1

Once our DirectionsManager is loaded, we then need to call our directionModuleLoaded function which will initialize our class and calculate the required waypoints.

JSApp-Pic-4

 

The calculateDirections function will calculate directions based on our requests, render options and waypoints added. The directionsUpdated event fires when the calculation is complete and the route is displayed on the map. We must call this function each time we make changes to the route options.

Our final output will be as shown below:

JSApp-Pic-5 

The full project code is attached on this blog post.

Technorati Tags: Bing Maps,AJAX SDK,Javascript,HTML 5,Maps

Sample-Code.zip