Back to Devexpress

AzureRouteDataProvider Class

wpf-devexpress-dot-xpf-dot-map-4c31dde4.md

latest18.6 KB
Original Source

AzureRouteDataProvider Class

Allows you to use the Azure Maps Route service to build a route.

Namespace : DevExpress.Xpf.Map

Assembly : DevExpress.Xpf.Map.v25.2.dll

NuGet Package : DevExpress.Wpf.Map

Declaration

csharp
public class AzureRouteDataProvider :
    AzureMapDataProviderBase
vb
Public Class AzureRouteDataProvider
    Inherits AzureMapDataProviderBase

Remarks

The AzureRouteDataProvider allows you to connect to the Azure Maps Route service. Assign this 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 map.

Calculate a Route Between Locations

Call the AzureRouteDataProvider.CalculateRoute method to calculate a route between the specified origin and destination, passing through the selected waypoints.

The AzureRouteOptions parameter of the AzureRouteDataProvider.CalculateRoute method 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. Default: 0, minimum: 0 and maximum: 5.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:

xaml
<Window xmlns:dxm="http://schemas.devexpress.com/winfx/2008/xaml/map"...>
    <Window.Resources>
        <sys:String x:Key="azureKey">
            Your Azure Maps key string here.
        </sys:String>
    </Window.Resources>
    <Grid>
        <dxm:MapControl Loaded="MapControl_Loaded" x:Name="mapControl">
            <dxm:ImageLayer>
                <dxm:AzureMapDataProvider AzureKey="{StaticResource azureKey}" Tileset="BaseRoad"/>
            </dxm:ImageLayer>
            <dxm:InformationLayer x:Name="infoLayer">
                <dxm:AzureRouteDataProvider x:Name="routeProvider" AzureKey="{StaticResource azureKey}"/>
            </dxm:InformationLayer>
        </dxm:MapControl>
    </Grid>
</Window>
csharp
using DevExpress.Xpf.Map;
using System.Windows;

namespace WpfMapExample {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
        }
        private void MapControl_Loaded(object sender, RoutedEventArgs e) {

            List<RouteWaypoint> waypoints = new List<RouteWaypoint> {
                   new RouteWaypoint("NY", new GeoPoint(41.145556, -73.995)),
                   new RouteWaypoint("Oklahoma", new GeoPoint(36.131389, -95.937222)),
                   new RouteWaypoint("Las Vegas", new GeoPoint(36.175, -115.136389))
            };
            // Calculate a route between three waypoints:
            routeProvider.CalculateRoute(waypoints, new AzureRouteOptions() {
                TravelMode = AzureTravelMode.Car,
                AvoidTypes = AzureRouteAvoidType.AlreadyUsedRoads
            });
        }
        private void OnLayerItemsGenerating(object sender, LayerItemsGeneratingEventArgs args) {
            mapControl.ZoomToFit(args.Items);
        }
    }
}
vb
Imports DevExpress.Xpf.Map
Imports System.Windows

Namespace WpfMapExample
    Public Partial Class MainWindow
        Inherits Window

        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub MapControl_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Dim waypoints As List(Of RouteWaypoint) = New List(Of RouteWaypoint) From {
                New RouteWaypoint("NY", New GeoPoint(41.145556, -73.995)),
                New RouteWaypoint("Oklahoma", New GeoPoint(36.131389, -95.937222)),
                New RouteWaypoint("Las Vegas", New GeoPoint(36.175, -115.136389))
            }
            ' Calculate a route between three waypoints:
            routeProvider.CalculateRoute(waypoints, New AzureRouteOptions() With {
                .TravelMode = AzureTravelMode.Car,
                .AvoidTypes = AzureRouteAvoidType.AlreadyUsedRoads
            })
        End Sub

        Private Sub OnLayerItemsGenerating(ByVal sender As Object, ByVal args As LayerItemsGeneratingEventArgs)
            mapControl.ZoomToFit(args.Items)
        End Sub
    End Class
End Namespace

Obtain Routing Result

The following example calculates a route and displays route details such the estimated duration and distance:

The Calculate route 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:

