public static IRequest CreateApiRequest(ApiRequestType requestType) { IRequest request = null; switch (requestType) { case ApiRequestType.Evemon: request = new EvemonRequest(); break; case ApiRequestType.History: request = new HistoryRequest(); break; case ApiRequestType.MarketStat: request = new MarketStatRequest(); break; case ApiRequestType.QuickLook: request = new QuickLookRequest(); break; case ApiRequestType.QuickLookOnPath: request = new QuickLookOnPathRequest(); break; case ApiRequestType.Route: request = new RouteRequest(); break; } return(request); }
static void Main(string[] args) { RoutingServiceClient client = new RoutingServiceClient(); RouteRequest request = new RouteRequest(); request.UserName = "******"; request.Password = "******"; request.IntegrationId = 4; request.MilesPerGallon = 6; request.Locations = new RouteLocation[] { new RouteLocation(){City = "Boise",State = "ID"}, new RouteLocation(){City = "Denver",State = "Co"}, }; RouteReturn returnValue = client.GetRoute(request); foreach (Error error in returnValue.Errors) { Console.WriteLine(error.ErrorMessage); } Console.WriteLine(returnValue.AverageFuelPrice); Console.WriteLine(returnValue.CostPerMile); Console.WriteLine(returnValue.EstimatedFuelCost); Console.ReadKey(); }
private RouteResponse TryRequestRouteResponse() { Osrm5x osrm = new Osrm5x(OsrmServerBaseUrl); RouteResponse response = null; try { RouteRequest request = new RouteRequest() { Coordinates = OsrmConverter.ConvertGeocoordinatesToLocations(Coordinates).ToArray(), Steps = true, Alternative = CalculateAlternativeRoutes }; response = osrm.Route(request); } catch (Exception e) { Console.WriteLine(e); if (response != null) { Console.WriteLine("Status Code of RouteRequest: " + response.Code); } } return(response); }
public void GetDirections(List<Point> locations, EventHandler onResults) { if (IsInitialized) { var routeRequest = new RouteRequest {Credentials = new Credentials {Token = token}}; var waypoints = new List<Waypoint>(); foreach (Point loc in locations) { waypoints.Add(new Waypoint {Location = new Location {Longitude = loc.X, Latitude = loc.Y}}); } routeRequest.Waypoints = waypoints; routeRequest.Options = new RouteOptions { Mode = TravelMode, Optimization = RouteOptimization, RoutePathType = RoutePathType.Points, TrafficUsage = TrafficUsage }; var routeService = new RouteServiceClient(); routeService.CalculateRouteCompleted += (o, e) => { RouteResponse routeResponse = e.Result; onResults(this, new RouteResultArgs {Result = routeResponse.Result}); }; routeService.CalculateRouteAsync(routeRequest); } }
public async Task <RouteResponse> GetRoute(string source, string target, string shipmentDate, double weightInKg, double largestSizeinCm, string goodsType, bool recommended) { //_client.BaseAddress = new Uri(_client.BaseAddress.ToString() + "JSONIntegration/FindRoutes"); Parcel parcel = new Parcel() { ShipmentDate = shipmentDate, WeightInKg = weightInKg, LargestSizeInCm = largestSizeinCm, GoodsType = goodsType, Recommended = recommended, }; RouteRequest request = new RouteRequest() { Source = source, Target = target, Parcel = parcel, }; var jstring = JsonConvert.SerializeObject(request); var message = new HttpRequestMessage(); message.Content = new StringContent(jstring); message.Headers.Add("username", _username); message.Headers.Add("password", _password); message.Method = HttpMethod.Post; message.RequestUri = new Uri(_client.BaseAddress.ToString() + "JSONIntegration/FindRoutes"); var response = _client.SendAsync(message).Result; var resultString = response.Content.ReadAsStringAsync().Result; var routeResp = JsonConvert.DeserializeObject <RouteResponse>(resultString); return(routeResp); }
private async void CalculateRoute(GeocodeResult from, GeocodeResult to) { using (RouteServiceClient client = new RouteServiceClient("CustomBinding_IRouteService")) { RouteRequest request = new RouteRequest { Credentials = new Credentials() { ApplicationId = Resources.BingApiKey }, Waypoints = new ObservableCollection <Waypoint> { ConvertResultToWayPoint(@from), ConvertResultToWayPoint(to) }, Options = new RouteOptions { RoutePathType = RoutePathType.Points }, }; try { RouteResult = client.CalculateRoute(request).Result; } catch (Exception) { await this.interactionService.ShowMessageBox("Sorry", $"Could not find: {this.From}"); return; } } GetDirections(); }
public static RouteRequest CastModelToRouteRequest(RouteRequestModel model, int userId) { RouteRequest rr = new RouteRequest(); rr.SrcGAddress = model.SrcGAddress; rr.SrcDetailAddress = model.SrcDetailAddress; rr.SrcLatitude = decimal.Parse(model.SrcLatitude); rr.SrcLongitude = decimal.Parse(model.SrcLongitude); rr.SrcGeo = CreatePoint(model.SrcLatitude, model.SrcLongitude); rr.DstGAddress = model.DstGAddress; rr.DstDetailAddress = model.DstDetailAddress; rr.DstLatitude = decimal.Parse(model.DstLatitude); rr.DstLongitude = decimal.Parse(model.DstLongitude); rr.DstGeo = CreatePoint(model.DstLatitude, model.DstLongitude); rr.AccompanyCount = model.AccompanyCount; rr.RequestCreateTime = DateTime.Now; rr.RequestLastModifyTime = DateTime.Now; rr.RouteRequestType = (int)RouteRequestType.ByWebUser; rr.RouteRequestUserId = userId; rr.RRIsDeleted = false; rr.RRIsConfirmed = (int)BooleanValue.True; rr.IsDrive = model.IsDrive; rr.RecommendPathId = model.RecommendPathId; if (model.IsDrive) { rr.RouteRequestState = (int)RouteRequestState.WaitForPassenger; } else { rr.RouteRequestState = (int)RouteRequestState.WaitForDriver; } rr.SrcDstDistance = getDistance(double.Parse(model.SrcLatitude), double.Parse(model.SrcLongitude), double.Parse(model.DstLatitude), double.Parse(model.DstLongitude)); return(rr); }
/// <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)); }
public TestParameters(bool canDeactivate, bool isAuthorized, object newViewModel, RouteRequest routeRequest = null) { CanDeactivate = canDeactivate; IsAuthorized = isAuthorized; NewViewModel = newViewModel; RouteRequest = routeRequest ?? new RouteRequest("uri", null, ViewportOptions.MainViewport(), new ClaimsPrincipal()); }
public CommandResponse Run(RouteRequest request, int hotelId, string date) { try { var currentDir = Environment.CurrentDirectory; var path = currentDir + $"/task 2 - hotelrates.json"; var jsonStr = (request.contentStr != null || request.contentStr != "") ? System.IO.File.ReadAllText(path) : request.contentStr; var sr = JObject.Parse(jsonStr); var root = JsonConvert.DeserializeObject <Root>(jsonStr); var hoteRates = new List <HotelRate>(); if (root.hotel.hotelID == hotelId) { var rates = JsonConvert.DeserializeObject <Hotel>(jsonStr); hoteRates = rates.hotelRates.Where(a => a.targetDay.ToString("MM/dd/yyyy") == Convert.ToDateTime(date).ToString("MM/dd/yyyy")).ToList(); } var rootJson = new JavaScriptSerializer().Serialize(root); var hoteRatesJson = new JavaScriptSerializer().Serialize(hoteRates); var json = JsonConvert.SerializeObject(new { hotel = rootJson, hoteRatesJson }); var cr = new CommandResponse(json, "application/json"); return(cr); } catch (Exception e) { throw new Exception(e.Message); } }
public async Task <double> GetTravelTime(Models.Address fromAddress, Models.Address toAddress) { var request = new RouteRequest() { Waypoints = new List <SimpleWaypoint>() { new SimpleWaypoint(fromAddress.Lat, fromAddress.Lon), new SimpleWaypoint(toAddress.Lat, toAddress.Lon) }, BingMapsKey = Constants.API_Keys.Bing }; double travelTime = 0; var response = await ServiceManager.GetResponseAsync(request); 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 BingMapsRESTToolkit.Route; //Do something with the result. travelTime = Convert.ToDouble(result.TravelDuration); } return(travelTime); }
static async System.Threading.Tasks.Task Main(string[] args) { Console.WriteLine("Calling GRPC Service"); Console.Write("Hit enter to do the deed"); Console.ReadLine(); using var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Greeter.GreeterClient(channel); var reply = await client.SayHelloAsync(new HelloRequest { Name = "Putintane" }); Console.WriteLine($"Got the response {reply.Message}"); Console.WriteLine($"Got the response {reply.Message}"); Console.WriteLine("Planning your route ..."); var clientRouting = new DrivingRouter.DrivingRouterClient(channel); var request = new RouteRequest { Street = "555 Mockingbird Ct.", City = "Des Moines", Zip = "23892" }; var replyRoute = await clientRouting.PlanRouteAsync(request); Console.WriteLine("Arriving at " + replyRoute.ArrivalTime); Console.WriteLine("Miles: " + replyRoute.Miles); foreach (var step in replyRoute.Steps) { Console.WriteLine($"\t{step}"); } }
/// <summary> /// Demostrates how to make a Transit Route Request. /// </summary> private void TransitRouteBtn_Clicked(object sender, RoutedEventArgs e) { var r = new RouteRequest() { RouteOptions = new RouteOptions() { TravelMode = TravelModeType.Transit, DistanceUnits = DistanceUnitType.Miles, RouteAttributes = new List <RouteAttributeType>() { RouteAttributeType.RoutePath, RouteAttributeType.TransitStops }, Optimize = RouteOptimizationType.TimeAvoidClosure, DateTime = new DateTime(2016, 6, 30, 8, 0, 0, DateTimeKind.Utc), TimeType = RouteTimeType.Departure }, Waypoints = new List <SimpleWaypoint>() { new SimpleWaypoint() { Address = "London, UK" }, new SimpleWaypoint() { Address = "E14 3SP" } }, BingMapsKey = BingMapsKey }; ProcessRequest(r); }
public void RouteRequest_Url() { var r = new RouteRequest { Coordinates = locations }; Assert.IsTrue(r.CoordinatesUrlPart.Contains("13.420526,52.503033")); Assert.IsTrue(r.CoordinatesUrlPart.Contains("13.429290,52.516582")); // Default values are not sent //Assert.AreEqual<int>(1, ParamValues(r.UrlParams, "alternatives").Length); //Assert.AreEqual<string>("false", ParamValues(r.UrlParams, "alternatives")[0]); //Assert.AreEqual<int>(1, ParamValues(r.UrlParams, "steps").Length); //Assert.AreEqual<string>("false", ParamValues(r.UrlParams, "steps")[0]); //Assert.AreEqual<int>(1, ParamValues(r.UrlParams, "geometries").Length); //Assert.AreEqual<string>("polyline", ParamValues(r.UrlParams, "geometries")[0]); //Assert.AreEqual<int>(1, ParamValues(r.UrlParams, "overview").Length); //Assert.AreEqual<string>("simplified", ParamValues(r.UrlParams, "overview")[0]); //Assert.AreEqual<int>(1, ParamValues(r.UrlParams, "continue_straight").Length); //Assert.AreEqual<string>("default", ParamValues(r.UrlParams, "continue_straight")[0]); }
public long GetRoadTime(Point[] points) { DBC.Assert(points.Length == 2, "Calculating road time requires exactly 2 points. " + points.Length + " were provided."); var cacheResult = routeCache.GetTime(points[0].address, points[1].address); if (cacheResult != null) { Log(points, true); return cacheResult.Value; } Log(points, false); var router = new RouteServiceClient(); var request = new RouteRequest(); request.Credentials = new Credentials(); request.Credentials.Token = GetToken(); request.Waypoints = new Waypoint[points.Length]; for (int i = 0; i < points.Length; i++) { var p = points[i]; var waypoint = new Waypoint(); waypoint.Description = p.address; waypoint.Location = new Location(); waypoint.Location.Latitude = p.lat; waypoint.Location.Longitude = p.lon; request.Waypoints[i] = waypoint; } RouteResponse response = router.CalculateRoute(request); var seconds = response.Result.Summary.TimeInSeconds; routeCache.Add(points, seconds); return seconds; }
private void BtnCalc_Click(object sender, RoutedEventArgs e) { var routeRequest = new RouteRequest() { RouteOptions = new RouteOptions() { RouteAttributes = new List <RouteAttributeType>() { RouteAttributeType.RoutePath } }, Waypoints = new List <SimpleWaypoint>() { new SimpleWaypoint() { Address = txtMoza.Text }, new SimpleWaypoint() { Address = txtYaad.Text } }, BingMapsKey = myKey }; Sale(routeRequest); }
public List <MyWaypoint> CreateRoute(MyWaypoint startPoint, MyWaypoint endPoint) { // create route from waypointString RouteRequest routeRequest = new RouteRequest(); // Set the credentials using a valid Bing Maps key routeRequest.Credentials = new BingRouteService.Credentials(); routeRequest.Credentials.ApplicationId = m_bingMapKey; // tell them that we want points along the route routeRequest.Options = new RouteOptions(); routeRequest.Options.RoutePathType = RoutePathType.Points; //Parse user data to create array of waypoints BingRouteService.Waypoint[] waypoints = new BingRouteService.Waypoint[2]; BingRouteService.Waypoint point1 = new BingRouteService.Waypoint(); BingRouteService.Location location1 = new BingRouteService.Location(); location1.Latitude = startPoint.Latitude; location1.Longitude = startPoint.Longitude; point1.Location = location1; point1.Description = "Start"; waypoints[0] = point1; BingRouteService.Waypoint point2 = new BingRouteService.Waypoint(); BingRouteService.Location location2 = new BingRouteService.Location(); location2.Latitude = endPoint.Latitude; location2.Longitude = endPoint.Longitude; point2.Location = location2; point2.Description = "End"; waypoints[1] = point2; routeRequest.Waypoints = waypoints; // Make the calculate route request RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); RouteResponse routeResponse = routeService.CalculateRoute(routeRequest); // pull out the lat/lon values List <MyWaypoint> returnPoints = new List <MyWaypoint>(); if (routeResponse.Result.Legs.Length > 0) { //MessageBox.Show("Distance: " + routeResponse.Result.Summary.Distance.ToString() // + " Time: " + routeResponse.Result.Summary.TimeInSeconds.ToString()); foreach (BingRouteService.Location thisPt in routeResponse.Result.RoutePath.Points) { MyWaypoint thisPoint = new MyWaypoint(); thisPoint.Latitude = thisPt.Latitude; thisPoint.Longitude = thisPt.Longitude; //thisPoint.Altitude = GetAltitude(thisPoint.Latitude, thisPoint.Longitude); thisPoint.Altitude = 0.0; returnPoints.Add(thisPoint); } } return(returnPoints); }
public async Task <RouteResult> RouteAsync(RouteRequest routeRequest) { var routeWorkflow = RouteWorkflowTask.Go(routeRequest, _routeEntryRegistry, _routeAuthorizationManager, this, _logger); return(await routeWorkflow.RouteResult); }
public bool IsSimilarTiming(RouteRequest route, RouteRequest similarRoute, vwRRTiming routeTiming, vwRRTiming similarRouteTiming) { var diff = (similarRouteTiming.RRTheTime - routeTiming.RRTheTime); if (routeTiming.RRTimingOption == similarRouteTiming.RRTimingOption) { if (similarRouteTiming.RRDayofWeek == routeTiming.RRDayofWeek) { //var diffTime = (similarRouteTiming.RRTheTime - routeTiming.RRTheTime); if (Math.Abs(diff.Value.TotalHours) <= 2) { return(true); } } } if (similarRouteTiming.RRTimingOption == (int)TimingOptions.InDateAndTime) { if (similarRouteTiming.RRTheDate > DateTime.Now && similarRouteTiming.RRDayofWeek == routeTiming.RRDayofWeek && Math.Abs(diff.Value.TotalHours) <= 2) { return(true); } } return(false); }
static void Main(string[] args) { RoutingServiceClient client = new RoutingServiceClient(); RouteRequest request = new RouteRequest(); request.UserName = "******"; request.Password = "******"; request.IntegrationId = 4; request.MilesPerGallon = 6; request.Locations = new RouteLocation[] { new RouteLocation() { City = "Boise", State = "ID" }, new RouteLocation() { City = "Denver", State = "Co" }, }; RouteReturn returnValue = client.GetRoute(request); foreach (Error error in returnValue.Errors) { Console.WriteLine(error.ErrorMessage); } Console.WriteLine(returnValue.AverageFuelPrice); Console.WriteLine(returnValue.CostPerMile); Console.WriteLine(returnValue.EstimatedFuelCost); Console.ReadKey(); }
private IEnumerable <Point> TouristRoute(RouteRequest rrq) { IEnumerable <Sightseen> sightseens = appCtx.Sightseens.ToList(); int StationId = appCtx.Bikes.Where(b => b.Id == rrq.BikeId).Select(b => b.StationId).SingleOrDefault(); Station stBegin = appCtx.Stations.FirstOrDefault(s => s.Id == StationId); Station stEnd = appCtx.Stations.FirstOrDefault(s => s.Id == rrq.EndStationId); if (stBegin != null && stEnd != null) { Point c = new Point { X = (stBegin.Point.X + stEnd.Point.X) / 2, Y = (stBegin.Point.Y + stEnd.Point.Y) / 2 }; double r = Math.Sqrt(Math.Pow(c.X - stBegin.Point.X, 2) + Math.Pow(c.Y - stBegin.Point.Y, 2)); List <Point> result = new List <Point> { new Point { X = stBegin.Point.X, Y = stBegin.Point.Y } }; foreach (Sightseen s in sightseens) { if (isInCircle(c, s.Point, r)) { result.Add(s.Point); } } result.Add(new Point { X = stEnd.Point.X, Y = stEnd.Point.Y }); return(result); } return(null); }
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); } }
public IActionResult ChooseRoute([FromBody] RouteRequest rrq) { switch (rrq.Type) { case "shortest": StartRent(new RentModel { BikeId = rrq.BikeId }); return(Json(ShortRoute(rrq))); case "tourist": StartRent(new RentModel { BikeId = rrq.BikeId }); return(Json(TouristRoute(rrq))); case "free": StartRent(new RentModel { BikeId = rrq.BikeId }); return(Json(FreeRoute(rrq))); default: return(BadRequest(new { errorMessage = "Type of route is undefined" })); } }
public async Task <RouteResult> RouteAsync(string uri, object initData, ViewportOptions viewportOptions, ClaimsPrincipal principal) { var routeRequest = new RouteRequest(uri, initData, viewportOptions, principal); return(await RouteAsync(routeRequest)); }
private static Uri BuildDirectionsUri(RouteRequest routeRequest, Destination destination) { string rawLink = $"https://www.google.ca/maps/dir/{routeRequest.Origin}/{destination.DestinationName}"; string link = rawLink.Replace(' ', '+'); return(new Uri(link)); }
public GetRout() { InitializeComponent(); var routeRequest = new RouteRequest() { RouteOptions = new RouteOptions() { RouteAttributes = new List <RouteAttributeType>() { RouteAttributeType.RoutePath } }, Waypoints = new List <SimpleWaypoint>() { new SimpleWaypoint() { Address = "רחובות שני 21" }, new SimpleWaypoint() { Address = "שומרה" } }, BingMapsKey = myKey }; Sale(routeRequest); }
// 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); }
public HttpResponseMessage GetRoute(RouteRequest model) { WebClient client = new WebClient(); ItemResponse <string> response = new ItemResponse <string>(); response.Item = client.DownloadString(model.Url); return(Request.CreateResponse(HttpStatusCode.OK, response)); }
public async Task <RouteResponse> FindBestRoute(RouteRequest routeRequest) { List <Route> routes = await _repository.GetAllRoutes(); var response = _finder.BestRouteAsync(routeRequest.From, routeRequest.To, routes); return(await Task.FromResult(response)); }
public RouteResponse CalculateRoute([System.Xml.Serialization.XmlElementAttribute(IsNullable = true)] RouteRequest request) { object[] results = this.Invoke("CalculateRoute", new object[] { request }); return((RouteResponse)(results[0])); }
/// <summary> /// Demostrates how to make a Driving Route Request that has more than 25 waypoints. /// </summary> private void LongRouteBtn_Clicked(object sender, RoutedEventArgs e) { var r = new RouteRequest() { RouteOptions = new RouteOptions() { Avoid = new List <AvoidType>() { AvoidType.MinimizeTolls }, TravelMode = TravelModeType.Driving, DistanceUnits = DistanceUnitType.Miles, Heading = 45, RouteAttributes = new List <RouteAttributeType>() { RouteAttributeType.RoutePath }, Optimize = RouteOptimizationType.TimeWithTraffic }, Waypoints = new List <SimpleWaypoint>() //29 waypoints, more than what the routing service normally handles, so the request will break this up into two requests and merge the results. { new SimpleWaypoint(47.5886, -122.336), new SimpleWaypoint(47.5553, -122.334), new SimpleWaypoint(47.5557, -122.316), new SimpleWaypoint(47.5428, -122.322), new SimpleWaypoint(47.5425, -122.341), new SimpleWaypoint(47.5538, -122.362), new SimpleWaypoint(47.5647, -122.384), new SimpleWaypoint(47.5309, -122.380), new SimpleWaypoint(47.5261, -122.351), new SimpleWaypoint(47.5137, -122.382), new SimpleWaypoint(47.5101, -122.337), new SimpleWaypoint(47.4901, -122.341), new SimpleWaypoint(47.4850, -122.320), new SimpleWaypoint(47.5024, -122.263), new SimpleWaypoint(47.4970, -122.226), new SimpleWaypoint(47.4736, -122.265), new SimpleWaypoint(47.4562, -122.287), new SimpleWaypoint(47.4452, -122.338), new SimpleWaypoint(47.4237, -122.292), new SimpleWaypoint(47.4230, -122.257), new SimpleWaypoint(47.3974, -122.249), new SimpleWaypoint(47.3765, -122.277), new SimpleWaypoint(47.3459, -122.302), new SimpleWaypoint(47.3073, -122.280), new SimpleWaypoint(47.3115, -122.228), new SimpleWaypoint(47.2862, -122.218), new SimpleWaypoint(47.2714, -122.294), new SimpleWaypoint(47.2353, -122.306), new SimpleWaypoint(47.1912, -122.408) }, BingMapsKey = BingMapsKey }; ProcessRequest(r); RequestUrlTbx.Text = "Request broken up into multiple sub-requests."; }
private async void GO_button_Click(object sender, EventArgs e) { if (path.Count >= 2 && path.Count <= 4) { RouteInfo.Text = ""; //построение маршрута по введённым точкам var GO = new RouteRequest() { RouteOptions = new RouteOptions() { RouteAttributes = new List <RouteAttributeType>() { RouteAttributeType.RoutePath } }, Waypoints = path, BingMapsKey = "AvNYCSU2MmF9vSmTbV_ha_WPAxMroM9r_efIFraDGMZZPqWNjS5Xm7sb_qaVuEJc" }; var response = await ServiceManager.GetResponseAsync(GO); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { RouteInfo.Text += "общее расстояние (км): " + (response.ResourceSets[0].Resources[0] as Route).TravelDistance.ToString() + "\n"; RouteInfo.Text += "время в пути (часы): " + Convert.ToString((int)(response.ResourceSets[0].Resources[0] as Route).TravelDuration / 360) + "\n"; } var imagereq = new ImageryRequest() { //получение статического изображения маршрута ImagerySet = ImageryType.RoadOnDemand, BingMapsKey = "AvNYCSU2MmF9vSmTbV_ha_WPAxMroM9r_efIFraDGMZZPqWNjS5Xm7sb_qaVuEJc", ZoomLevel = 10, MapArea = new BoundingBox { EastLongitude = longtitudes.Max(), WestLongitude = longtitudes.Min(), NorthLatitude = latitudes.Max(), SouthLatitude = latitudes.Min(), }, Pushpins = pushpins, HighlightEntity = true }; using (var imageStream = await ServiceManager.GetImageAsync(imagereq)) { Image img = Image.FromStream(imageStream); MapBox.Image = img; MapBox.SizeMode = PictureBoxSizeMode.StretchImage; } } else { MessageBox.Show("задайте от двух до четырёх точек маршрута"); } }
public void RouteRequest_Defaults() { var r = new RouteRequest(); Assert.AreEqual <bool>(false, r.Alternative); Assert.AreEqual <bool>(false, r.Steps); Assert.AreEqual <string>("polyline", r.Geometries); Assert.AreEqual <string>("simplified", r.Overview); Assert.AreEqual <string>("default", r.ContinueStraight); }
public static void yolBul(Location location) { ClientIslem.dtYolIndex++; RouteRequest routeRequest = new RouteRequest(); routeRequest.Culture = new System.Globalization.CultureInfo("en-US"); routeRequest.Options.RoutePathType = RoutePathType.Points; routeRequest.Waypoints.Add(location); routeRequest.Waypoints.Add(location); routeProvider.CalculateRouteAsync(routeRequest); }
private void ExecuteRouting() { RouteRequest request = new RouteRequest(); request.Options.RoutePathType = RoutePathType.Points; Location sofia = new Location(42.7072638273239, 23.3318710327148); Location munich = new Location(48.1364169716835, 11.577525883913); Location amsterdam = new Location(52.3712052404881, 4.8920676112175); request.Waypoints.Add(sofia); request.Waypoints.Add(munich); request.Waypoints.Add(amsterdam); this.routeProvider.CalculateRouteAsync(request); }
public static void yolIstek (LocationCollection locations) { RouteRequest routeRequest = new RouteRequest(); routeRequest.Culture = new System.Globalization.CultureInfo("en-US"); routeRequest.Options.RoutePathType = RoutePathType.Points; for (int i = 0; i < locations.Count;i++) { routeRequest.Waypoints.Add(locations[i]); } yolAniProvider.CalculateRouteAsync(routeRequest); }
private void FindRouteClicked(object sender, RoutedEventArgs e) { this.routeLayer.Items.Clear(); RouteRequest routeRequest = new RouteRequest(); routeRequest.Culture = new System.Globalization.CultureInfo("en-US"); routeRequest.Options.RoutePathType = RoutePathType.Points; if (this.wayPoints.Count > 1) { this.findRouteButton.IsEnabled = false; foreach (Location location in this.wayPoints) { routeRequest.Waypoints.Add(location); } this.routeProvider.CalculateRouteAsync(routeRequest); } }
/*oblicza trasę na podstawie otrzymanych współrzędnych * jesli waypointów mniej niż dwa informacja * w przeciwnym wypadku zapisz je na mapie */ public void CalculateRoute(Microsoft.Phone.Controls.Maps.Map map, GeocodeService.GeocodeResult[] coordinates, Helper.MapResultReceived croute, TravelMode tm = TravelMode.Driving) { if (coordinates.Length < 2) { MessageBox.Show("Too small number od location: you need startPoint and endpoint at least"); return; } try { MapResponseSendHere = new Helper.MapResultReceived(croute); routedMap = map; RouteService.RouteServiceClient routeService = new RouteService.RouteServiceClient("BasicHttpBinding_IRouteService"); routeService.Endpoint.Binding.ReceiveTimeout = timeout; routeService.Endpoint.Binding.SendTimeout = timeout; routeService.Endpoint.Binding.OpenTimeout = timeout; RouteRequest routeRequest = new RouteRequest(); { routeRequest.Credentials = new Microsoft.Phone.Controls.Maps.Credentials() { ApplicationId = bingMapKey }; routeRequest.Options = new RouteService.RouteOptions() { RoutePathType = RouteService.RoutePathType.Points, Mode = tm }; } routeRequest.Waypoints = new System.Collections.ObjectModel.ObservableCollection<RouteService.Waypoint>(); foreach (GeocodeService.GeocodeResult coord in coordinates) { if (null != coord) { if (coordinates[coordinates.Length - 1] != coord) //jesli to ostatni punkt ustaw: MOBICA routeRequest.Waypoints.Add(GeocodeToWaypoint(coord)); else routeRequest.Waypoints.Add(GeocodeToWaypoint(coord, "MOBICA")); } } routeService.CalculateRouteCompleted += (sender, e) => CalculateRouteCompleted(sender, e); routeService.CalculateRouteAsync(routeRequest, coordinates.Length); } catch (Exception ex) { MessageBox.Show("An exception occurred: " + ex.Message); } }
public string CreateRoute(string waypointString) { string results = ""; RouteRequest routeRequest = new RouteRequest(); // Set the credentials using a valid Bing Maps key routeRequest.Credentials = new RouteService.Credentials(); routeRequest.Credentials.ApplicationId = key; //Parse user data to create array of waypoints string[] points = waypointString.Split(';'); Waypoint[] waypoints = new Waypoint[points.Length]; int pointIndex = -1; foreach (string point in points) { pointIndex++; waypoints[pointIndex] = new Waypoint(); string[] digits = point.Split(','); waypoints[pointIndex].Location = new RouteService.Location(); waypoints[pointIndex].Location.Latitude = double.Parse(digits[0].Trim()); waypoints[pointIndex].Location.Longitude = double.Parse(digits[1].Trim()); if (pointIndex == 0) waypoints[pointIndex].Description = "Start"; else if (pointIndex == points.Length) waypoints[pointIndex].Description = "End"; else waypoints[pointIndex].Description = string.Format("Stop #{0}", pointIndex); } routeRequest.Waypoints = waypoints; // Make the calculate route request RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); RouteResponse routeResponse = routeService.CalculateRoute(routeRequest); // Iterate through each itinerary item to get the route directions StringBuilder directions = new StringBuilder(""); if (routeResponse.Result.Legs.Length > 0) { int instructionCount = 0; int legCount = 0; foreach (RouteLeg leg in routeResponse.Result.Legs) { legCount++; directions.Append(string.Format("Leg #{0}\n", legCount)); foreach (ItineraryItem item in leg.Itinerary) { instructionCount++; directions.Append(string.Format("{0}. {1}\n", instructionCount, item.Text)); } } //Remove all Bing Maps tags around keywords. //If you wanted to format the results, you could use the tags Regex regex = new Regex("<[/a-zA-Z:]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline); results = regex.Replace(directions.ToString(), string.Empty); } else results = "No Route found"; return results; }
private void FindRoute() { this.ErrorSummary.Visibility = Visibility.Collapsed; RouteRequest routeRequest = new RouteRequest(); routeRequest.Culture = new System.Globalization.CultureInfo("en-US"); routeRequest.Options.RoutePathType = RoutePathType.Points; if (this.routePoints.Count > 1) { foreach (Location location in this.routePoints) { routeRequest.Waypoints.Add(location); } this.routeProvider.CalculateRouteAsync(routeRequest); } }
/// <summary> /// Calculates a route, based on geocode resuls. /// </summary> private void CalculateRoute(GeocodeResult[] locations=null) { // Preparing a request for route calculation. var request = new RouteRequest() { Culture = CultureInfo.CurrentUICulture.Name, Waypoints = new ObservableCollection<Waypoint>(), // Don't raise exceptions. ExecutionOptions = new UsingBingMaps.Bing.Route.ExecutionOptions() { SuppressFaults = true }, // Only accept results with high confidence. Options = new RouteOptions() { RoutePathType = RoutePathType.Points } }; if (from_address == false) { Waypoint w_to = new Waypoint(); Waypoint w_from = new Waypoint(); w_to.Location = x_to; w_from.Location = x_from; request.Waypoints.Add(w_from); request.Waypoints.Add(w_to); } else { foreach (var result in locations) { request.Waypoints.Add(GeocodeResultToWaypoint(result)); } } // Get credentials and only then place an async call on the route service. _credentialsProvider.GetCredentials(credentials => { // Pass in credentials for web services call. // Replace with your own Credentials. request.Credentials = credentials; // Make asynchronous call to fetch the data. _routeClient.CalculateRouteAsync(request); }); }
public string CreateRoute(string waypointString,string orientation,string language) { try { CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US"); string results = ""; RouteRequest routeRequest = new RouteRequest(); // Set the credentials using a valid Bing Maps key routeRequest.Credentials = new RouteService.Credentials(); routeRequest.Credentials.ApplicationId = key; routeRequest.Options = new RouteOptions(); routeRequest.Options.Mode = TravelMode.Walking; routeRequest.Options.RoutePathType = RoutePathType.Points; routeRequest.UserProfile = new SmartAudioCityGuide.RouteService.UserProfile(); routeRequest.UserProfile.DistanceUnit = SmartAudioCityGuide.RouteService.DistanceUnit.Kilometer; routeRequest.UserProfile.DeviceType = SmartAudioCityGuide.RouteService.DeviceType.Mobile; routeRequest.UserProfile.CurrentHeading = new SmartAudioCityGuide.RouteService.Heading(); routeRequest.UserProfile.CurrentHeading.Orientation = double.Parse(orientation.Trim(), culture); //Parse user data to create array of waypoints string[] points = waypointString.Split(';'); Waypoint[] waypoints = new Waypoint[points.Length]; int pointIndex = -1; foreach (string point in points) { pointIndex++; waypoints[pointIndex] = new Waypoint(); string[] digits = point.Split(','); waypoints[pointIndex].Location = new RouteService.Location(); waypoints[pointIndex].Location.Latitude = double.Parse(digits[0].Trim(), culture); waypoints[pointIndex].Location.Longitude = double.Parse(digits[1].Trim(), culture); if (pointIndex == 0) waypoints[pointIndex].Description = "Start"; else if (pointIndex == points.Length) waypoints[pointIndex].Description = "End"; else waypoints[pointIndex].Description = string.Format("Stop #{0}", pointIndex); } routeRequest.Waypoints = waypoints; // Make the calculate route request RouteResponse routeResponse = routeService.CalculateRoute(routeRequest); string tes = serializer.Serialize(routeResponse); // Iterate through each itinerary item to get the route directions StringBuilder directions = new StringBuilder(""); if (routeResponse.Result.Legs.Length > 0) { int instructionCount = 0; int legCount = 0; foreach (RouteLeg leg in routeResponse.Result.Legs) { legCount++; directions.Append(string.Format("Leg #{0}\n", legCount)); foreach (ItineraryItem item in leg.Itinerary) { instructionCount++; directions.Append(string.Format("{0}. {1}\n", instructionCount, item.Text)); } } //Remove all Bing Maps tags around keywords. //If you wanted to format the results, you could use the tags /*Regex regex = new Regex("<[/a-zA-Z:1-9=\\\"]*>",*/ Regex regex = new Regex("<[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline); results = regex.Replace(directions.ToString(), string.Empty); for (int i = 0; i < routeResponse.Result.Legs[0].Itinerary.Length; i++ ) { Route routeInfo = new Route(); routeInfo.description = regex.Replace(routeResponse.Result.Legs[0].Itinerary[i].Text,string.Empty); routeInfo.lat = routeResponse.Result.Legs[0].Itinerary[i].Location.Latitude; routeInfo.lon = routeResponse.Result.Legs[0].Itinerary[i].Location.Longitude; routeInfo.time = routeResponse.Result.Legs[0].Itinerary[i].Summary.TimeInSeconds; routeInfo.dist = routeResponse.Result.Legs[0].Itinerary[i].Summary.Distance; for(int j = 0 ; j < routeResponse.Result.Legs[0].Itinerary[i].Hints.Length ; j++) { routeInfo.hint.Add(regex.Replace(routeResponse.Result.Legs[0].Itinerary[i].Hints[j].Text,string.Empty)); } if(!language.Contains("en")) { routeInfo.description = TranslateMethod(routeInfo.description,"en",language); } routeList.Add(routeInfo); } } else return "No Route found"; return serializer.Serialize(routeList); } catch (Exception) { return "An exception occurred."; } }
public void GetTripAsync(List<Meeting> meetings) { if (meetings.Count()<=1) return; //Initialisation var request = new RouteRequest(); request.Credentials = new Credentials(); request.Credentials.ApplicationId = BingMapCredential.CREDENTIAL; request.Waypoints = new ObservableCollection<Waypoint>(); foreach (Meeting meeting in meetings) { if (IsCanceled) return; if (meeting.IsLocationFail) continue; request.Waypoints.Add(new Waypoint() { Location = new Location() { Latitude = meeting.Location.Latitude, Longitude = meeting.Location.Longitude } }); } request.Options = new RouteOptions(); request.Options.RoutePathType = RoutePathType.Points; request.UserProfile = new UserProfile(); request.UserProfile.DistanceUnit = DistanceUnit.Kilometer; var service = new RouteServiceClient("BasicHttpBinding_IRouteService"); //Réponse service.CalculateRouteCompleted += (o, e) => { if (IsCanceled) return; if (e.Error != null || e.Result == null) { try { Debug.WriteLine(e.Error.Message); } catch (Exception exception) { } TripReceived(this, new TripReceivedEventArgs(){Error = true}); return; } List<Trip> trips = new List<Trip>(); var legs = e.Result.Result.Legs; var countRoutePath = e.Result.Result.RoutePath.Points.Count; int lastIndex = 0; var count = legs.Count; for (int i = 0; i < count; i++) { if (IsCanceled) return; var leg = legs[i]; Trip trip = new Trip(); meetings[i].Location = leg.ActualStart; meetings[i + 1].Location = leg.ActualEnd; trip.Start = meetings[i]; trip.End = meetings[i + 1]; trip.Duration = leg.Summary.TimeInSeconds / 60; trip.Distance = leg.Summary.Distance; while (lastIndex < countRoutePath) { if (IsCanceled) return; Location point = e.Result.Result.RoutePath.Points[lastIndex]; if (Math.Round(trip.End.Location.Latitude, 5) == Math.Round(point.Latitude, 5) && Math.Round(trip.End.Location.Longitude, 5) == Math.Round(point.Longitude, 5)) { break; } trip.RoutePath.Add(point); lastIndex++; } trips.Add(trip); } TripReceived(this, new TripReceivedEventArgs(trips, e.Result.Result) ); }; //Appel service.CalculateRouteAsync(request); if (IsCanceled) return; }
public void RouteCalc(Pushpin p) { // Create the service variable and set the callback method using the CalculateRouteCompleted property. RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); routeService.CalculateRouteCompleted += new EventHandler<CalculateRouteCompletedEventArgs>(routeService_CalculateRouteCompleted); // Set the token. RouteRequest routeRequest = new RouteRequest(); routeRequest.Credentials = new LimaRoute.RouteService.Credentials(); routeRequest.Credentials.ApplicationId = "Av7R1AqbtqdVUDABzrWemEJHTh4ddfpZe6J_Y--onTh1xJ_a_hualfbL08DKiOB5"; // Return the route points so the route can be drawn. routeRequest.Options = new RouteOptions(); routeRequest.Options.RoutePathType = RoutePathType.Points; // Set the waypoints of the route to be calculated using the Geocode Service results stored in the geocodeResults variable. Waypoint waypoint1 = new Waypoint(); waypoint1.Location = new Location(); waypoint1.Description = "Mi ubicación"; waypoint1.Location.Latitude = watcher.Position.Location.Latitude; waypoint1.Location.Longitude = watcher.Position.Location.Longitude; Waypoint waypoint2 = new Waypoint(); waypoint2.Location = new Location(); waypoint2.Description = "Destino"; waypoint2.Location.Latitude = p.Location.Latitude; waypoint2.Location.Longitude = p.Location.Longitude; //Add the waypoints routeRequest.Waypoints = new ObservableCollection<Waypoint>(); routeRequest.Waypoints.Add(waypoint1); routeRequest.Waypoints.Add(waypoint2); // Make the CalculateRoute asnychronous request. routeService.CalculateRouteAsync(routeRequest); }
/// <summary> /// Calls a request to bing maps api which will calculate the route between several specified bikesttations. /// </summary> /// <param name="stations"></param> public void CalculateRoute() { //RouteServiceClient routeClient = new RouteServiceClient("BasicHttpBinding_IRouteService"); //routeClient.CalculateRouteCompleted += new EventHandler<CalculateRouteCompletedEventArgs>(CalculatedRoute_Completed); RouteRequest routeRequest = new RouteRequest(); routeRequest.Options = new RouteOptions(); routeRequest.Options.Mode = TravelMode.Driving; routeRequest.Options.Optimization = RouteOptimization.MinimizeDistance; routeRequest.Options.RoutePathType = RoutePathType.Points; routeRequest.Credentials = new Credentials(); routeRequest.Credentials.ApplicationId = BikeConsts.MAPS_KEY; routeRequest.Waypoints = new ObservableCollection<Waypoint>(); routeRequest.Waypoints.Add(CreateWaypoint(this.From.Location)); routeRequest.Waypoints.Add(CreateWaypoint(this.To.Location)); RouteServiceClient.BeginCalculateRoute(routeRequest, new AsyncCallback(EndCalculateRoute), null); }
private void CalculateRoute() { RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); routeService.CalculateRouteCompleted += new EventHandler<CalculateRouteCompletedEventArgs>(routeService_CalculateRouteCompleted); RouteRequest request = new RouteRequest(); request.Credentials = new Credentials(); request.Credentials.ApplicationId = ((ApplicationIdCredentialsProvider)map.CredentialsProvider).ApplicationId; request.Options = new RouteOptions(); request.Options.Optimization = RouteOptimization.MinimizeTime; request.Options.RoutePathType = RoutePathType.Points; request.Waypoints = new System.Collections.ObjectModel.ObservableCollection<Waypoint>(); Waypoint wayPointAcquirer = new Waypoint(); wayPointAcquirer.Location = new Location(); wayPointAcquirer.Location.Latitude = 40.738965; wayPointAcquirer.Location.Longitude = -73.996047; request.Waypoints.Add(wayPointAcquirer); foreach (UserModel user in list_User_Choosed) { Waypoint wayPoint = new Waypoint(); wayPoint.Description = user.Address; wayPoint.Location = new Location(); wayPoint.Location.Latitude = user.Latitude; wayPoint.Location.Longitude = user.Longitude; request.Waypoints.Add(wayPoint); } //foreach (GeocodeResult result in results) //{ // Waypoint wayPoint = new Waypoint(); // wayPoint.Description = result.DisplayName; // wayPoint.Location = new Location(); // wayPoint.Location.Latitude = result.Locations[0].Latitude; // wayPoint.Location.Longitude = result.Locations[0].Longitude; // request.Waypoints.Add(wayPoint); //} routeService.CalculateRouteAsync(request); }
/// <summary> /// Add driving directions for the given trail / address pair. /// </summary> /// <param name="address">The starting address.</param> /// <param name="trail">The trail ending address.</param> /// <returns>Task for asynchronous completion.</returns> private async Task AddDrivingDirections(Address address, Trail trail) { RouteRequest request = new RouteRequest { Credentials = new Credentials { ApplicationId = this.Configuration.ApplicationId, }, Waypoints = new[] { new Waypoint { Description = "Start", Location = new Location { Latitude = address.Coordinate.Latitude.Value, Longitude = address.Coordinate.Longitude.Value, }, }, new Waypoint { Description = "End", Location = new Location { Latitude = trail.Location.Latitude.Value, Longitude = trail.Location.Longitude.Value, }, }, }, }; ResponseSummary summary; RouteResult result; RetryPolicy policy = this.BuildRetryPolicy(); IRouteService routeService = this.RouteServiceFactory.CreateRouteService(); try { RouteResponse response = await policy.ExecuteAsync(() => routeService.CalculateRouteAsync(request)); summary = response.ResponseSummary; result = response.Result; } catch (FaultException<ResponseSummary> ex) { summary = ex.Detail; result = null; } finally { IDisposable disposable = routeService as IDisposable; if (disposable != null) { disposable.Dispose(); } } if (summary.StatusCode != ResponseStatusCode.Success) { if (summary.StatusCode == ResponseStatusCode.BadRequest && summary.FaultReason.Contains("No route was found for the waypoints provided.")) { this.Logger.WarnFormat("No route found between trail add address: '{0}', '{1}'", trail, address); } else { throw new ApplicationException(string.Format("Routing service call failed. {0}: {1}", summary.StatusCode, summary.FaultReason)); } } else { address.Directions.Add(new DrivingDirections { Address = address, Trail = trail, DrivingTimeSeconds = (int)result.Summary.TimeInSeconds, }); } }
private void btnMap2Yol_Click(object sender, RoutedEventArgs e) { RouteRequest routeRequest = new RouteRequest(); routeRequest.Culture = new System.Globalization.CultureInfo("en-US"); routeRequest.Options.RoutePathType = RoutePathType.Points; if (radioKYol.IsChecked == true) routeRequest.Options.Optimization = RouteOptimization.MinimizeDistance; else routeRequest.Options.Optimization = RouteOptimization.MinimizeTime; if (radioOpTrafik.IsChecked == true) routeRequest.Options.TrafficUsage = TrafficUsage.TrafficBasedTime; if (radioOpSTrafik.IsChecked == true) routeRequest.Options.TrafficUsage = TrafficUsage.TrafficBasedRouteAndTime; if (radioNOpTrafik.IsChecked == true) routeRequest.Options.TrafficUsage = TrafficUsage.None; if (radioDrvType.IsChecked == true) routeRequest.Options.Mode = TravelMode.Driving; else routeRequest.Options.Mode = TravelMode.Walking; for (int i = 0; i < ClientIslem.rotaPoints.Count; i++) { routeRequest.Waypoints.Add(ClientIslem.rotaPoints[i]); } if (ClientIslem.rotaPoints.Count < 2) MessageBox.Show("Harita üzerinde en az iki nokta belirlemelisiniz..","Dikkat!",MessageBoxButton.OK); else ClientIslem.yolAniProvider.CalculateRouteAsync(routeRequest); }
private void CalculateRouting(GeoCoordinate userPosition) { Waypoint endPosition = new Waypoint(); endPosition.Location = userPosition; var routeRequest = new RouteRequest(); routeRequest.Credentials = new Credentials(); routeRequest.Credentials.ApplicationId = "Al9X2Bk2UP07iOZG9N_pt4yGUWpLHcyGmG5EjiRSZDFi4EJn6AnF6MxtGfehDJZi"; routeRequest.Waypoints = new System.Collections.ObjectModel.ObservableCollection<Waypoint>(); routeRequest.Waypoints.Add(StartPosition); routeRequest.Waypoints.Add(endPosition); routeRequest.Options = new RouteOptions(); routeRequest.Options.RoutePathType = RoutePathType.Points; routeRequest.UserProfile = new UserProfile(); routeRequest.UserProfile.DistanceUnit = DistanceUnit.Kilometer; var routeClient = new RouteServiceClient("BasicHttpBinding_IRouteService"); routeClient.CalculateRouteCompleted += new EventHandler<CalculateRouteCompletedEventArgs>(routeClient_CalculateRouteCompleted); routeClient.CalculateRouteAsync(routeRequest); }
public List<TimedPosition> GetRoute(TimeSpan startTime, double startLat, double startLong, double endLat, double endLong, double speedOfTravel) { RouteRequest routeRequest = new RouteRequest(); routeRequest.Credentials = creds; routeRequest.Options = new RouteOptions() { RoutePathType = RoutePathType.Points }; Waypoint wp1 = new Waypoint() { Description = "Start", Location = new Location() { Latitude = startLat, Longitude = startLong } }; Waypoint wp2 = new Waypoint() { Description = "End", Location = new Location() { Latitude = endLat, Longitude = endLong } }; routeRequest.Waypoints = new Waypoint[] { wp1, wp2 }; // Make the calculate route request int attempts = 0; RouteResponse routeResponse = null; while (routeResponse == null && attempts < MaxServiceRetries) { try { routeResponse = routeService.CalculateRoute(routeRequest); } finally { attempts++; } } if (attempts == MaxServiceRetries | routeResponse.Result.RoutePath.Points.Length <2) return null; List<TimedPosition> path = new List<TimedPosition>(routeResponse.Result.RoutePath.Points.Length); System.Windows.Point startPoint, endPoint; startPoint = new System.Windows.Point( routeResponse.Result.RoutePath.Points[0].Longitude, routeResponse.Result.RoutePath.Points[0].Latitude); TimeSpan time = startTime; for (int i = 1; i < routeResponse.Result.RoutePath.Points.Length; i++) { endPoint = new System.Windows.Point( routeResponse.Result.RoutePath.Points[i].Longitude, routeResponse.Result.RoutePath.Points[i].Latitude); double distance = MapUtils.GetDistance(startPoint, endPoint); time = time.Add(TimeSpan.FromMilliseconds(100 * distance / speedOfTravel)); path.Add(new TimedPosition(time, routeResponse.Result.RoutePath.Points[i].Latitude, routeResponse.Result.RoutePath.Points[i].Longitude)); startPoint = endPoint; } return path; }
/// <summary> /// Not implemented. /// </summary> /// <param name="request">The parameter is not used.</param> /// <returns>Throws an exception.</returns> /// <seealso cref="IRouteService.CalculateRoute"/> public RouteResponse CalculateRoute(RouteRequest request) { throw new NotImplementedException(); }
public List<TimedPosition> GetRoute(TimeSpan startTime, double startLat, double startLong, double endLat, double endLong) { RouteRequest routeRequest = new RouteRequest(); routeRequest.Credentials = creds; routeRequest.Options = new RouteOptions() { RoutePathType = RoutePathType.Points }; Waypoint wp1 = new Waypoint() { Description = "Start", Location = new Location() { Latitude = startLat, Longitude = startLong } }; Waypoint wp2 = new Waypoint() { Description = "End", Location = new Location() { Latitude = endLat, Longitude = endLong } }; routeRequest.Waypoints = new Waypoint[] { wp1, wp2 }; // Make the calculate route request int attempts = 0; RouteResponse routeResponse = null; while (routeResponse == null && attempts < MaxServiceRetries) { try { routeResponse = routeService.CalculateRoute(routeRequest); } finally { attempts++; } } if (attempts == MaxServiceRetries | routeResponse.Result.RoutePath.Points.Length < 2) return null; List<TimedPosition> path = new List<TimedPosition>(); for (int i = 0; i < routeResponse.Result.RoutePath.Points.Length; i++) { if (i > 0) { routeRequest.Waypoints = new Waypoint[] { new Waypoint() { Location = new Location() { Longitude = routeResponse.Result.RoutePath.Points[i-1].Longitude, Latitude= routeResponse.Result.RoutePath.Points[i-1].Latitude } }, new Waypoint() { Location = new Location() { Longitude = routeResponse.Result.RoutePath.Points[i].Longitude, Latitude= routeResponse.Result.RoutePath.Points[i].Latitude } } }; RouteResponse subRouteResponse = routeService.CalculateRoute(routeRequest); startTime = startTime.Add(TimeSpan.FromSeconds(subRouteResponse.Result.Summary.TimeInSeconds)); } path.Add(new TimedPosition(startTime, routeResponse.Result.RoutePath.Points[i].Latitude, routeResponse.Result.RoutePath.Points[i].Longitude)); } return path; }
private void CalculateRoute(GeocodeResult[] locations) { RouteRequest request = new RouteRequest(); request.Waypoints = new ObservableCollection<Waypoint>(); foreach (GeocodeResult result in locations) { request.Waypoints.Add(GeocodeResultToWaypoint(result)); } // Don't raise exceptions. request.ExecutionOptions = new RouteService.ExecutionOptions(); request.ExecutionOptions.SuppressFaults = true; // Only accept results with high confidence. request.Options = new RouteOptions(); request.Options.RoutePathType = RoutePathType.Points; ((ClientTokenCredentialsProvider)App.Current.Resources["MyCredentials"]).GetCredentials( (Credentials credentials) => { //Pass in credentials for web services call. //Replace with your own Credentials. request.Credentials = credentials; // Make asynchronous call to fetch the data ... pass state object. RouteClient.CalculateRouteAsync(request); }); }
/// <summary> /// Calculates a route based on the distance between points. /// </summary> /// <param name="request">The request to calculate a route for..</param> /// <returns>A response with the calculated distance.</returns> /// <seealso cref="IRouteService.CalculateRouteAsync"/> public Task<RouteResponse> CalculateRouteAsync(RouteRequest request) { if (request == null) { throw new ArgumentNullException("request"); } const double secondsPerUnitDistance = 60 * 60; Location start = request.Waypoints[0].Location; Location end = request.Waypoints[0].Location; double northSouth = start.Latitude - end.Latitude; double eastWest = start.Longitude - end.Longitude; double approximateDistance = Math.Sqrt(Math.Pow(northSouth, 2) + Math.Pow(eastWest, 2)); int travelTimeSeconds = (int)(approximateDistance * secondsPerUnitDistance); RouteResponse response = new RouteResponse { ResponseSummary = new ResponseSummary { StatusCode = ResponseStatusCode.Success, }, Result = new RouteResult { Summary = new RouteSummary { TimeInSeconds = travelTimeSeconds, }, }, }; return TaskExt.WrapInTask(() => response); }