Skip to main content

Routing

  • 6 minutes to read

The Map control supports Microsoft’s Bing Route service. This service provides the most optimal route, either from major roads in four directions, or calculated between two or more locations on a map.

MapControl_BingRouteDataProvider

The Bing Route data provider provides the Map control’s routing functionality and is represented by the BingRouteDataProvider object. The sections below explain how to use the BingRouteDataProvider in the map control.

Important

Due to Bing canceled the SOAP service on July 30, 2017, the Map Control’s Bing Routing provider does not work properly in versions earlier than 16.1.

Enable Routing

Do the following to enable routing in the Map control:

The code snippet below shows how to do this.

private void Form1_Load(object sender, System.EventArgs e) {
    // ...
    BingRouteDataProvider routeDataProvider = new BingRouteDataProvider {
        BingKey = yourBingKey
    };
    map.Layers.Add(new InformationLayer {
        DataProvider = routeDataProvider
    });
}

There are two ways to use the map routing feature in your application, depending on your task:

  • Calculate a route between two or more locations on a map;
  • Get a route from major roads to the specified destination.

The sections below describe each approach.

Calculate a Route between Locations

When the Map control is connected to the Bing Route service (see the section above for details), you can calculate a route between two or more locations on a map. To accomplish this, call the BingRouteDataProvider.CalculateRoute method and pass the list of locations (waypoints) as its argument, as shown below.

private void Form1_Load(object sender, System.EventArgs e) {
    // ...
    // Create three waypoints and add them to the route waypoints list.
    List<RouteWaypoint> waypoints = new List<RouteWaypoint>();
    waypoints.Add(new RouteWaypoint("NY", new GeoPoint(41.145556, -73.995)));
    waypoints.Add(new RouteWaypoint("Oklahoma", new GeoPoint(36.131389, -95.937222)));
    waypoints.Add(new RouteWaypoint("Las Vegas", new GeoPoint(36.175, -115.136389)));

    // Call the BingRouteDataProvider.CalculateRoute method.
    routeDataProvider.CalculateRoute(waypoints);
}

The image below shows the calculated route between the specified locations on the map.

RouteBetweenWaypoints

Calculate Routes from Major Roads

The Map control allows you to obtain different routes to a specified location (latitude and longitude coordinates) using major roads from the north, east, south, and west. If it cannot find major roads coming from these directions, the response may contain more than one route from the same direction or fewer than four routes.

For instance, an application UI contains two text boxes named “tbLatitude” and “tbLongitude”, and a button named “calculateRoutes”.

To start a route calculation, click the Calculate Routes button. This calls the BingRouteDataProvider.CalculateRoutesFromMajorRoads method and a destination location (waypoint coordinates and description) and options are passed to its argument.

string description = "Route Waypoint";
double lat;
double lon;    

private void bCalculateRoutes_Click(object sender, EventArgs e) {
    RouteProvider.CalculateRoutesFromMajorRoads(
        new RouteWaypoint( description, new GeoPoint(lat, lon) )
    );
}

The results for San Francisco (Latitude - “37.783333” and Longitude - “-122.416667”) are shown in the image below.

RoutesFromSanFranciscoRoads

Routing Result

The RouteCalculationResult object that is provided by the BingRouteDataProvider.RouteCalculated event handler arguments’ BingRouteCalculatedEventArgs.CalculationResult stores the route calculation results from the Bing Route service.

For instance, you can access a route path between locations calculated in the Calculate a Route between Locations section of this document.

To accomplish this, handle the BingRouteDataProvider.RouteCalculated event.

View Example

private void OnRouteCalculated(object sender, BingRouteCalculatedEventArgs e) {
    RouteCalculationResult result = e.CalculationResult;
    if((result.RouteResults == null) ||
        (result.ResultCode == RequestResultCode.BadRequest)) {
        rtbResults.Text = "The Bing Route service does not work for this location.";
        return;
    }

    StringBuilder resultList = new StringBuilder("");

    if(result.IntermediatePoints != null) {
        resultList.Append(String.Format("_________________________\n"));

        for(int i = 0; i < e.CalculationResult.IntermediatePoints.Count; i++)
            resultList.Append(
                String.Format("Starting point {0}: {1} ({2})\n",
                i + 1,
                e.CalculationResult.IntermediatePoints[i].Description,
                e.CalculationResult.IntermediatePoints[i].Location)
            );
    }

    if((result.RouteResults != null) & (result.ResultCode == RequestResultCode.Success)) {

        for(int rnum = 0; rnum < e.CalculationResult.RouteResults.Count; rnum++) {
            resultList.Append(String.Format("_________________________\n"));
            resultList.Append(String.Format("Path {0}:\n", rnum + 1));
            resultList.Append(String.Format(
                "Distance: {0}\n",
                e.CalculationResult.RouteResults[rnum].Distance
            ));
            resultList.Append(String.Format(
                "Time: {0}\n",
                e.CalculationResult.RouteResults[0].Time
            ));

            if(e.CalculationResult.RouteResults[rnum].Legs != null) {
                int legNum = 1;
                foreach(BingRouteLeg leg in e.CalculationResult.RouteResults[rnum].Legs) {
                    resultList.Append(String.Format("\tLeg {0}:\n", legNum++));
                    resultList.Append(String.Format("\tDistance: {0}\n", leg.Distance));
                    resultList.Append(String.Format("\tTime: {0}\n", leg.Time));
                    if(leg.Itinerary != null) {
                        foreach(BingItineraryItem itineraryItem in leg.Itinerary) {
                            resultList.Append(String.Format(itineraryItem.Maneuver + "\n"));
                            resultList.Append(String.Format(
                                "\t\tLocation: {0}\n",
                                itineraryItem.Location
                            ));
                        }
                    }
                }
            }
        }
    }
    rtbResults.Text = resultList.ToString();
}

The result is shown in the image below.

RoutePathCustomization

Examples

The following examples demonstrate how to use the routing feature in the map control:

See Also