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; }
// // GET: /FMM/Route/Detail public async Task <ActionResult> Detail(string key) { using (RouteServiceClient client = new RouteServiceClient()) { MethodReturnResult <Route> result = await client.GetAsync(key); if (result.Code == 0) { RouteViewModel viewModel = new RouteViewModel() { Name = result.Data.Key, Status = result.Data.Status, CreateTime = result.Data.CreateTime, Creator = result.Data.Creator, Description = result.Data.Description, Editor = result.Data.Editor, EditTime = result.Data.EditTime }; return(PartialView("_InfoPartial", viewModel)); } else { ModelState.AddModelError("", result.Message); } } return(PartialView("_InfoPartial")); }
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); } }
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 async Task <ActionResult> SaveModify(RouteViewModel model) { using (RouteServiceClient client = new RouteServiceClient()) { MethodReturnResult <Route> result = await client.GetAsync(model.Name); if (result.Code == 0) { result.Data.Status = model.Status; result.Data.RouteType = model.RouteType; result.Data.Description = model.Description; result.Data.Editor = User.Identity.Name; result.Data.EditTime = DateTime.Now; MethodReturnResult rst = await client.ModifyAsync(result.Data); if (rst.Code == 0) { rst.Message = string.Format(FMMResources.StringResource.Route_SaveModify_Success , model.Name); } return(Json(rst)); } return(Json(result)); } }
public async Task <ActionResult> Copy(string key) { using (RouteServiceClient client = new RouteServiceClient()) { MethodReturnResult <Route> result = await client.GetAsync(key); if (result.Code == 0) { RouteViewModel model = new RouteViewModel() { Name = result.Data.Key, RouteType = result.Data.RouteType, Description = result.Data.Description, Status = result.Data.Status, Creator = User.Identity.Name, CreateTime = DateTime.Now, Editor = User.Identity.Name, EditTime = DateTime.Now, ParentName = key }; return(PartialView("_CopyPartial", model)); } else { ModelState.AddModelError("", result.Message); return(PartialView("_CopyPartial")); } } }
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 <ActionResult> Save(RouteViewModel model) { using (RouteServiceClient client = new RouteServiceClient()) { Route obj = new Route() { Key = model.Name, Status = model.Status, RouteType = model.RouteType, Description = model.Description, Editor = User.Identity.Name, EditTime = DateTime.Now, CreateTime = DateTime.Now, Creator = User.Identity.Name }; MethodReturnResult rst = await client.AddAsync(obj); if (rst.Code == 0) { rst.Message = string.Format(FMMResources.StringResource.Route_Save_Success , model.Name); } return(Json(rst)); } }
public async Task <ActionResult> Query(RouteQueryViewModel model) { if (ModelState.IsValid) { using (RouteServiceClient client = new RouteServiceClient()) { await Task.Run(() => { StringBuilder where = new StringBuilder(); if (model != null) { if (!string.IsNullOrEmpty(model.Name)) { where.AppendFormat(" {0} Key LIKE '{1}%'" , where.Length > 0 ? "AND" : string.Empty , model.Name); } } PagingConfig cfg = new PagingConfig() { OrderBy = "Key", Where = where.ToString() }; MethodReturnResult <IList <Route> > result = client.Get(ref cfg); if (result.Code == 0) { ViewBag.PagingConfig = cfg; ViewBag.List = result.Data; } }); } } return(PartialView("_ListPartial")); }
async public Task <MapPolyline> GetRouteAsync(GeoCoordinate from, GeoCoordinate to) { TaskCompletionSource <MapPolyline> tcs = new TaskCompletionSource <MapPolyline>(); RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); routeService.CalculateRouteCompleted += (sender, e) => { var points = e.Result.Result.RoutePath.Points; var coordinates = points.Select(x => new GeoCoordinate(x.Latitude, x.Longitude)); var routeColor = Colors.Blue; var routeBrush = new SolidColorBrush(routeColor); var routeLine = new MapPolyline() { Locations = new LocationCollection(), Stroke = routeBrush, Opacity = 0.65, StrokeThickness = 5.0, }; foreach (var location in points) { routeLine.Locations.Add(new GeoCoordinate(location.Latitude, location.Longitude)); } tcs.TrySetResult(routeLine); }; routeService.CalculateRouteAsync(new RouteRequest() { Credentials = new RoutesAPI.Credentials() { ApplicationId = Settings.BingmapsAPIKey }, Options = new RouteOptions() { RoutePathType = RoutePathType.Points }, Waypoints = new ObservableCollection <Waypoint>( new Waypoint[] { new Waypoint { Location = new Location { Latitude = to.Latitude, Longitude = to.Longitude } }, new Waypoint { Location = new Location { Latitude = from.Latitude, Longitude = from.Longitude } } }) }); return(await tcs.Task); }
private void Init() { client = new RouteServiceClient(); client.InitCache(); String[] cities = client.GetCities(); foreach (var obj in cities) { selectCity.Items.Add(obj); } }
public RouteDrawing() { InitializeComponent(); List<GeoCoordinate> locations = new List<GeoCoordinate>(); RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); routeService.CalculateRouteCompleted += (sender, e) => { var points = e.Result.Result.RoutePath.Points; var coordinates = points.Select(x => new GeoCoordinate(x.Latitude, x.Longitude)); var routeColor = Colors.Blue; var routeBrush = new SolidColorBrush(routeColor); var routeLine = new MapPolyline() { Locations = new LocationCollection(), Stroke = routeBrush, Opacity = 0.65, StrokeThickness = 5.0, }; foreach (var location in points) { routeLine.Locations.Add(new GeoCoordinate(location.Latitude, location.Longitude)); } RouteLayer.Children.Add(routeLine); }; RouteBingMap.SetView(LocationRect.CreateLocationRect(locations)); routeService.CalculateRouteAsync(new RouteRequest() { Credentials = new Credentials() { ApplicationId = "Ak-j1fNexs-uNWG_YoP2WZlthezPoUWsRvSexDLTGfjQ1XqKgnfR1nqeC2YbZZSn" }, Options = new RouteOptions() { RoutePathType = RoutePathType.Points }, Waypoints = new ObservableCollection<Waypoint>( locations.Select(x => new Waypoint() { Location = x.Location })) }); }
public async Task <ActionResult> Delete(string key) { MethodReturnResult result = new MethodReturnResult(); using (RouteServiceClient client = new RouteServiceClient()) { result = await client.DeleteAsync(key); if (result.Code == 0) { result.Message = string.Format(FMMResources.StringResource.Route_Delete_Success , key); } return(Json(result)); } }
private void btnTestService_Click(object sender, EventArgs e) { RouteService.IRouteService RouteService = new RouteServiceClient(); RouteServiceParameterDTO originalroute = new RouteServiceParameterDTO(); //originalroute.StreetAvenueName = "Rua XYZ de ABC"; originalroute.StreetAvenueName = "Rua Jose Fabiano Rodrigues"; originalroute.Number = "10"; originalroute.City = "Osasco"; originalroute.State = "SP"; RouteServiceParameterDTO destinationroute = new RouteServiceParameterDTO(); destinationroute.StreetAvenueName = "Avenida Manoel Pedro Pimentel"; destinationroute.Number = "155"; destinationroute.City = "Osasco"; destinationroute.State = "SP"; GetRouteRequest inValue = new GetRouteRequest(); inValue.Body = new GetRouteRequestBody(); RouteServiceParameterRequestDTO routeServiceParameterRequestDTO = new RouteServiceParameterRequestDTO(); routeServiceParameterRequestDTO.originalRoute = originalroute; routeServiceParameterRequestDTO.destinationRoute = destinationroute; routeServiceParameterRequestDTO.routeType = RouteType.FastestRoute; inValue.Body.routeParameterRequest = routeServiceParameterRequestDTO; try { GetRouteResponse retVal = RouteService.GetRoute(inValue); string result = "Distancia Total {0}. Custo Combustivel {1}. Tempo Total Rota {2}. Custo Considerando Pedagio {3}"; if (retVal.Body.GetRouteResult != null) { MessageBox.Show(string.Format(result, retVal.Body.GetRouteResult.TotalDistance.ToString(), retVal.Body.GetRouteResult.TotalFuelCost.ToString(), retVal.Body.GetRouteResult.TotalTime.ToString(), retVal.Body.GetRouteResult.TotalTollFeeCost.ToString())); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public RouteCalculator( CredentialsProvider credentialsProvider, string to, string from, Dispatcher uiDispatcher, Action <RouteResponse> routeFound) { if (credentialsProvider == null) { throw new ArgumentNullException("credentialsProvider"); } if (string.IsNullOrEmpty(to)) { throw new ArgumentNullException("to"); } if (string.IsNullOrEmpty(from)) { throw new ArgumentNullException("from"); } if (uiDispatcher == null) { throw new ArgumentNullException("uiDispatcher"); } if (routeFound == null) { throw new ArgumentNullException("routeFound"); } _credentialsProvider = credentialsProvider; _to = to; _from = from; _uiDispatcher = uiDispatcher; _routeFound = routeFound; _geocodeClient = new GeocodeServiceClient(); _geocodeClient.GeocodeCompleted += client_GeocodeCompleted; _routeClient = new RouteServiceClient(); _routeClient.CalculateRouteCompleted += client_RouteCompleted; }
private double GetDistanceBetweenCities(string mestoA, string mestoB) { gridCalculate.Visibility = Visibility.Visible; var request = new RouteRequest(); request.Credentials = new Credentials(); request.Credentials.ApplicationId = Properties.Resources.BingKey; var waypoints = new List <Waypoint>(2); waypoints.Add(GetCityWaypoint(mestoA)); waypoints.Add(GetCityWaypoint(mestoB)); request.Waypoints = waypoints.ToArray(); IRouteService client = new RouteServiceClient("BasicHttpBinding_IRouteService"); var routeResponse = client.CalculateRoute(request); gridCalculate.Visibility = Visibility.Collapsed; return(routeResponse.Result.Summary.Distance); }
public void EndCalculateRoute(IAsyncResult e) { RouteResponse response = RouteServiceClient.EndCalculateRoute(e); if ((response.ResponseSummary.StatusCode == RouteService.ResponseStatusCode.Success) & (response.Result.Legs.Count != 0)) { LocationCollection locations = new LocationCollection(); foreach (Location p in response.Result.RoutePath.Points) { //add the location also to the location collection locations.Add(p); } this.Locations = locations; this.Distance = response.Result.Summary.Distance; this.Time = (int)response.Result.Summary.TimeInSeconds / 60 * BikeConsts.DRIVE_TO_BIKE; } }
void pin_Tap(object sender1, System.Windows.Input.GestureEventArgs e1) { List <GeoCoordinate> locations = new List <GeoCoordinate>(); locations.Add(currentLocation); Pushpin senderAs = sender1 as Pushpin; locations.Add(senderAs.Location); destination = senderAs; DestinationPoint.Children.Clear(); DestinationPoint.Children.Add(destination); RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); routeService.CalculateRouteCompleted += (sender, e) => { DrawRoute(e); }; mapBing.SetView(LocationRect.CreateLocationRect(locations)); routeService.CalculateRouteAsync(new RouteRequest() { Credentials = new Credentials() { ApplicationId = LocationManager.bingApiKey }, Options = new RouteOptions() { RoutePathType = RoutePathType.Points }, Waypoints = new ObservableCollection <Waypoint>( locations.Select(x => new Waypoint() { Location = new Microsoft.Phone.Controls.Maps.Platform.Location() { Latitude = x.Latitude, Longitude = x.Longitude } })) }); SetDriveMode(true); }
/// <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); }
// // GET: /FMM/Route/ public async Task <ActionResult> Index() { using (RouteServiceClient client = new RouteServiceClient()) { await Task.Run(() => { PagingConfig cfg = new PagingConfig() { OrderBy = "Key" }; MethodReturnResult <IList <Route> > result = client.Get(ref cfg); if (result.Code == 0) { ViewBag.PagingConfig = cfg; ViewBag.List = result.Data; } }); } return(View(new RouteQueryViewModel())); }
/// <summary> /// 根据工艺流程代码取得工艺流程类型 /// </summary> /// <param name="RouteName"></param> /// <returns></returns> public string GetRouteTypeName(string routeName) { string routeTypeName = ""; using (RouteServiceClient client = new RouteServiceClient()) { PagingConfig cfg = new PagingConfig() { IsPaging = false, Where = string.Format("Key = '{0}'", routeName) }; MethodReturnResult <IList <Route> > result = client.Get(ref cfg); if (result.Code <= 0 && result.Data.Count > 0) { routeTypeName = result.Data[0].RouteType.GetDisplayName(); } } return(routeTypeName); }
public RouteCalculator( CredentialsProvider credentialsProvider, Location to, Location from, Dispatcher uiDispatcher, Action <RouteResponse> routeFound) { if (credentialsProvider == null) { throw new ArgumentNullException("credentialsProvider"); } if (uiDispatcher == null) { throw new ArgumentNullException("uiDispatcher"); } if (routeFound == null) { throw new ArgumentNullException("routeFound"); } from_address = false; x_from = from; x_to = to; _credentialsProvider = credentialsProvider; _uiDispatcher = uiDispatcher; _routeFound = routeFound; _routeClient = new RouteServiceClient(); _routeClient.CalculateRouteCompleted += client_RouteCompleted; // Calculate the route. CalculateRoute(); }
public async Task <ActionResult> PagingQuery(string where, string orderBy, int?currentPageNo, int?currentPageSize) { if (ModelState.IsValid) { int pageNo = currentPageNo ?? 0; int pageSize = currentPageSize ?? 20; if (Request["PageNo"] != null) { pageNo = Convert.ToInt32(Request["PageNo"]); } if (Request["PageSize"] != null) { pageSize = Convert.ToInt32(Request["PageSize"]); } using (RouteServiceClient client = new RouteServiceClient()) { await Task.Run(() => { PagingConfig cfg = new PagingConfig() { PageNo = pageNo, PageSize = pageSize, Where = where ?? string.Empty, OrderBy = orderBy ?? string.Empty }; MethodReturnResult <IList <Route> > result = client.Get(ref cfg); if (result.Code == 0) { ViewBag.PagingConfig = cfg; ViewBag.List = result.Data; } }); } } return(PartialView("_ListPartial")); }
public IEnumerable <SelectListItem> GetRouteNameList() { using (RouteServiceClient client = new RouteServiceClient()) { PagingConfig cfg = new PagingConfig() { IsPaging = false, Where = string.Format("Status='{0}'", Convert.ToInt32(EnumObjectStatus.Available)) }; MethodReturnResult <IList <Route> > result = client.Get(ref cfg); if (result.Code <= 0) { IEnumerable <SelectListItem> lst = from item in result.Data select new SelectListItem() { Text = item.Key, Value = item.Key }; return(lst); } } return(new List <SelectListItem>()); }
// // GET: /FMM/RouteStep/ public async Task <ActionResult> Index(string routeName) { using (RouteServiceClient client = new RouteServiceClient()) { MethodReturnResult <Route> result = await client.GetAsync(routeName ?? string.Empty); if (result.Code > 0 || result.Data == null) { return(RedirectToAction("Index", "Route")); } ViewBag.Route = result.Data; } using (RouteStepServiceClient client = new RouteStepServiceClient()) { await Task.Run(() => { PagingConfig cfg = new PagingConfig() { OrderBy = "SortSeq", Where = string.Format("Key.RouteName='{0}'", routeName) }; MethodReturnResult <IList <RouteStep> > result = client.Get(ref cfg); if (result.Code == 0) { ViewBag.PagingConfig = cfg; ViewBag.List = result.Data; } }); } return(View(new RouteStepQueryViewModel() { RouteName = routeName })); }
public RouteCalculator( CredentialsProvider credentialsProvider, string to, string from, Dispatcher uiDispatcher, Action<RouteResponse> routeFound) { if (credentialsProvider == null) { throw new ArgumentNullException("credentialsProvider"); } if (string.IsNullOrEmpty(to)) { throw new ArgumentNullException("to"); } if (string.IsNullOrEmpty(from)) { throw new ArgumentNullException("from"); } if (uiDispatcher == null) { throw new ArgumentNullException("uiDispatcher"); } if (routeFound == null) { throw new ArgumentNullException("routeFound"); } _credentialsProvider = credentialsProvider; _to = to; _from = from; _uiDispatcher = uiDispatcher; _routeFound = routeFound; _geocodeClient = new GeocodeServiceClient(); _geocodeClient.GeocodeCompleted += client_GeocodeCompleted; _routeClient = new RouteServiceClient(); _routeClient.CalculateRouteCompleted += client_RouteCompleted; }
private string CreateRoute(double ot0, double ot1, double to0, double to1) { string results = ""; RouteRequest routeRequest = new RouteRequest(); // Set the credentials using a valid Bing Maps key routeRequest.Credentials = new Microsoft.Maps.MapControl.WPF.Credentials(); routeRequest.Credentials.ApplicationId = key; //Parse user data to create array of waypoints Waypoint[] waypoints = new Waypoint[2]; waypoints[0] = new Waypoint(); waypoints[0].Location = new RouteService.Location(); waypoints[0].Location.Latitude = ot0; waypoints[0].Location.Longitude = ot1; waypoints[1] = new Waypoint(); waypoints[1].Location = new RouteService.Location(); waypoints[1].Location.Latitude = to0; waypoints[1].Location.Longitude = to1; routeRequest.Waypoints = waypoints; // Make the calculate route request RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); RouteResponse routeResponse = routeService.CalculateRoute(routeRequest); MapPolyline mapPolyline = new MapPolyline(); // mapPolyline. = routeResponse.Result.RoutePath; // mapPolyline.StrokeColor = Colors.Black; // mapPolyline.StrokeThickness = 3; // mapPolyline.StrokeDashed = true; MapRoute.Children.Add(mapPolyline); // 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 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 RouteCalculator( CredentialsProvider credentialsProvider, Location to, Location from, Dispatcher uiDispatcher, Action<RouteResponse> routeFound) { if (credentialsProvider == null) { throw new ArgumentNullException("credentialsProvider"); } if (uiDispatcher == null) { throw new ArgumentNullException("uiDispatcher"); } if (routeFound == null) { throw new ArgumentNullException("routeFound"); } from_address = false; x_from = from; x_to = to; _credentialsProvider = credentialsProvider; _uiDispatcher = uiDispatcher; _routeFound = routeFound; _routeClient = new RouteServiceClient(); _routeClient.CalculateRouteCompleted += client_RouteCompleted; // Calculate the route. CalculateRoute(); }
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); }
private string CreateMajorRoutes(string locationString) { string results = ""; MajorRoutesRequest majorRoutesRequest = new MajorRoutesRequest(); // Set the credentials using a valid Bing Maps key majorRoutesRequest.Credentials = new RouteService.Credentials(); majorRoutesRequest.Credentials.ApplicationId = key; // Set the destination of the routes from major roads Waypoint endPoint = new Waypoint(); endPoint.Location = new RouteService.Location(); string[] digits = locationString.Split(','); endPoint.Location.Latitude = double.Parse(digits[0].Trim()); endPoint.Location.Longitude = double.Parse(digits[1].Trim()); endPoint.Description = "Location"; // Set the option to return full routes with directions MajorRoutesOptions options = new MajorRoutesOptions(); options.ReturnRoutes = true; majorRoutesRequest.Destination = endPoint; majorRoutesRequest.Options = options; // Make the route-from-major-roads request RouteServiceClient routeService = new RouteServiceClient(); // The result is an MajorRoutesResponse Object MajorRoutesResponse majorRoutesResponse = routeService.CalculateRoutesFromMajorRoads(majorRoutesRequest); Regex regex = new Regex("<[/a-zA-Z:]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline); if (majorRoutesResponse.StartingPoints.Length > 0) { StringBuilder directions = new StringBuilder(); for (int i = 0; i < majorRoutesResponse.StartingPoints.Length; i++) { directions.Append(String.Format("Coming from {1}\n", i + 1, majorRoutesResponse.StartingPoints[i].Description)); for (int j = 0; j < majorRoutesResponse.Routes[i].Legs[0].Itinerary.Length; j++) { //Strip tags string step = regex.Replace( majorRoutesResponse.Routes[i].Legs[0].Itinerary[j].Text, string.Empty); directions.Append(String.Format(" {0}. {1}\n", j + 1, step)); } } results = directions.ToString(); } else results = "No Routes found"; return results; }
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); }
// This method makes the initial CalculateRoute asynchronous request using the results of the Geocode Service. private void CalculateRoute(GeocodeService.GeocodeResult[] locations) { // 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 credentials. RouteService.RouteRequest routeRequest = new RouteService.RouteRequest(); routeRequest.Culture = MyMap.Culture; routeRequest.Credentials = new RouteService.Credentials(); routeRequest.Credentials.ApplicationId = ((ApplicationIdCredentialsProvider)MyMap.CredentialsProvider).ApplicationId; // Return the route points so the route can be drawn. routeRequest.Options = new RouteService.RouteOptions(); routeRequest.Options.RoutePathType = RouteService.RoutePathType.Points; // Set the waypoints of the route to be calculated using the Geocode Service results stored in the geocodeResults variable. routeRequest.Waypoints = new System.Collections.ObjectModel.ObservableCollection<RouteService.Waypoint>(); foreach (GeocodeService.GeocodeResult result in locations) { routeRequest.Waypoints.Add(GeocodeResultToWaypoint(result)); } // Make asynchronous call to fetch the data ... pass state object. // Make the CalculateRoute asnychronous request. routeService.CalculateRouteAsync(routeRequest); }
void pin_Tap(object sender1, System.Windows.Input.GestureEventArgs e1) { List<GeoCoordinate> locations = new List<GeoCoordinate>(); locations.Add(currentLocation); Pushpin senderAs = sender1 as Pushpin; locations.Add(senderAs.Location); destination = senderAs; DestinationPoint.Children.Clear(); DestinationPoint.Children.Add(destination); RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); routeService.CalculateRouteCompleted += (sender, e) => { DrawRoute(e); }; mapBing.SetView(LocationRect.CreateLocationRect(locations)); routeService.CalculateRouteAsync(new RouteRequest() { Credentials = new Credentials() { ApplicationId = LocationManager.bingApiKey }, Options = new RouteOptions() { RoutePathType = RoutePathType.Points }, Waypoints = new ObservableCollection<Waypoint>( locations.Select(x => new Waypoint() { Location = new Microsoft.Phone.Controls.Maps.Platform.Location() { Latitude = x.Latitude, Longitude = x.Longitude } })) }); SetDriveMode(true); }
//The Route Service private string CreateRoute(string waypointString) { string results = ""; string key = "ApwndqJgdJ9M1Bpb7d_ihBwXW-J0N3HdXrZvFZqvFtmeYN5DewRoGPI7czgFo5Sh"; 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); }
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 async Task <ActionResult> SaveCopy(RouteViewModel model) { Route obj = new Route() { Key = model.Name, RouteType = model.RouteType, Status = model.Status, Description = model.Description, Creator = User.Identity.Name, CreateTime = DateTime.Now, Editor = User.Identity.Name, EditTime = DateTime.Now }; MethodReturnResult result = new MethodReturnResult(); using (RouteServiceClient client = new RouteServiceClient()) { result = await client.AddAsync(obj); if (result.Code == 0) { result.Message = "复制工艺流程主体成功"; StringBuilder where = new StringBuilder(); using (RouteStepServiceClient routeStepServiceClient = new RouteStepServiceClient()) { where.AppendFormat(" Key.RouteName ='{0}'", model.ParentName); PagingConfig cfg = new PagingConfig() { IsPaging = false, OrderBy = "SortSeq", Where = where.ToString() }; MethodReturnResult <IList <RouteStep> > routeStep = routeStepServiceClient.Get(ref cfg); if (routeStep.Code == 0) { List <RouteStep> listOfRouteStep = routeStep.Data.ToList <RouteStep>(); foreach (RouteStep itemOfRouteStep in listOfRouteStep) { #region 制工步信息 RouteStep objRouteStep = new RouteStep() { Key = new RouteStepKey() { RouteName = model.Name, RouteStepName = itemOfRouteStep.Key.RouteStepName }, DefectReasonCodeCategoryName = itemOfRouteStep.DefectReasonCodeCategoryName, Duration = itemOfRouteStep.Duration, ScrapReasonCodeCategoryName = itemOfRouteStep.ScrapReasonCodeCategoryName, SortSeq = itemOfRouteStep.SortSeq, RouteOperationName = itemOfRouteStep.RouteOperationName, Description = itemOfRouteStep.Description, Editor = User.Identity.Name, EditTime = DateTime.Now, CreateTime = DateTime.Now, Creator = User.Identity.Name }; MethodReturnResult rstOfRouteStep = await routeStepServiceClient.AddAsync(objRouteStep); if (rstOfRouteStep.Code != 0) { result.Code = 1001; result.Message = "复制工步信息失败" + rstOfRouteStep.Message; return(Json(result)); } #endregion #region 制工步参数 using (RouteStepParameterServiceClient routeStepParameterServiceClient = new RouteStepParameterServiceClient()) { #region 除新增工艺流程工步带过来的工步参数 cfg = new PagingConfig() { Where = string.Format(" Key.RouteName='{0}' AND Key.RouteStepName = '{1}'" , model.Name , itemOfRouteStep.Key.RouteStepName), OrderBy = "ParamIndex" }; MethodReturnResult <IList <RouteStepParameter> > routeStepParameterNewAdd = routeStepParameterServiceClient.Get(ref cfg); if (routeStepParameterNewAdd.Code == 0) { List <RouteStepParameter> listOfRouteStepParameterNewAdd = routeStepParameterNewAdd.Data.ToList <RouteStepParameter>(); foreach (RouteStepParameter itemOfRouteStepParameterNewAdd in listOfRouteStepParameterNewAdd) { MethodReturnResult rstOfRouteStepParameterNewAdd = routeStepParameterServiceClient.Delete(itemOfRouteStepParameterNewAdd.Key); if (rstOfRouteStepParameterNewAdd.Code != 0) { result.Code = 1001; result.Message = "删除初始工步参数信息失败" + rstOfRouteStepParameterNewAdd.Message; return(Json(result)); } } } #endregion #region 制工步参数 cfg = new PagingConfig() { Where = string.Format(" Key.RouteName='{0}' AND Key.RouteStepName = '{1}'" , model.ParentName , itemOfRouteStep.Key.RouteStepName), OrderBy = "ParamIndex" }; MethodReturnResult <IList <RouteStepParameter> > routeStepParameter = routeStepParameterServiceClient.Get(ref cfg); if (routeStepParameter.Code == 0) { List <RouteStepParameter> listOfRouteStepParameter = routeStepParameter.Data.ToList <RouteStepParameter>(); foreach (RouteStepParameter itemOfRouteStepParameter in listOfRouteStepParameter) { RouteStepParameter objRouteStepParameter = new RouteStepParameter() { Key = new RouteStepParameterKey() { RouteName = model.Name, RouteStepName = itemOfRouteStepParameter.Key.RouteStepName, ParameterName = itemOfRouteStepParameter.Key.ParameterName }, MaterialType = itemOfRouteStepParameter.MaterialType, DataFrom = itemOfRouteStepParameter.DataFrom, DataType = itemOfRouteStepParameter.DataType, DCType = itemOfRouteStepParameter.DCType, IsDeleted = itemOfRouteStepParameter.IsDeleted, IsMustInput = itemOfRouteStepParameter.IsMustInput, IsReadOnly = itemOfRouteStepParameter.IsReadOnly, IsUsePreValue = itemOfRouteStepParameter.IsUsePreValue, ParamIndex = itemOfRouteStepParameter.ParamIndex, ValidateFailedMessage = itemOfRouteStepParameter.ValidateFailedMessage, ValidateFailedRule = itemOfRouteStepParameter.ValidateFailedRule, ValidateRule = itemOfRouteStepParameter.ValidateRule, Editor = User.Identity.Name, EditTime = DateTime.Now, }; MethodReturnResult rstOfRouteStepParameter = await routeStepParameterServiceClient.AddAsync(objRouteStepParameter); if (rstOfRouteStepParameter.Code != 0) { result.Code = 1001; result.Message = "复制工步参数信息失败" + rstOfRouteStepParameter.Message; return(Json(result)); } } } #endregion } #endregion #region 制工步属性 using (RouteStepAttributeServiceClient routeStepAttributeServiceClient = new RouteStepAttributeServiceClient()) { #region 除新增工艺流程工步带过来的工步属性 cfg = new PagingConfig() { Where = string.Format(" Key.RouteName='{0}' AND Key.RouteStepName = '{1}'" , model.Name , itemOfRouteStep.Key.RouteStepName), OrderBy = "Key.AttributeName" }; MethodReturnResult <IList <RouteStepAttribute> > routeStepAttributeNewAdd = routeStepAttributeServiceClient.Get(ref cfg); if (routeStepAttributeNewAdd.Code == 0) { List <RouteStepAttribute> listOfRouteStepAttributeNewAdd = routeStepAttributeNewAdd.Data.ToList <RouteStepAttribute>(); foreach (RouteStepAttribute itemOfRouteStepAttributeNewAdd in listOfRouteStepAttributeNewAdd) { MethodReturnResult rstOfRouteStepAttributeNewAdd = routeStepAttributeServiceClient.Delete(itemOfRouteStepAttributeNewAdd.Key); if (rstOfRouteStepAttributeNewAdd.Code != 0) { result.Code = 1001; result.Message = "删除初始工步属性信息失败" + rstOfRouteStepAttributeNewAdd.Message; return(Json(result)); } } } #endregion #region 制工步属性 cfg = new PagingConfig() { Where = string.Format(" Key.RouteName='{0}' AND Key.RouteStepName = '{1}'" , model.ParentName , itemOfRouteStep.Key.RouteStepName), OrderBy = "Key.AttributeName" }; MethodReturnResult <IList <RouteStepAttribute> > routeStepAttribute = routeStepAttributeServiceClient.Get(ref cfg); if (routeStepAttribute.Code == 0) { List <RouteStepAttribute> listOfRouteStepAttribute = routeStepAttribute.Data.ToList <RouteStepAttribute>(); foreach (RouteStepAttribute itemOfRouteStepAttribute in listOfRouteStepAttribute) { RouteStepAttribute objRouteStepAttribute = new RouteStepAttribute() { Key = new RouteStepAttributeKey() { RouteName = model.Name, RouteStepName = itemOfRouteStepAttribute.Key.RouteStepName, AttributeName = itemOfRouteStepAttribute.Key.AttributeName }, Value = itemOfRouteStepAttribute.Value, Editor = User.Identity.Name, EditTime = DateTime.Now, }; MethodReturnResult rstOfRouteStepAttribute = await routeStepAttributeServiceClient.AddAsync(objRouteStepAttribute); if (rstOfRouteStepAttribute.Code != 0) { result.Code = 1001; result.Message = "复制工步属性信息失败" + rstOfRouteStepAttribute.Message; return(Json(result)); } } } #endregion } #endregion } result.Message += " \r\n 复制工艺流程工步参数及工步属性成功"; } } } } return(Json(result)); }
private string CreateMajorRoutes(string locationString) { string results = ""; string key = "ArLeGdHOcc5h7j3L4W37oFGcU9E-LF3tAZi4o0DfhXbPJ8aiyTGbIDNHex08R2u7"; MajorRoutesRequest majorRoutesRequest = new MajorRoutesRequest(); // Set the credentials using a valid Bing Maps key majorRoutesRequest.Credentials = new RouteService.Credentials(); majorRoutesRequest.Credentials.ApplicationId = key; // Set the destination of the routes from major roads Waypoint endPoint = new Waypoint(); endPoint.Location = new RouteService.Location(); string[] digits = locationString.Split(','); endPoint.Location.Latitude = double.Parse(digits[0].Trim()); endPoint.Location.Longitude = double.Parse(digits[1].Trim()); endPoint.Description = "Location"; // Set the option to return full routes with directions MajorRoutesOptions options = new MajorRoutesOptions(); options.ReturnRoutes = true; majorRoutesRequest.Destination = endPoint; majorRoutesRequest.Options = options; // Make the route-from-major-roads request RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); // The result is an MajorRoutesResponse Object MajorRoutesResponse majorRoutesResponse = routeService.CalculateRoutesFromMajorRoads(majorRoutesRequest); Regex regex = new Regex("<[/a-zA-Z:]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline); if (majorRoutesResponse.StartingPoints.Length > 0) { StringBuilder directions = new StringBuilder(); for (int i = 0; i < majorRoutesResponse.StartingPoints.Length; i++) { directions.Append(String.Format("Coming from {1}\n", i + 1, majorRoutesResponse.StartingPoints[i].Description)); for (int j = 0; j < majorRoutesResponse.Routes[i].Legs[0].Itinerary.Length; j++) { //Strip tags string step = regex.Replace( majorRoutesResponse.Routes[i].Legs[0].Itinerary[j].Text, string.Empty); directions.Append(String.Format(" {0}. {1}\n", j + 1, step)); } } results = directions.ToString(); } else { results = "No Routes found"; } return(results); }
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; }