xaml
<Window xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
        xmlns:dxm="http://schemas.devexpress.com/winfx/2008/xaml/map"
        xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" ...>
    <Window.Resources>
        <sys:String x:Key="azureKey">Your AzureMaps key here</sys:String>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="250"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <dxe:ListBoxEdit Grid.Column="0" Grid.Row="1" x:Name="listbox"/>
        <dx:SimpleButton Grid.Row="0" Content="Calculate route" Click="SimpleButton_Click"/>
        <dxm:MapControl Loaded="MapControl_Loaded" x:Name="mapControl" Grid.Column="1" Grid.RowSpan="2"
                        ToolTipEnabled="True" 
                        ShowSearchPanel="False" 
                        ZoomLevel="3">
            <dxm:MapControl.ZoomTrackbarOptions>
                <dxm:ZoomTrackbarOptions Visible="False" />
            </dxm:MapControl.ZoomTrackbarOptions>
            <dxm:ImageLayer>
                <dxm:AzureMapDataProvider AzureKey="{StaticResource azureKey}" Tileset="BaseRoad"/>
            </dxm:ImageLayer>
            <dxm:InformationLayer x:Name="infoLayer">
                <dxm:AzureRouteDataProvider x:Name="routeProvider" 
                                            AzureKey="{StaticResource azureKey}" 
                                            RouteCalculated="routeProvider_RouteCalculated"
                                            LayerItemsGenerating="OnLayerItemsGenerating" 
                                            RouteStroke="Blue"/>
            </dxm:InformationLayer>
        </dxm:MapControl>
    </Grid>
</Window>
csharp
using DevExpress.Xpf.Map;
using System.Text;
using System.Windows;

namespace WpfMapExample {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();
        }
        private void OnLayerItemsGenerating(object sender, LayerItemsGeneratingEventArgs args) {
            mapControl.ZoomToFit(args.Items);
        }
        private void SimpleButton_Click(object sender, RoutedEventArgs e) {
            List<RouteWaypoint> waypoints = new List<RouteWaypoint> {
                   new RouteWaypoint("NY", new GeoPoint(41.145556, -73.995)),
                   new RouteWaypoint("Oklahoma", new GeoPoint(36.131389, -95.937222)),
                   new RouteWaypoint("Las Vegas", new GeoPoint(36.175, -115.136389))
            };
            // Calculate a route between three waypoints:
            routeProvider.CalculateRoute(waypoints, new AzureRouteOptions() {
                TravelMode = AzureTravelMode.Car,
                AvoidTypes = AzureRouteAvoidType.AlreadyUsedRoads
            });
        }
        private void routeProvider_RouteCalculated(object sender, AzureRouteCalculatedEventArgs e) {
            AzureRouteCalculationResult result = e.CalculationResult;
            if ((result.RouteResults == null) ||
                (result.ResultCode == RequestResultCode.BadRequest)) {
                listbox.Items.Add("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}");
                        }
                    }
                }
            }
            listbox.Items.Add(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);
        }
    }
}
vb
Imports DevExpress.Xpf.Map
Imports System.Text
Imports System.Windows

Namespace WpfMapExample
    Public Partial Class MainWindow
        Inherits Window

        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub OnLayerItemsGenerating(ByVal sender As Object, ByVal args As LayerItemsGeneratingEventArgs)
            mapControl.ZoomToFit(args.Items)
        End Sub

        Private Sub SimpleButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Dim waypoints As List(Of RouteWaypoint) = New List(Of RouteWaypoint) From {
                New RouteWaypoint("NY", New GeoPoint(41.145556, -73.995)),
                New RouteWaypoint("Oklahoma", New GeoPoint(36.131389, -95.937222)),
                New RouteWaypoint("Las Vegas", New GeoPoint(36.175, -115.136389))
            }
            routeProvider.CalculateRoute(waypoints, New AzureRouteOptions() With {
                .TravelMode = AzureTravelMode.Car,
                .AvoidTypes = AzureRouteAvoidType.AlreadyUsedRoads
            })
        End Sub

        Private Sub routeProvider_RouteCalculated(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
                listbox.Items.Add("The Azure Route service does not work for this location.")
                Return
            End If

            Dim resultList As StringBuilder = 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
            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($"\tLeg {Math.Min(System.Threading.Interlocked.Increment(legNum), legNum - 1)}")
                            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}")
                        Next
                    End If
                Next
            End If
            listbox.Items.Add(resultList.ToString())
        End Sub
        Private Shared Function GetTravelTimeString(ByVal summary As AzureRouteSummary) As String
            Dim timeSpan = TimeSpan.FromSeconds(summary.TravelTimeSeconds)
            Return $"{timeSpan.Days}d, {timeSpan.Hours}hr, {timeSpan.Minutes}min"
        End Function

        Private Shared Function GetDistanceString(ByVal summary As AzureRouteSummary) As String
            Return String.Format("{0:0.00}km", CDbl(summary.TravelLengthMeters) / 1000)
        End Function
    End Class
End Namespace

Implements

ISupportWebRequest

Inheritance

Object DispatcherObject DependencyObject Freezable MapDependencyObject InformationDataProviderBase WebInformationDataProvider<DevExpress.Map.Native.JsonProvidedEventArgs> AzureMapDataProviderBase AzureRouteDataProvider

See Also

AzureRouteDataProvider Members

DevExpress.Xpf.Map Namespace