private async void Sale(RouteRequest routeRequest) { var response = await routeRequest.Execute(); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { var route = response.ResourceSets[0].Resources[0] as Route; var coords = route.RoutePath.Line.Coordinates; //This is 2D array of lat/long values. var locs = new LocationCollection(); for (int i = 0; i < coords.Length; i++) { locs.Add(new Microsoft.Maps.MapControl.WPF.Location(coords[i][0], coords[i][1])); } var routeLine = new MapPolyline() { Locations = locs, Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue), StrokeThickness = 5 }; mMap.Children.Add(routeLine); } }
/// <summary> /// Requests the truck route information needed for a matrix cell. /// </summary> /// <param name="origin">Origin of the route.</param> /// <param name="destination">Destination of the route.</param> /// <param name="timeIdx">The time interval index.</param> /// <param name="dmRequest">The distance matrix request.</param> /// <returns>Truck route information needed for a matrix cell.</returns> private async Task <Response> CalculateTruckRoute(SimpleWaypoint origin, SimpleWaypoint destination, int timeIdx, DistanceMatrixRequest dmRequest) { var request = new RouteRequest() { BingMapsKey = dmRequest.BingMapsKey, Culture = dmRequest.Culture, Domain = dmRequest.Domain, UserIp = dmRequest.UserIp, UserLocation = dmRequest.UserLocation, UserMapView = dmRequest.UserMapView, UserRegion = dmRequest.UserRegion, RouteOptions = new RouteOptions() { MaxSolutions = 1, DistanceUnits = dmRequest.DistanceUnits, Optimize = RouteOptimizationType.Time, TravelMode = TravelModeType.Truck, VehicleSpec = dmRequest.VehicleSpec }, Waypoints = new List <SimpleWaypoint>() { origin, destination } }; if (TimeIntervals != null && timeIdx >= 0) { request.RouteOptions.DateTime = TimeIntervals[timeIdx]; request.RouteOptions.Optimize = RouteOptimizationType.TimeWithTraffic; } return(await request.Execute().ConfigureAwait(false)); }
// UPDATED (old method is left commented out below updated method) // create route between 2 waypoints using Bing maps public List <MyWaypoint> CreateRoute(MyWaypoint startPoint, MyWaypoint endPoint) { //MessageBox.Show("CreateRoute method called!");// FOR DEBUGGING PURPOSES // create route from waypointString RouteRequest routeRequest = new RouteRequest() { // create Start and End SimpleWaypoints by passing in lat/lon of startPoint and endPoint Waypoints = new List <SimpleWaypoint>() { new SimpleWaypoint(startPoint.Latitude, startPoint.Longitude), new SimpleWaypoint(endPoint.Latitude, endPoint.Longitude) }, BingMapsKey = m_bingMapKey }; // define response (we want Route Path) routeRequest.RouteOptions = new RouteOptions(); routeRequest.RouteOptions.RouteAttributes = new List <RouteAttributeType>() { RouteAttributeType.RoutePath }; routeRequest.RouteOptions.Optimize = RouteOptimizationType.Distance; // create Route request //MessageBox.Show("Executing route request!"); var routeResponse = routeRequest.Execute().Result; //MessageBox.Show("Executed route request!"); // show message if route not returned? if (routeResponse.ResourceSets.Length <= 0) { System.Console.WriteLine("No Path Found"); return(null); } // pull out the lat/lon values List <MyWaypoint> returnPoints = new List <MyWaypoint>(); var route = routeResponse.ResourceSets[0].Resources[0] as Route; // var result = routeResponse.ResourceSets[0].Resources as BingMapsRESTToolkit.Location[]; //MessageBox.Show("Distance: " + routeResponse.Result.Summary.Distance.ToString() // + " Time: " + routeResponse.Result.Summary.TimeInSeconds.ToString()); // define and add points to returnPoints foreach (var point in route.RoutePath.Line.Coordinates) { MyWaypoint myWaypoint = new MyWaypoint(); myWaypoint.Latitude = point[0]; myWaypoint.Longitude = point[1]; //thisPoint.Altitude = GetAltitude(thisPoint.Latitude, thisPoint.Longitude); myWaypoint.Altitude = 0.0; returnPoints.Add(myWaypoint); } //MessageBox.Show("CreateRoute method finished!"); //FOR DEBUGGING PURPOSES return(returnPoints); }
/// <summary> /// Logika routingu. /// Skorzystałem z BingMapsRESTToolkit /// </summary> /// <param name="fwp">FirstWaypoint - Lokalizacja jednego pina - tego ze zwierzakiem</param> /// <param name="swp">SecondWaypoint - Lokalizacja drugiego pina - destynacji</param> /// <param name="key">Klucz do map bing</param> /// <param name="map">Referencja do mapy, aby dodać do niej drogę</param> /// <returns></returns> public static async Task GetRoute(Microsoft.Maps.MapControl.WPF.Location fwp, Microsoft.Maps.MapControl.WPF.Location swp, String key, Map map) { var request = new RouteRequest() { Waypoints = new List <SimpleWaypoint>() { new SimpleWaypoint(fwp.Latitude, fwp.Longitude), new SimpleWaypoint(swp.Latitude, swp.Longitude) }, BingMapsKey = key, RouteOptions = new RouteOptions() { TravelMode = TravelModeType.Driving, Optimize = RouteOptimizationType.Time, RouteAttributes = new List <RouteAttributeType>() { RouteAttributeType.RoutePath } } }; var response = await request.Execute(); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { var result = response.ResourceSets[0].Resources[0] as Route; double[][] routePath = result.RoutePath.Line.Coordinates; LocationCollection locs = new LocationCollection(); for (int i = 0; i < routePath.Length; ++i) { if (routePath[i].Length >= 2) { locs.Add(new Microsoft.Maps.MapControl.WPF.Location(routePath[i][0], routePath[i][1])); } } MainWindow.Waypoints = new LocationCollection(); MainWindow.Waypoints = locs; MainWindow.ReceivedRoute = new MapPolyline() { Locations = locs, Stroke = new SolidColorBrush(Colors.Black), StrokeThickness = 2 }; map.Children.Add(MainWindow.ReceivedRoute); } }
private async void Rut(RouteRequest routeRequest) { var response = await routeRequest.Execute(); BoundingBox rect = new BoundingBox(new double[] { response.ResourceSets[0].Resources[0].BoundingBox[0], response.ResourceSets[0].Resources[0].BoundingBox[1], response.ResourceSets[0].Resources[0].BoundingBox[2], response.ResourceSets[0].Resources[0].BoundingBox[3] }); Microsoft.Maps.MapControl.WPF.Location shani = new Microsoft.Maps.MapControl.WPF.Location(31.876640708011877, 34.81796609362201); mMap.SetView(shani, 14); }
private async void Sale(RouteRequest routeRequest) { var response = await routeRequest.Execute(); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { var route = response.ResourceSets[0].Resources[0] as Route; var coords = route.RoutePath.Line.Coordinates; //This is 2D array of lat/long values. var locs = new LocationCollection(); for (int i = 0; i < coords.Length; i++) { locs.Add(new Microsoft.Maps.MapControl.WPF.Location(coords[i][0], coords[i][1])); } var routeLine = new MapPolyline() { Locations = locs, Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Blue), StrokeThickness = 5 }; if (mMap.Children.Count > 0) { mMap.Children.RemoveAt(0); } mMap.Children.Add(routeLine); Microsoft.Maps.MapControl.WPF.Location start = new Microsoft.Maps.MapControl.WPF.Location(locs[0].Latitude, locs[0].Longitude); mMap.SetView(start, 12); mMap.Center = start; Route aa = response.ResourceSets[0].Resources[0] as Route; txtKm.Text = aa.TravelDistance.ToString(); txtTime.Text = App.SecondToHMS(aa.TravelDuration); } }
public async Task <double> DrawPolyline(Polyline polyline, SimpleWaypoint from, SimpleWaypoint to) { polyline.Geopath.Clear(); RouteRequest request = new RouteRequest() { RouteOptions = new RouteOptions() { Avoid = new List <AvoidType>() { AvoidType.MinimizeTolls }, TravelMode = TravelModeType.Driving, DistanceUnits = DistanceUnitType.Kilometers, RouteAttributes = new List <RouteAttributeType>() { RouteAttributeType.RoutePath }, Optimize = RouteOptimizationType.TimeWithTraffic }, Waypoints = new List <SimpleWaypoint>() { from, to }, BingMapsKey = "IL4KJLeeFpfhl9mqdvw8~QuoEqNN-cICujvx87S4zcg~AgVzx_pxd7tdbOkilsKFwk5B-2iNInOs1OC1HXhm810TqteSR1TzPN87K6czdFAL" }; var response = await request.Execute(); if (response.StatusCode == 200) { foreach (var pos in response.ResourceSets.First().Resources.OfType <Route>().First().RoutePath.Line.Coordinates.Select(e => new Position(e[0], e[1])).ToList()) { polyline.Geopath.Add(pos); } } else { DisplayAlert("Routing error", string.Concat(response.ErrorDetails ?? new[] { "Unknown error occured", "" }), "Ok"); } return(response.ResourceSets.First().Resources.OfType <Route>().First().TravelDistance); }
private async void CalculateRoutePathBtn_Clicked(object sender, RoutedEventArgs e) { //Remove any existing lines. lineLayer.Children.Clear(); //Loop through each agent and calculate a route along the roads. for (int i = 0; i < result.AgentItineraries.Length; i++) { var a = result.AgentItineraries[i]; //Create a route request to get a route paths along a road. var r = new RouteRequest() { //Customize these options based on agents. RouteOptions = new RouteOptions() { Avoid = new List <AvoidType>() { AvoidType.MinimizeTolls }, TravelMode = TravelModeType.Driving, DistanceUnits = DistanceUnitType.Miles, Heading = 45, RouteAttributes = new List <RouteAttributeType>() { //Only retrieving route path information for visualization. Change this to "All" if you want the instructions too. RouteAttributeType.RoutePath }, Optimize = RouteOptimizationType.TimeWithTraffic }, Waypoints = a.Route.GetAllWaypoints(), BingMapsKey = BingMapsKey }; var route = await r.Execute(); //Show the route on the map. ShowRouteOnMap(route, AgentColors[i]); } }
async void CalculateRouteBtn_Clicked(object sender, RoutedEventArgs e) { MyMap.Children.Clear(); OutputTbx.Text = string.Empty; LoadingBar.Visibility = Visibility.Visible; var waypoints = GetWaypoints(); if (waypoints.Count < 2) { MessageBox.Show("Need a minimum of 2 waypoints to calculate a route."); return; } //var travelMode = (TravelModeType)Enum.Parse(typeof(TravelModeType), (string)(TravelModeTypeCbx.SelectedItem as ComboBoxItem).Content); //var tspOptimization = (TspOptimizationType)Enum.Parse(typeof(TspOptimizationType), (string)(TspOptimizationTypeCbx.SelectedItem as ComboBoxItem).Tag); var travelMode = TravelModeType.Driving; var tspOptimization = TspOptimizationType.StraightLineDistance; try { //Calculate a route between the waypoints so we can draw the path on the map. var routeRequest = new RouteRequest() { Waypoints = waypoints, //Specify that we want the route to be optimized WaypointOptimization = tspOptimization, RouteOptions = new RouteOptions() { TravelMode = travelMode, RouteAttributes = new List<RouteAttributeType>() { RouteAttributeType.RoutePath, RouteAttributeType.ExcludeItinerary } }, //When straight line distances are used, the distance matrix API is not used, so a session key can be used. BingMapsKey = (tspOptimization == TspOptimizationType.StraightLineDistance) ? SessionKey : BingMapsKey }; //Only use traffic based routing when travel mode is driving. if (routeRequest.RouteOptions.TravelMode != TravelModeType.Driving) { routeRequest.RouteOptions.Optimize = RouteOptimizationType.Time; } else { routeRequest.RouteOptions.Optimize = RouteOptimizationType.TimeWithTraffic; } var r = await routeRequest.Execute(); RenderRouteResponse(routeRequest, r); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } LoadingBar.Visibility = Visibility.Collapsed; }
/// <summary> /// An asynchronous fetch of a map route (untested) /// </summary> /// <param name="mapData"></param> /// <param name="bingMapsKey"></param> /// <param name="StartStopList"></param> public static void GetMapRouteAsync(SimioMapRoute mapData, string bingMapsKey, List <string> StartStopList) { try { List <SimpleWaypoint> wayPointList = new List <SimpleWaypoint>(); foreach (string location in StartStopList) { SimpleWaypoint wayPoint = new SimpleWaypoint(location); wayPointList.Add(wayPoint); } if (true) { var request = new RouteRequest(); request.Waypoints = wayPointList; request.BingMapsKey = bingMapsKey; Task <Response> t = request.Execute(); var result = t.Result; t.RunSynchronously(); var r = t.Result; if (r != null && r.ResourceSets != null && r.ResourceSets.Length > 0 && r.ResourceSets[0].Resources != null && r.ResourceSets[0].Resources.Length > 0) { for (var i = 0; i < r.ResourceSets[0].Resources.Length; i++) { throw new ApplicationException((r.ResourceSets[0].Resources[i] as Location).Name); } } else { throw new ApplicationException("No results found."); } } if (true) { Task <Response> t = ServiceManager.GetResponseAsync(new RouteRequest() { BingMapsKey = bingMapsKey, Waypoints = wayPointList }); t.RunSynchronously(); var r = ServiceManager.GetResponseAsync(new RouteRequest() { BingMapsKey = bingMapsKey, Waypoints = wayPointList }).GetAwaiter().GetResult(); if (r != null && r.ResourceSets != null && r.ResourceSets.Length > 0 && r.ResourceSets[0].Resources != null && r.ResourceSets[0].Resources.Length > 0) { for (var i = 0; i < r.ResourceSets[0].Resources.Length; i++) { throw new ApplicationException((r.ResourceSets[0].Resources[i] as Location).Name); } } else { throw new ApplicationException("No results found."); } } Console.ReadLine(); } catch (Exception ex) { string x = $"Err={ex}"; } }
/// <summary> /// This method has a lot of logic that is specific to the map type. /// To process a request you can easily just call the Execute method on the request. /// This will build much of the SimioMapRoute object. /// </summary> /// <param name="request"></param> public bool GetRoute(string mapsKey, string originAddress, string destinationAddress, out SimioMapRoute mapRoute, out string requestUrl, out string explanation) { explanation = ""; requestUrl = ""; mapRoute = null; try { mapRoute = new SimioMapRoute(originAddress, destinationAddress); // Build a list of our two waypoints (from and to) List <SimpleWaypoint> wpList = new List <SimpleWaypoint>(); wpList.Add(new SimpleWaypoint(originAddress)); //e.g. "Pittsburgh, PA")); wpList.Add(new SimpleWaypoint(destinationAddress)); // e.g. "Sewickley, PA")); List <RouteAttributeType> routeAttributes = new List <RouteAttributeType>(); routeAttributes.Add(RouteAttributeType.RoutePath); // Construct the request and attributes var request = new RouteRequest() { BingMapsKey = mapsKey, Waypoints = wpList }; request.RouteOptions = new RouteOptions(); request.RouteOptions.RouteAttributes = routeAttributes; requestUrl = request.ToString(); var start = DateTime.Now; // Async. Execute the request. var task = Task <Response> .Run(async() => { return(await request.Execute()); }); Response r2 = task.Result; // Check if we got a good response if (r2 != null && r2.ResourceSets != null && r2.ResourceSets.Length > 0 && r2.ResourceSets[0].Resources != null && r2.ResourceSets[0].Resources.Length > 0) { ResourceSet rs = (ResourceSet)r2.ResourceSets[0]; Route route = (Route)rs.Resources[0]; RouteLeg[] legs = route.RouteLegs; ItineraryItem[] itineraries = legs[0].ItineraryItems; ItineraryItem itinItem = itineraries[2]; string bb = route.BoundingBox.ToString(); mapRoute.SegmentList.Clear(); // We could make the bounding box from the one that Bing Maps sends us, // but we're going to do our own to match the usa 'map'. ////PointF ptLoc = new PointF((float)route.BoundingBox[1], (float)route.BoundingBox[0]); ////float width = (float)(route.BoundingBox[3] - route.BoundingBox[1]); ////float height = (float)(route.BoundingBox[2] - route.BoundingBox[0]); ////// We're going to bound according to the contiguous USA, which is appox. ////// lat 20 to 50, and lon -60 to -130 ////PointF ptLoc = transform.LonLatBoundingBox.Location; // new PointF( -130f, 20f); ////float width = lonlatBox.Width; // 70f; ////float height = lonlatBox.Height; // 30f; ////// Turning the thing on its side, since we want latitude to be 'Y' ////mapData.LonLatBoundingBox = new RectangleF(ptLoc.X, ptLoc.Y, width, height); ////mapData.Origin = new PointF(ptLoc.X + width / 2f, ptLoc.Y + height / 2f); ////mapData.SimioScaling = simioScaling; // Build something for the form's 'result textbox StringBuilder sb = new StringBuilder(); // Create segments from the itineraries, and pick up the indices // that reference the RoutePath array of lat,lon coordinates. // We are assuming a single itinerary. See Bing Maps for for info. for (var ii = 0; ii < itineraries.Length; ii++) { ItineraryItem item = itineraries[ii]; if (route.RoutePath != null) { int idxStart = item.Details[0].StartPathIndices[0]; int idxEnd = item.Details[0].EndPathIndices[0]; double lat = route.RoutePath.Line.Coordinates[idxStart][0]; double lon = route.RoutePath.Line.Coordinates[idxStart][1]; MapCoordinate mcStart = new MapCoordinate(lat, lon); lat = route.RoutePath.Line.Coordinates[idxEnd][0]; lon = route.RoutePath.Line.Coordinates[idxEnd][1]; MapCoordinate mcEnd = new MapCoordinate(lat, lon); MapSegment segment = null; if (ii == 0) { segment = mapRoute.AddFirstSegment(mcStart, mcEnd); } else { segment = mapRoute.AppendSegment(mcEnd); } // Now add Bing-specific info segment.Distance = item.TravelDistance; segment.Duration = item.TravelDuration; } sb.AppendLine($"Compass={item.CompassDirection} Distance={item.TravelDistance} >> {item.Instruction.Text}"); } // for each itinerary explanation = sb.ToString(); return(true); } else { explanation = "No results found."; return(false); } } catch (Exception ex) { explanation = $"Err={ex.Message}"; return(false); } }