windowsforms-devexpress-dot-xtramap-5fafa908.md
The class that communicates with Azure Maps Route service.
Namespace : DevExpress.XtraMap
Assembly : DevExpress.XtraMap.v25.2.dll
NuGet Package : DevExpress.Win.Map
public class AzureRouteDataProvider :
AzureMapDataProviderBase
Public Class AzureRouteDataProvider
Inherits AzureMapDataProviderBase
The AzureRouteDataProvider implements the Azure Maps Route service. Assign such an object to the InformationLayer.DataProvider property to enable the service and allow users to calculate a route on a map.
Azure Maps services support JSON response formats. Install the System.Text.Json package in projects that target .NET Framework to parse the Azure server response and display information on a DevExpress Map control.
Call one of the AzureRouteDataProvider.CalculateRoute method overloads to calculate a route between the specified origin and destination, passing through the selected waypoints.
The AzureRouteOptions parameter of the AzureRouteDataProvider.CalculateRoute method overload allows you to specify route options.
The following settings are available:
AzureRouteOptions.TravelModeSpecifies the transportation / commute mode.AzureRouteOptions.MaxAlternativesSpecifies the number of alternative routes to be calculated.AzureRouteOptions.AvoidTypesSpecifies items that AzureRouteDataProvider should try to avoid when calculating the route.AzureRouteOptions.CustomParametersSpecifies additional route definitions.
The following example calculates a car-optimized route through the specified waypoints:
using DevExpress.XtraMap;
// ...
const string key = "your key";
// ...
private void Form1_Load(object sender, EventArgs e) {
MapControl map = new MapControl();
// Specify the map position on the form.
map.Dock = DockStyle.Fill;
// Create a layer.
ImageLayer image = new ImageLayer();
image.DataProvider = new AzureMapDataProvider(){
AzureKey = key,
};
AzureRouteDataProvider routeProvider = new AzureRouteDataProvider();
routeProvider.AzureKey = key;
// 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 AzureRouteDataProvider.CalculateRoute method.
azureRoute.CalculateRoute(waypoints, new AzureRouteOptions() {
TravelMode = AzureTravelMode.Car,
AvoidTypes = AzureRouteAvoidType.AlreadyUsedRoads
});
InformationLayer route = new InformationLayer();
route.DataProvider = routeProvider;
map.Layers.AddRange(new LayerBase[] { image, route});
this.Controls.Add(map);
}
Imports DevExpress.XtraMap
' ...
Private Const key As String = "your key"
' ...
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim map As New MapControl()
' Specify the map position on the form.
map.Dock = DockStyle.Fill
' Create a layer.
Dim image As New ImageLayer()
image.DataProvider = New AzureMapDataProvider() With {.AzureKey = key}
Dim routeProvider As New AzureRouteDataProvider()
routeProvider.AzureKey = key
' Create three waypoints and add them to the route waypoints list.
Dim waypoints As New List(Of 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 AzureRouteDataProvider.CalculateRoute method.
azureRoute.CalculateRoute(waypoints, New AzureRouteOptions() With {
.TravelMode = AzureTravelMode.Car,
.AvoidTypes = AzureRouteAvoidType.AlreadyUsedRoads
})
Dim route As New InformationLayer()
route.DataProvider = routeProvider
map.Layers.AddRange(New LayerBase() { image, route})
Me.Controls.Add(map)
End Sub
The following example calculates a route based on two or more RouteWaypoint objects.
Right-click on a map surface to specify waypoints: origin, destination, and points between. ListBox entries display geographical points (GeoPoint.Longitude and GeoPoint.Latitude). The “Calculate Route” button initiates the routing request by obtaining the waypoint information and passing it to the CalculateRoute method. The ComboBoxEdit and CheckedListBox editors specify route options (AzureRouteOptions.AvoidTypes and AzureRouteOptions.TravelMode properties).
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraMap;
namespace AzureRouting {
public partial class Form1 : Form {
const string azureKey = "your key";
ObservableCollection<GeoPoint> geoPoints = new ObservableCollection<GeoPoint>();
MapItemStorage itemData;
InformationLayer routeInfoLayer;
AzureRouteDataProvider azureRoute;
public Form1() {
InitializeComponent();
mapControl.Layers.AddRange(
new LayerBase[] {
new ImageLayer() {
DataProvider = new AzureMapDataProvider() {
AzureKey = azureKey,
Tileset = AzureTileset.Imagery,
},
},
new ImageLayer() {
DataProvider = new AzureMapDataProvider() {
AzureKey = azureKey,
Tileset = AzureTileset.BaseHybridRoad,
},
},
routeInfoLayer = new InformationLayer() {
DataProvider = azureRoute = new AzureRouteDataProvider() {
AzureKey = azureKey,
},
},
new VectorItemsLayer() {
Data = itemData = new MapItemStorage(),
}
}
);
routeInfoLayer.ItemStyle.StrokeWidth = 2;
routeInfoLayer.ItemStyle.Stroke = Color.DeepSkyBlue;
routeInfoLayer.Error += RouteInfoLayer_Error;
waypointsListBoxControl.DataSource = geoPoints;
mapControl.Zoom(6);
mapControl.SetCenterPoint(new GeoPoint(40.714627, -74.002863), false);
mapControl.EnableRotation = false;
}
private void RouteInfoLayer_Error(object sender, MapErrorEventArgs e) {
throw new System.NotImplementedException();
}
private void mapControl_Click(object sender, System.EventArgs e) {
MouseEventArgs mouseEventArgs = (MouseEventArgs)e;
if(mouseEventArgs.Button == MouseButtons.Right) {
GeoPoint mousePoint = mapControl.ScreenPointToCoordPoint(mouseEventArgs.Location) as GeoPoint;
geoPoints.Add(mousePoint);
itemData.Items.Add(new MapPushpin() {
Location = mousePoint,
});
}
}
private void calculateRouteButton_Click(object sender, System.EventArgs e) {
if (geoPoints.Count <= 1) {
MessageBox.Show("Specify at least two Waypoints to calculate a route.");
return;
}
azureRoute.CalculateRoute(geoPoints.Select(point => new RouteWaypoint("", point)).ToList(), new AzureRouteOptions() {
TravelMode = GetTravelMode(),
AvoidTypes = GetAvoidTypes()
});
geoPoints.Clear();
itemData.Items.Clear();
}
AzureTravelMode GetTravelMode() {
return (AzureTravelMode)Enum.Parse(typeof(AzureTravelMode), (string)travelModeComboBox.SelectedItem);
}
AzureRouteAvoidType GetAvoidTypes() {
var avoidTypes = AzureRouteAvoidType.None;
foreach (string item in avoidTypesCheckedListBox.CheckedItems) {
var avoidType = (AzureRouteAvoidType)Enum.Parse(typeof(AzureRouteAvoidType), item);
avoidTypes |= avoidType;
}
return avoidTypes;
}
}
}
Imports System.Collections.Generic
Imports System.Collections.ObjectModel
Imports System.Drawing
Imports System.Linq
Imports System.Windows.Forms
Imports DevExpress.XtraMap
Namespace AzureRouting
Partial Public Class Form1
Inherits Form
Private Const azureKey As String = "your key"
Private geoPoints As New ObservableCollection(Of GeoPoint)()
Private itemData As MapItemStorage
Private routeInfoLayer As InformationLayer
Private azureRoute As AzureRouteDataProvider
Public Sub New()
InitializeComponent()
mapControl.Layers.AddRange(New LayerBase() {
New ImageLayer() With {
.DataProvider = New AzureMapDataProvider() With {
.AzureKey = azureKey,
.Tileset = AzureTileset.Imagery
}
},
New ImageLayer() With {
.DataProvider = New AzureMapDataProvider() With {
.AzureKey = azureKey,
.Tileset = AzureTileset.BaseHybridRoad
}
},
routeInfoLayer = New InformationLayer() With {
.DataProvider = azureRoute = New AzureRouteDataProvider() With {.AzureKey = azureKey}
},
New VectorItemsLayer() With {.Data = itemData = New MapItemStorage()}
})
routeInfoLayer.ItemStyle.StrokeWidth = 2
routeInfoLayer.ItemStyle.Stroke = Color.DeepSkyBlue
AddHandler routeInfoLayer.Error, AddressOf RouteInfoLayer_Error
waypointsListBoxControl.DataSource = geoPoints
mapControl.Zoom(6)
mapControl.SetCenterPoint(New GeoPoint(40.714627, -74.002863), False)
mapControl.EnableRotation = False
End Sub
Private Sub RouteInfoLayer_Error(ByVal sender As Object, ByVal e As MapErrorEventArgs)
Throw New System.NotImplementedException()
End Sub
Private Sub mapControl_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim mouseEventArgs As MouseEventArgs = CType(e, MouseEventArgs)
If mouseEventArgs.Button = MouseButtons.Right Then
Dim mousePoint As GeoPoint = TryCast(mapControl.ScreenPointToCoordPoint(mouseEventArgs.Location), GeoPoint)
geoPoints.Add(mousePoint)
itemData.Items.Add(New MapPushpin() With {.Location = mousePoint})
End If
End Sub
Private Sub calculateRouteButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If geoPoints.Count <= 1 Then
MessageBox.Show("Specify at least two Waypoints to calculate a route.")
Return
End If
azureRoute.CalculateRoute(geoPoints.Select(Function(point) New RouteWaypoint("", point)).ToList(), New AzureRouteOptions() With {
.TravelMode = GetTravelMode(),
.AvoidTypes = GetAvoidTypes()
})
geoPoints.Clear()
itemData.Items.Clear()
End Sub
Private Function GetTravelMode() As AzureTravelMode
Return DirectCast(System.Enum.Parse(GetType(AzureTravelMode), CStr(travelModeComboBox.SelectedItem)), AzureTravelMode)
End Function
Private Function GetAvoidTypes() As AzureRouteAvoidType
Dim avoidTypes = AzureRouteAvoidType.None
For Each item As String In avoidTypesCheckedListBox.CheckedItems
Dim avoidType = DirectCast(System.Enum.Parse(GetType(AzureRouteAvoidType), item), AzureRouteAvoidType)
avoidTypes = avoidTypes Or avoidType
Next item
Return avoidTypes
End Function
End Class
End Namespace
The following example displays detailed information about the calculated route:
The button click initiates the routing request. The CalculateRoute method is called in the button click event handler.
The RouteCalculated event is handled to process the request result. e.CalculationResult gets the AzureRouteCalculationResult object that contains the result of the route calculation and allow you to obtain the following information:
An AzureRouteCalculationResult.IntermediatePoints collection. You can obtain the Description and Location of each RouteWaypoint in the list.
An AzureRouteCalculationResult.RouteResults collection. You can obtain summary information about the route, its legs and sections. For example, TravelLengthMeters, TravelTimeSeconds Arrival and Departure time.
using DevExpress.XtraMap;
using System.Text;
// ...
const string key = "your key";
// ...
routeProvider = new AzureRouteDataProvider { AzureKey = key };
routeProvider.RouteCalculated += OnRouteCalculated;
// ...
private void OnCalculateRoutesClick(object sender, EventArgs e) {
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)));
routeProvider.CalculateRoute(waypoints, new AzureRouteOptions() {
TravelMode = AzureTravelMode.Car
});
}
private void OnRouteCalculated(object sender, AzureRouteCalculatedEventArgs e) {
AzureRouteCalculationResult result = e.CalculationResult;
if ((result.RouteResults == null) ||
(result.ResultCode == RequestResultCode.BadRequest)) {
MessageBox.Show("The Azure 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("Waypoint {0}: {1} ({2})\n",
i + 1,
e.CalculationResult.IntermediatePoints[i].Description,
e.CalculationResult.IntermediatePoints[i].Location)
);
}
if (result.RouteResults != null) {
for (int rnum = 0; rnum < e.CalculationResult.RouteResults.Count; rnum++) {
var routeSummary = e.CalculationResult.RouteResults[rnum].Summary;
resultList.AppendLine(" _________________________");
resultList.AppendLine($"Path {rnum + 1} summary:");
resultList.AppendLine($"Travel Distance: {GetDistanceString(routeSummary)}");
resultList.AppendLine($"Travel Time: {GetTravelTimeString(routeSummary)}");
if (e.CalculationResult.RouteResults[rnum].Legs != null){
int legNum = 1;
foreach (AzureRouteLeg leg in e.CalculationResult.RouteResults[rnum].Legs){
resultList.AppendLine($"\tLeg {legNum++}");
resultList.AppendLine($"\tDistance: {GetDistanceString(leg.Summary)}");
resultList.AppendLine($"\tTravel Time: {GetTravelTimeString(leg.Summary)}");
resultList.AppendLine($"\tDeparture Time: {leg.Summary.Departure}");
resultList.AppendLine($"\tArrival Time: {leg.Summary.Arrival}");
resultList.AppendLine($"\tDeviation Time: {leg.Summary.DeviationTime}");
}
}
}
}
MessageBox.Show(resultList.ToString());
}
static string GetTravelTimeString(AzureRouteSummary summary) {
var timeSpan = TimeSpan.FromSeconds(summary.TravelTimeSeconds);
return $"{timeSpan.Days}d, {timeSpan.Hours}hr, {timeSpan.Minutes}min";
}
static string GetDistanceString(AzureRouteSummary summary) {
return String.Format("{0:0.00}km", (double)summary.TravelLengthMeters / 1000);
}
Imports DevExpress.XtraMap
Imports System.Text
' ...
Private Const key As String = "your key"
' ...
routeProvider = New AzureRouteDataProvider With {.AzureKey = key}
AddHandler routeProvider.RouteCalculated, AddressOf OnRouteCalculated
' ...
Private Sub OnCalculateRoutesClick(ByVal sender As Object, ByVal e As EventArgs)
Dim waypoints As New List(Of 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)))
routeProvider.CalculateRoute(waypoints, New AzureRouteOptions() With {.TravelMode = AzureTravelMode.Car})
End Sub
Private Sub OnRouteCalculated(ByVal sender As Object, ByVal e As AzureRouteCalculatedEventArgs)
Dim result As AzureRouteCalculationResult = e.CalculationResult
If (result.RouteResults Is Nothing) OrElse (result.ResultCode = RequestResultCode.BadRequest) Then
MessageBox.Show("The Azure Route service does not work for this location.")
Return
End If
Dim resultList As New StringBuilder("")
If result.IntermediatePoints IsNot Nothing Then
resultList.Append(String.Format(" _________________________" & vbLf))
For i As Integer = 0 To e.CalculationResult.IntermediatePoints.Count - 1
resultList.Append(String.Format("Waypoint {0}: {1} ({2})" & vbLf, i + 1, e.CalculationResult.IntermediatePoints(i).Description, e.CalculationResult.IntermediatePoints(i).Location))
Next i
End If
If result.RouteResults IsNot Nothing Then
For rnum As Integer = 0 To e.CalculationResult.RouteResults.Count - 1
Dim routeSummary = e.CalculationResult.RouteResults(rnum).Summary
resultList.AppendLine(" _________________________")
resultList.AppendLine($"Path {rnum + 1} summary:")
resultList.AppendLine($"Travel Distance: {GetDistanceString(routeSummary)}")
resultList.AppendLine($"Travel Time: {GetTravelTimeString(routeSummary)}")
If e.CalculationResult.RouteResults(rnum).Legs IsNot Nothing Then
Dim legNum As Integer = 1
For Each leg As AzureRouteLeg In e.CalculationResult.RouteResults(rnum).Legs
resultList.AppendLine($vbTab & "Leg {legNum++}")
resultList.AppendLine($vbTab & "Distance: {GetDistanceString(leg.Summary)}")
resultList.AppendLine($vbTab & "Travel Time: {GetTravelTimeString(leg.Summary)}")
resultList.AppendLine($vbTab & "Departure Time: {leg.Summary.Departure}")
resultList.AppendLine($vbTab & "Arrival Time: {leg.Summary.Arrival}")
resultList.AppendLine($vbTab & "Deviation Time: {leg.Summary.DeviationTime}")
Next leg
End If
Next rnum
End If
MessageBox.Show(resultList.ToString())
End Sub
Shared Function GetTravelTimeString(ByVal summary As AzureRouteSummary) As String
Dim timeSpan = System.TimeSpan.FromSeconds(summary.TravelTimeSeconds)
Return $"{timeSpan.Days}d, {timeSpan.Hours}hr, {timeSpan.Minutes}min"
End Function
Shared Function GetDistanceString(ByVal summary As AzureRouteSummary) As String
Return String.Format("{0:0.00}km", CDbl(summary.TravelLengthMeters) / 1000)
End Function
Object InformationDataProviderBase WebInformationDataProvider AzureMapDataProviderBase AzureRouteDataProvider
See Also