public static async void CalculateRoute(MapControl mapControl,double startLatitude, double startLongitude, double endLatitude, double endLongitude) { BasicGeoposition startLocation = new BasicGeoposition(); startLocation.Latitude = startLatitude; startLocation.Longitude = startLongitude; Geopoint startPoint = new Geopoint(startLocation); BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Latitude = endLatitude; endLocation.Longitude = endLongitude; Geopoint endPoint = new Geopoint(endLocation); MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Aqua; viewOfRoute.OutlineColor = Colors.Black; mapControl.Routes.Add(viewOfRoute); await mapControl.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); var distance = routeResult.Route.LengthInMeters.ToString(); } }
private async void Draw() { var geoLocator = new Geolocator(); Geoposition pos = await geoLocator.GetGeopositionAsync(); Geocoordinate cor = pos.Coordinate; Geopoint startPoint = cor.Point; myMap.Center = startPoint; //21.0236917063594 105.797116253525 BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Latitude = 21.0236917063594; endLocation.Longitude = 105.797116253525; Geopoint endPoint = new Geopoint(endLocation); //AddMarker(endPoint); // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync (startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.Highways); MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); // Add the new MapRouteView to the Routes collection // of the MapControl. myMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. //await myMap.TrySetViewBoundsAsync( // routeResult.Route.BoundingBox, // null, // Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); //if (routeResult.Status == MapRouteFinderStatus.Success) //{ // // Use the route to initialize a MapRouteView. // viewOfRoute = new MapRouteView(routeResult.Route); // // Add the new MapRouteView to the Routes collection // // of the MapControl. //} //myMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. //await myMap.TrySetViewBoundsAsync( // routeResult.Route.BoundingBox, // null, // Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); }
private async void ShowRoute(Location from, Location to) { try { if ((App.Current as App).UserLocation != null) { ClearAllMapItems(); this.Map.Routes.Clear(); //Tijdelijke locatie aanmaken BasicGeoposition tempFrom = new BasicGeoposition(); tempFrom.Longitude = from.Longitude; tempFrom.Latitude = from.Latitude; BasicGeoposition tempTo = new BasicGeoposition(); tempTo.Longitude = to.Longitude; tempTo.Latitude = to.Latitude; //Start en eindpunt ophalen en klaarzetten voor onderstaande vraag Geopoint startpunt = new Geopoint(tempFrom); Geopoint eindpunt = new Geopoint(tempTo); //De route tussen 2 punten opvragen MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync(startpunt, eindpunt); if (routeResult.Status == MapRouteFinderStatus.Success)//Het is gelukt, we hebben een antwoord gekregen. { MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Color.FromArgb(255, 62, 94, 148); this.Map.Routes.Add(viewOfRoute); //Fit de mapcontrol op de route await this.Map.TrySetViewBoundsAsync(routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); } } } catch (Exception ex) { } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { // Show users part = e.Parameter as Campuses; SQLiteAsyncConnection connection = new SQLiteAsyncConnection("institutionFinder.db"); var users = await connection.QueryAsync<Campuses>("Select * FROM Campuses WHERE Name ='" + part.Name + "'"); // Get users camp = users.FirstOrDefault(); map.MapServiceToken = "yvPVkyiTloR2lug6UK3uVg"; map.Center = new Geopoint(new BasicGeoposition() { Latitude = camp.Latitude, Longitude = camp.Longitude }); map.ZoomLevel = 15; map.LandmarksVisible = true; MapIcon MapIcon1 = new MapIcon(); MapIcon1.Location = new Geopoint(new BasicGeoposition() { Latitude = camp.Latitude, Longitude = camp.Longitude }); MapIcon1.NormalizedAnchorPoint = new Point(10,10); MapIcon1.Title = camp.Name; map.MapElements.Add(MapIcon1); MapIcon1.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///ViewModels/map.jpg")); Windows.UI.Xaml.Shapes.Ellipse fence = new Windows.UI.Xaml.Shapes.Ellipse(); MapControl.SetNormalizedAnchorPoint(fence, new Point(0.5, 0.5)); // Get a route as shown previously. BasicGeoposition startLocation = new BasicGeoposition(); startLocation.Latitude = -25.73134; startLocation.Longitude = 28.21837; Geopoint startPoint = new Geopoint(startLocation); // End at the city of Seattle, Washington. BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Latitude = camp.Latitude; endLocation.Longitude = camp.Longitude; Geopoint endPoint = new Geopoint(endLocation); MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Yellow; viewOfRoute.OutlineColor = Colors.Black; // Add the new MapRouteView to the Routes collection // of the MapControl. map.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await map.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); } }
private async void UpdateRouteOnMap() { List<Bestelling> route = AppGlobal.Instance.BestellingController.Bestellingen; if (!route.Any()) { // Route is finished AppGlobal.Instance._CurrentSession.CurrentRoute = null; AppGlobal.Instance._CurrentSession.FollowedRoute = null; } else { List<Bestelling> firstRoute = new List<Bestelling>(); firstRoute.Add(route.ElementAt(0)); // Get the route between the points. MapRouteFinderResult routePoints = await AppGlobal.Instance._GeoUtil.GetRoutePoint2Point(route); // MapRouteFinderResult currentPath = await AppGlobal.Instance._GeoUtil.GetRoutePoint2Point(firstRoute); if (routePoints.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routePoints.Route); viewOfRoute.RouteColor = Colors.LightGray; viewOfRoute.OutlineColor = Colors.LightGray; MapRouteView currentFollowingPath = new MapRouteView(routePoints.Route); currentFollowingPath.RouteColor = Colors.Crimson; currentFollowingPath.OutlineColor = Colors.Crimson; // Add the new MapRouteView to the Routes collection // of the MapControl. MapControl1.Routes.Clear(); MapControl1.Routes.Add(viewOfRoute); MapControl1.Routes.Add(currentFollowingPath); } } }
//el function di bta5od no2teten, wa7da start w wa7da end, then btrsm el route 3ala 5areta private async void ShowRouteOnMap() { BasicGeoposition startLocation = new BasicGeoposition(); startLocation.Latitude = 30.054632; startLocation.Longitude = 31.314325; Geopoint startPoint = new Geopoint(startLocation); BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Latitude = 30.045189; endLocation.Longitude = 31.270243; Geopoint endPoint = new Geopoint(endLocation); // Get a route as shown previously. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Yellow; viewOfRoute.OutlineColor = Colors.Black; // Add the new MapRouteView to the Routes collection // of the MapControl. MyMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await MyMap.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); } }
public async void GetRouteWithToken(Geopoint endPoint, CancellationToken token, Favorite favorite = null, int retry = 0) { if (favorite != null) { ShowSearchLocationPoint(endPoint, favorite.Name); if (userLastLocation == null) { //var dialog = new MessageDialog( // "To get there, the phone must find your location first. Please wait a bit an try again."); //await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => //{ // await dialog.ShowAsync(); //}); await MapCtrl.TrySetViewAsync(endPoint, 15, 0, null); } else { // Fit the MapControl to the route. await MapCtrl.TrySetViewBoundsAsync(MapExtensions.GetAreaFromLocations(new List<Geopoint>() { userLastLocation, endPoint }), new Thickness(40, 40, 40, 40), MapAnimationKind.None); } return; } if (userLastLocation == null) return; if (previousRouteEndingPoint == endPoint && userLastLocation == previousRouteStartingPoint) { Debug.WriteLine("Skip route finder : same location provided."); return; } previousRouteStartingPoint = userLastLocation; previousRouteEndingPoint = endPoint; var task = FindRoute(userLastLocation, endPoint); if (task != await Task.WhenAny(task, Task.Delay(2000, token))) { MapCtrl.Routes.Clear(); // timout case Debug.WriteLine("get route TIMEOUT or CANCELED !"); // BUG : apparently MapRouteFinder.GetWalkingRouteAsync is on UI thread. don't recall it again // if (!token.IsCancellationRequested && retry < 5) // GetRouteWithToken(endPoint, token, null, ++retry); return; } var routeResult = task.Result; //var routeResult = task.Result; Debug.WriteLine("get route ended with result : " + routeResult.Status); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = new SolidColorBrush((Application.Current.Resources["PhoneAccentBrush"] as SolidColorBrush).Color).Color; viewOfRoute.OutlineColor = Colors.Black; if (previousMapRoute == null || previousMapRoute.LengthInMeters != routeResult.Route.LengthInMeters) { MapCtrl.Routes.Clear(); Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { // Add the new MapRouteView to the Routes collection // of the MapControl. MapCtrl.Routes.Add(viewOfRoute); ShowUserLocation(); }); } previousMapRoute = routeResult.Route; } else { MapCtrl.Routes.Clear(); } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { this.navigationHelper.OnNavigatedTo(e); this.navigationHelper.OnNavigatedTo(e); ContengRentRoom data = e.Parameter as ContengRentRoom; string partyTitle = (string)e.Parameter; lblTitle.Text = partyTitle; // Load data MobileServiceInvalidOperationException exception = null; try { items = await partyTable .Where(Party => Party.partyTitle == partyTitle) .ToCollectionAsync(); } catch (MobileServiceInvalidOperationException ex) { exception = ex; } if (exception != null) { await new MessageDialog(exception.Message, "Error loading items").ShowAsync(); } else { // Show data lblTitle.Text = items[0].partyTitle; lblTime.Text = items[0].time; lblContact.Text = items[0].contact; lblContent.Text = items[0].content; lblCrowd.Text = items[0].crowd; lblPrice.Text = items[0].price; tbxPublisher.Text = items[0].publisher; lblAddress.Text = items[0].address; try { // Download image from blob // Souece: http://stackoverflow.com/questions/23256372/windows-phone-8-1-loading-images-from-remote-urls-placeholder Uri myUri = new Uri(items[0].imageAddress, UriKind.Absolute); BitmapImage bmi = new BitmapImage(); bmi.CreateOptions = BitmapCreateOptions.IgnoreImageCache; bmi.UriSource = myUri; img.Source = bmi; // Show room location on map // Authorization of map services map.MapServiceToken = "QRJj0BZ57yT77gTeYfN-uw"; // Show current location // Source: https://msdn.microsoft.com/en-us/magazine/dn818495.aspx geolocator = new Geolocator(); geoposition = await geolocator.GetGeopositionAsync(); result = await MapLocationFinder.FindLocationsAsync(items[0].address, geoposition.Coordinate.Point, 1); map.Center = result.Locations[0].Point; map.ZoomLevel = 15; //Pin image MapIcon mapIcon = new MapIcon(); mapIcon.Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/MapPin.png")); mapIcon.NormalizedAnchorPoint = new Point(0.25, 0.9); mapIcon.Location = result.Locations[0].Point; mapIcon.Title = "Room is here"; map.MapElements.Add(mapIcon); } catch (Exception ex) { MessageDialog msgbox = new MessageDialog("Failed to acquire information: " + ex.Message); await msgbox.ShowAsync(); } } Ring.IsActive = false; // Get number from contact GlobalMethod global = new GlobalMethod(); callNumber = global.getNumber(items[0].contact); btnCall.Content = "Call " + callNumber; btnSMS.Content = "SMS " + callNumber; // Get the drive rout between two points // Source: https://msdn.microsoft.com/en-us/magazine/dn818495.aspx try { BasicGeoposition startLocation = new BasicGeoposition(); startLocation.Altitude = geoposition.Coordinate.Point.Position.Altitude; startLocation.Latitude = geoposition.Coordinate.Point.Position.Latitude; startLocation.Longitude = geoposition.Coordinate.Point.Position.Longitude; Geopoint startPoint = new Geopoint(startLocation); BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Altitude = result.Locations[0].Point.Position.Altitude; endLocation.Latitude = result.Locations[0].Point.Position.Latitude; endLocation.Longitude = result.Locations[0].Point.Position.Longitude; Geopoint endPoint = new Geopoint(endLocation); // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None, 290); // Display the route between two points if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Blue; viewOfRoute.OutlineColor = Colors.Blue; // Add the new MapRouteView to the Routes collection // of the MapControl. map.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await map.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); } // Display summary info about the route. // Source: https://msdn.microsoft.com/en-us/magazine/dn818495.aspx route.Inlines.Add(new Run() { Text = "Total estimated time (minutes) = " + routeResult.Route.EstimatedDuration.TotalMinutes.ToString("F1") }); route.Inlines.Add(new LineBreak()); route.Inlines.Add(new Run() { Text = "Total length (kilometers) = " + (routeResult.Route.LengthInMeters / 1000).ToString("F1") }); route.Inlines.Add(new LineBreak()); // Display the directions. route.Inlines.Add(new Run() { Text = "DIRECTIONS" }); route.Inlines.Add(new LineBreak()); route.Inlines.Add(new LineBreak()); // Loop through the legs and maneuvers. foreach (MapRouteLeg leg in routeResult.Route.Legs) { foreach (MapRouteManeuver maneuver in leg.Maneuvers) { route.Inlines.Add(new Run() { Text = maneuver.InstructionText }); route.Inlines.Add(new LineBreak()); } } } catch { await new MessageDialog("No route from your location to party location.").ShowAsync(); } }
/// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="sender"> /// The source of the event; typically <see cref="NavigationHelper"/>. /// </param> /// <param name="e">Event data that provides both the navigation parameter passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited.</param> private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) { // start at Grand Central Station BasicGeoposition startLocation = new BasicGeoposition(); startLocation.Latitude = 40.7517; startLocation.Longitude = -073.9766; Geopoint startPoint = new Geopoint(startLocation); // end at Central Park BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Latitude = 40.7669; endLocation.Longitude = -073.9790; Geopoint endPoint = new Geopoint(endLocation); // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetWalkingRouteAsync( startPoint, endPoint); if (routeResult.Status == MapRouteFinderStatus.Success) { // Display summary info about the route. tbTurnByTurn.Inlines.Add(new Run() { Text = resourceLoader.GetString("Summary") }); tbTurnByTurn.Inlines.Add(new LineBreak()); tbTurnByTurn.Inlines.Add(new LineBreak()); tbTurnByTurn.Inlines.Add(new Run() { Text = resourceLoader.GetString("TotalTime") + " = " + routeResult.Route.EstimatedDuration.TotalMinutes.ToString("F1") }); tbTurnByTurn.Inlines.Add(new LineBreak()); tbTurnByTurn.Inlines.Add(new Run() { Text = resourceLoader.GetString("TotalLength") + " = " + (routeResult.Route.LengthInMeters / 1000).ToString("F1") }); tbTurnByTurn.Inlines.Add(new LineBreak()); tbTurnByTurn.Inlines.Add(new LineBreak()); // Display the directions. tbTurnByTurn.Inlines.Add(new Run() { Text = resourceLoader.GetString("Directions") }); tbTurnByTurn.Inlines.Add(new LineBreak()); tbTurnByTurn.Inlines.Add(new LineBreak()); // loop through the legs and maneuvers foreach (MapRouteLeg leg in routeResult.Route.Legs) { foreach (MapRouteManeuver maneuver in leg.Maneuvers) { tbTurnByTurn.Inlines.Add(new Run() { Text = maneuver.InstructionText }); tbTurnByTurn.Inlines.Add(new LineBreak()); tbTurnByTurn.Inlines.Add(new LineBreak()); } } // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Blue; viewOfRoute.OutlineColor = Colors.Blue; // Add the new MapRouteView to the Routes collection // of the MapControl. MapwithDrivingRoute.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await MapwithDrivingRoute.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); } else { // Tell the user to try again. string message = this.resourceLoader.GetString("NoRoute"); string title = this.resourceLoader.GetString("NoRouteTitle"); MessageDialog messageDialog = new MessageDialog(message, title); await messageDialog.ShowAsync(); } }
private async void elementClick(MapControl sender, MapElementClickEventArgs args) { if (indicador == -1) { var dialog = new Windows.UI.Popups.MessageDialog("Indicaciones desde aqui"); dialog.Commands.Add(new Windows.UI.Popups.UICommand("Aceptar") { Id = 1 }); dialog.Commands.Add(new Windows.UI.Popups.UICommand("Cancelar") { Id = 0 }); var result = await dialog.ShowAsync(); if (result.Id.Equals(1)) { startLocation = new BasicGeoposition() { Latitude = args.Location.Position.Latitude, Longitude = args.Location.Position.Longitude }; indicador = 1; } } else { var dialog = new Windows.UI.Popups.MessageDialog("Indicaciones hasta aqui"); dialog.Commands.Add(new Windows.UI.Popups.UICommand("Aceptar") { Id = 1 }); dialog.Commands.Add(new Windows.UI.Popups.UICommand("Cancelar") { Id = 0 }); var result = await dialog.ShowAsync(); if (result.Id.Equals(1)) { endLocation = new BasicGeoposition() { Latitude = args.Location.Position.Latitude, Longitude = args.Location.Position.Longitude }; MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync(new Geopoint(startLocation), new Geopoint(endLocation), MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Yellow; viewOfRoute.OutlineColor = Colors.Black; map.Routes.Add(viewOfRoute); await map.TrySetViewBoundsAsync(routeResult.Route.BoundingBox, null, MapAnimationKind.None); } } indicador = -1; } }
async private void OnPositionChanged(Geolocator sender, PositionChangedEventArgs e) { if (!tracking) { point = e.Position.Coordinate.Point; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { icon.Location = point; }); await myMap.TrySetViewAsync(point); } else { currentPoint = e.Position.Coordinate.Point; await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { icon.Location = currentPoint; }); MapRouteFinderResult routeResult = await MapRouteFinder.GetWalkingRouteAsync(point, currentPoint); if (routeResult.Route == null) return; if (routeResult.Status == MapRouteFinderStatus.Success) { await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { //directionChanged MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Blue; viewOfRoute.OutlineColor = Colors.Blue; myMap.Routes.Add(viewOfRoute); }); Distance += routeResult.Route.LengthInMeters; point = currentPoint; await Dispatcher.RunAsync( CoreDispatcherPriority.High, () => { distanceBlock.Text = Distance.ToString() + "m"; }); //distanceBlock.Text = Distance.ToString() + "m"; } await myMap.TrySetViewAsync(currentPoint); } }
private async void ShowRouteOnMap2() { // Request permission to access location var accessStatus = await Geolocator.RequestAccessAsync(); switch (accessStatus) { case GeolocationAccessStatus.Allowed: // If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used. Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 100 }; // Carry out the operation Geoposition startPosition = await geolocator.GetGeopositionAsync().AsTask(); // End at the city of Seattle, Washington. BasicGeoposition endLocation = new BasicGeoposition() { Latitude = 51.050460, Longitude = 3.703510 }; BasicGeoposition gep = new BasicGeoposition(); gep.Latitude = startPosition.Coordinate.Latitude; gep.Longitude = startPosition.Coordinate.Longitude; Geopoint gp1 = new Geopoint(gep); Geopoint gp2 = new Geopoint(endLocation); // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( gp1, gp2, MapRouteOptimization.Time, MapRouteRestrictions.None); // Create a MapIcon. MapIcon mapIcon1 = new MapIcon(); mapIcon1.Location = gp1; mapIcon1.NormalizedAnchorPoint = new Point(0.5, 1.0); mapIcon1.Title = "Start Location"; mapIcon1.ZIndex = 0; // Add the MapIcon to the map. MyMap.MapElements.Add(mapIcon1); MapIcon mapIcon2 = new MapIcon(); mapIcon2.Location = gp2; mapIcon2.NormalizedAnchorPoint = new Point(0.5, 1.0); mapIcon2.Title = "Somewhere over the ............"; mapIcon1.ZIndex = 0; MyMap.MapElements.Add(mapIcon2); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Red; viewOfRoute.OutlineColor = Colors.Black; // Add the new MapRouteView to the Routes collection // of the MapControl. MyMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await MyMap.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); } break; case GeolocationAccessStatus.Denied: // break; } // Start at Microsoft in Redmond, Washington. BasicGeoposition startLocation = new BasicGeoposition() { Latitude = 51.030460, Longitude = 3.703510 }; }
private async void getZiekenhuizen()//route van huidige locatie naar dichtste ziekenhuis { MapService.ServiceToken = "qZO7GwUqKeWcjJiEOva1qA"; MyMap.MapElements.Clear(); Geoposition gp = await getLocation(); BasicGeoposition gpBasis = new BasicGeoposition(); gpBasis.Longitude = gp.Coordinate.Point.Position.Longitude; gpBasis.Latitude = gp.Coordinate.Point.Position.Latitude; Geopoint gpPoint = new Geopoint(gpBasis); string httpheader = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + gpBasis.Latitude + "," + gpBasis.Longitude + "&radius=30000&type=hospital&key=AIzaSyBVbK0OS14hDYy10rOAhX94BEOuV02HBXQ"; var client = new HttpClient(); var result = await client.GetStringAsync(httpheader); GooglePlacesResponse gpr = (GooglePlacesResponse)JsonConvert.DeserializeObject <GooglePlacesResponse>(result); int count = gpr.results.Length; BasicGeoposition plaats = new BasicGeoposition(); BasicGeoposition nearestHospital = new BasicGeoposition(); Geopoint nearestHospitalPoint; double dichtste = 30000; if (gpr.status == "OK") { for (int j = 0; j < count; j++) { string name = gpr.results[j].name; plaats.Latitude = gpr.results[j].geometry.location.lat; plaats.Longitude = gpr.results[j].geometry.location.lng; double afstand = Distance(gpBasis.Latitude, gpBasis.Longitude, plaats.Latitude, plaats.Longitude, 1); if (afstand < dichtste) { dichtste = afstand; nearestHospital.Longitude = plaats.Longitude; nearestHospital.Latitude = plaats.Latitude; } } nearestHospitalPoint = new Geopoint(nearestHospital); var resultaat = await MapLocationFinder.FindLocationsAtAsync(nearestHospitalPoint); eigenLocatie.Text = locatieTekst(resultaat); AddPushpin(nearestHospital.Latitude, nearestHospital.Longitude, "zh"); AddPushpin(gpBasis.Latitude, gpBasis.Longitude, "eigen"); routeResult = await MapRouteFinder.GetDrivingRouteAsync(nearestHospitalPoint, gpPoint); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Blue; viewOfRoute.OutlineColor = Colors.Blue; // Add the new MapRouteView to the Routes collection // of the MapControl. MyMap.Routes.Clear(); MyMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await MyMap.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); slider.Value = MyMap.ZoomLevel; } else { message("Je route kon niet berekend worden", "FOUTMELDING"); } } }
private async void ShowRouteOnMap() { HttpClient client = new HttpClient(); var coordinatJson = await client.GetStringAsync("http://dev.virtualearth.net/REST/v1/Locations?CountryRegion=Belgium&adminDistrict=&locality=" + ((Campus)Campusses.SelectedItem).City + "&postalCode=&addressLine=" + ((Campus)Campusses.SelectedItem).Street + ((Campus)Campusses.SelectedItem).HouseNumber + "&key=QJnnkMOv4orFAt7p4GK1~ikA6-gj9lszj5iNbmmhGUA~AihogMlA2PlLcNuwEBlmsXhaMUVihNwVB_ja3eWdfaNts9aEQTutaGi9q66wMGFW"); var Coordinats = JsonConvert.DeserializeObject <RootObjectLocation>(coordinatJson); double latitude = Coordinats.resourceSets[0].resources[0].geocodePoints[0].coordinates[0]; double longitude = Coordinats.resourceSets[0].resources[0].geocodePoints[0].coordinates[1]; // Request permission to access location var accessStatus = await Geolocator.RequestAccessAsync(); switch (accessStatus) { case GeolocationAccessStatus.Allowed: Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 100 }; Geoposition startPosition = await geolocator.GetGeopositionAsync().AsTask(); BasicGeoposition endLocation = new BasicGeoposition() { Latitude = latitude, Longitude = longitude }; BasicGeoposition gep = new BasicGeoposition(); gep.Latitude = startPosition.Coordinate.Latitude; gep.Longitude = startPosition.Coordinate.Longitude; Geopoint gp1 = new Geopoint(gep); Geopoint gp2 = new Geopoint(endLocation); // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( gp1, gp2, MapRouteOptimization.Time, MapRouteRestrictions.None); // Create a MapIcon. MapIcon mapIcon1 = new MapIcon(); mapIcon1.Location = gp1; mapIcon1.NormalizedAnchorPoint = new Point(0.5, 1.0); mapIcon1.Title = "Uw locatie"; mapIcon1.ZIndex = 0; // Add the MapIcon to the map. MyMap.MapElements.Add(mapIcon1); MapIcon mapIcon2 = new MapIcon(); mapIcon2.Location = gp2; mapIcon2.NormalizedAnchorPoint = new Point(0.5, 1.0); mapIcon2.Title = ((Campus)Campusses.SelectedItem).Name; mapIcon1.ZIndex = 0; MyMap.MapElements.Add(mapIcon2); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Red; viewOfRoute.OutlineColor = Colors.Red; // Add the new MapRouteView to the Routes collection // of the MapControl. if (MyMap.Routes.Count > 0) { MyMap.Routes.RemoveAt(0); } MyMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await MyMap.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); } break; case GeolocationAccessStatus.Denied: var dialog = new Windows.UI.Popups.MessageDialog("Gelieve uw locatie te delen. Dit kan u doen in de privacyinstellingen van uw toestel."); await dialog.ShowAsync(); break; } }
private async void GetRoute() { status.Log(LocalizableStrings.LOCATION_GETTING_ROUTE); try { Geolocator locator = new Geolocator(); locator.DesiredAccuracy = PositionAccuracy.High; GeolocationAccessStatus locationAccess = await Geolocator.RequestAccessAsync(); if (locationAccess != GeolocationAccessStatus.Allowed) { status.Log(LocalizableStrings.LOCATION_NOT_ALLOWED); return; } Geoposition currentPosition = await locator.GetGeopositionAsync(); if (currentPosition == null) { status.Log(LocalizableStrings.LOCATION_CANNOT_GET_CURRENT_POSITION); return; } MapLocationFinderResult targetPosition = await MapLocationFinder.FindLocationsAsync(targetText.Text, null); if (targetPosition == null || targetPosition.Locations[0] == null) { status.Log(LocalizableStrings.LOCATION_CANNOT_GET_TARGET_POSITION); return; } Geopoint start = currentPosition.Coordinate.Point; Geopoint end = targetPosition.Locations[0].Point; MapRouteFinderResult route = await MapRouteFinder.GetDrivingRouteAsync(start, end); if (route != null) { if (route.Status != MapRouteFinderStatus.Success) { status.Log(string.Format(CultureInfo.CurrentCulture, LocalizableStrings.LOCATION_ROUTE_ERROR, route.Status.ToString())); return; } MapRouteView routeView = new MapRouteView(route.Route); map.Routes.Add(routeView); List <string> list = new List <string>(); foreach (MapRouteLeg leg in route.Route.Legs) { for (int i = 0; i < leg.Maneuvers.Count; i++) { MapRouteManeuver maneuver = leg.Maneuvers[i]; list.Add(string.Format("{0}. {1}", i + 1, maneuver.InstructionText)); } } routeList.ItemsSource = list; status.Log(LocalizableStrings.LOCATION_FOUND_ROUTE); } } catch (Exception ex) { status.Log(ex.Message); } }
/// <summary> /// The methods provided in this section are simply used to allow /// NavigationHelper to respond to the page's navigation methods. /// <para> /// Page specific logic should be placed in event handlers for the /// <see cref="NavigationHelper.LoadState"/> /// and <see cref="NavigationHelper.SaveState"/>. /// The navigation parameter is available in the LoadState method /// in addition to page state preserved during an earlier session. /// </para> /// </summary> /// <param name="e">Provides data for navigation methods and event /// handlers that cannot cancel the navigation request.</param> protected async override void OnNavigatedTo(NavigationEventArgs e) {//MapManager.ShowDownloadedMapsUI(); for download map //the map token from the devoloper account MyMap.MapServiceToken = "_y9lVdW-3ewMrx0C6bGnZQ"; //Geolocator initialization locator = new Geolocator(); locator.DesiredAccuracy = PositionAccuracy.High; locator.MovementThreshold = 20; Geoposition position = null; try{ position = await locator.GetGeopositionAsync(); } catch {} //await MyMap.TrySetViewAsync(position.Coordinate.Point, 18D); //centering the map to the current position MyMap.Center = position.Coordinate.Point; MyMap.ZoomLevel = 15; //adding icon to the current position MapIcon mapIcon = new MapIcon(); mapIcon.Image = RandomAccessStreamReference.CreateFromUri( new Uri("ms-appx:///Assets/inside_project_img/map_pin.png")); mapIcon.NormalizedAnchorPoint = new Point(0.5, 1); mapIcon.Location = position.Coordinate.Point; mapIcon.Title = "You are here"; MyMap.MapElements.Add(mapIcon); //adding icon to the distination BasicGeoposition destinationPosition = new BasicGeoposition(); destinationPosition.Longitude = Convert.ToDouble(MainPage.DestinationLongitude); destinationPosition.Latitude = Convert.ToDouble(MainPage.DestinationLatitude); MapIcon mapIcon1 = new MapIcon(); mapIcon1.Image = RandomAccessStreamReference.CreateFromUri( new Uri("ms-appx:///Assets/inside_project_img/map_pin.png")); mapIcon1.NormalizedAnchorPoint = new Point(0.5, 1); mapIcon1.Location = new Geopoint(destinationPosition); mapIcon.Title = "You are here"; MyMap.MapElements.Add(mapIcon1); //adding a circle to the current position Windows.UI.Xaml.Shapes.Ellipse fence = new Windows.UI.Xaml.Shapes.Ellipse(); fence.Width = 100; fence.Height = 100; fence.Fill = new SolidColorBrush(Colors.Blue); fence.Stroke = new SolidColorBrush(Colors.Blue); fence.Opacity = 0.3; fence.StrokeThickness = 2; MapControl.SetLocation(fence, position.Coordinate.Point); MapControl.SetNormalizedAnchorPoint(fence, new Point(0.5, 0.5)); MyMap.Children.Add(fence); // This part is for the route . BasicGeoposition startLocation = new BasicGeoposition(); startLocation.Latitude = position.Coordinate.Latitude; startLocation.Longitude = position.Coordinate.Longitude; Geopoint startPoint = new Geopoint(startLocation); // End at Central Park. BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Latitude = Convert.ToDouble(MainPage.DestinationLatitude); endLocation.Longitude = Convert.ToDouble(MainPage.DestinationLongitude); Geopoint endPoint = new Geopoint(endLocation); // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync(startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Blue; viewOfRoute.OutlineColor = Colors.Blue; // Add the new MapRouteView to the Routes collection // of the MapControl. MyMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await MyMap.TrySetViewBoundsAsync(routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); } //locator.PositionChanged += locator_PositionChanged; // locator.StatusChanged += locator_StatusChanged; // this.navigationHelper.OnNavigatedTo(e); //after finding the route we disable the progress ring progress.Opacity = 0; appBar.IsEnabled = true; subtitle.Text = "Follow the road"; progress.Opacity = 0; MyMap.Opacity = 1; }
private async void searchtext_KeyDown(object sender, KeyRoutedEventArgs e) { if (e.Key == Windows.System.VirtualKey.Enter ) { if (searchtext.Text.Length > 0) { searchtext.Visibility = Visibility.Collapsed; RouteDetails.Text = ""; //MyMap.Children.Clear(); // Start, Begin in My Current Position Geopoint startPoint = new Geopoint(MyPosition); MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync(searchtext.Text, startPoint, 3); if (result.Status == MapLocationFinderStatus.Success) { // End, Ended in My find position FinalPosition.Latitude = result.Locations[0].Point.Position.Latitude; FinalPosition.Longitude = result.Locations[0].Point.Position.Longitude; Geopoint endPoint = new Geopoint(FinalPosition); MapControl.SetLocation(DrawMarker(PushPinGeneric), endPoint); MapControl.SetNormalizedAnchorPoint(DrawMarker(PushPinGeneric), new Point(0.5, 0.5)); if (FindOrRoute.Equals("Find")) { // Show Find await MyMap.TrySetViewAsync(endPoint, 15, 0, 0, MapAnimationKind.Bow); } else { //Show Route MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( startPoint,endPoint,MapRouteOptimization.Time,MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { // Display summary RouteDetails.Inlines.Add(new LineBreak()); RouteDetails.Inlines.Add(new Run() { Text = searchtext.Text.ToUpper() }); RouteDetails.Inlines.Add(new LineBreak()); string hours = ""; if (routeResult.Route.EstimatedDuration.TotalHours > 1) { hours = routeResult.Route.EstimatedDuration.TotalHours.ToString() + " hrs,"; } RouteDetails.Inlines.Add(new Run() { Text = (routeResult.Route.LengthInMeters / 1000).ToString() + " km," + hours + routeResult.Route.EstimatedDuration.TotalMinutes.ToString() + " mins." }); RouteDetails.Inlines.Add(new LineBreak()); RouteDetails.Inlines.Add(new LineBreak()); // Display the directions. RouteDetails.Inlines.Add(new Run() { Text = "DIRECTIONS" }); RouteDetails.Inlines.Add(new LineBreak()); foreach (MapRouteLeg leg in routeResult.Route.Legs) { foreach (MapRouteManeuver maneuver in leg.Maneuvers) { RouteDetails.Inlines.Add(new Run() { Text = maneuver.InstructionText }); RouteDetails.Inlines.Add(new LineBreak()); } } MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Red; viewOfRoute.OutlineColor = Colors.Black; MyMap.Routes.Add(viewOfRoute); await MyMap.TrySetViewBoundsAsync(routeResult.Route.BoundingBox, null, MapAnimationKind.Linear); } else { RouteDetails.Text = "A problem occurred: " + routeResult.Status.ToString(); } } } } else { MessageBox("Please insert your place to find", "Information"); } } }
async protected override void OnNavigatedTo(NavigationEventArgs e) { if (DaneGeograficzne.pktStartowy.Latitude != 0 && DaneGeograficzne.pktDocelowy.Longitude != 0) { Point anchor = new Point(); anchor.X = 0.5; anchor.Y = 1.0; Geopoint pktStartowy = new Geopoint(DaneGeograficzne.pktStartowy); Geopoint pktDocelowy = new Geopoint(DaneGeograficzne.pktDocelowy); MapIcon znacznikStart = new MapIcon(); znacznikStart.NormalizedAnchorPoint = anchor; znacznikStart.Location = pktStartowy; znacznikStart.Title = "Tu jestem"; MapIcon znacznikDocelowa = new MapIcon(); znacznikDocelowa.NormalizedAnchorPoint = anchor; znacznikDocelowa.Location = pktDocelowy; znacznikDocelowa.Title = "Koniec!"; MapPolyline trasaLotem = new MapPolyline(); trasaLotem.StrokeColor = Windows.UI.Colors.Black; trasaLotem.StrokeThickness = 3; trasaLotem.StrokeDashed = true; var Path = new Geopath(new List <BasicGeoposition> { DaneGeograficzne.pktStartowy, DaneGeograficzne.pktDocelowy }); trasaLotem.Path = Path; GeoCoordinate pin1 = new GeoCoordinate(DaneGeograficzne.pktStartowy.Latitude, DaneGeograficzne.pktStartowy.Longitude); GeoCoordinate pin2 = new GeoCoordinate(DaneGeograficzne.pktDocelowy.Latitude, DaneGeograficzne.pktDocelowy.Longitude); double distanceBetween = pin1.GetDistanceTo(pin2) / 1000; BasicGeoposition srodekTrasaLotem = new BasicGeoposition(); srodekTrasaLotem.Latitude = (DaneGeograficzne.pktStartLatitude + DaneGeograficzne.pktKoniecLatitude) / 2; srodekTrasaLotem.Longitude = (DaneGeograficzne.pktStartLongitude + DaneGeograficzne.pktKoniecLongitude) / 2; MapIcon znacznikDystans = new MapIcon(); znacznikDystans.Location = new Geopoint(srodekTrasaLotem); znacznikDystans.Title = string.Format("{0} km", Math.Round(distanceBetween, 2)); mojaMapa.MapElements.Add(znacznikStart); mojaMapa.MapElements.Add(znacznikDocelowa); mojaMapa.MapElements.Add(trasaLotem); mojaMapa.MapElements.Add(znacznikDystans); mojaMapa.Center = pktStartowy; await mojaMapa.TrySetViewAsync(new Geopoint(DaneGeograficzne.pktStartowy), 8); MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( new Geopoint(DaneGeograficzne.pktStartowy), new Geopoint(DaneGeograficzne.pktDocelowy), MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { System.Text.StringBuilder routeInfo = new System.Text.StringBuilder(); double estTime = Math.Round(routeResult.Route.EstimatedDuration.TotalMinutes, 2); routeInfo.Append("Dojazd samochodem:\n\t"); routeInfo.Append("Oszacowany czas dojazdu samochodem (min) = "); routeInfo.Append(estTime.ToString()); routeInfo.Append("\n\tDługość trasy (km) = "); routeInfo.Append((routeResult.Route.LengthInMeters / 1000).ToString()); // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); tbLegendaDlugosc.Text = routeInfo.ToString(); viewOfRoute.RouteColor = Colors.Yellow; viewOfRoute.OutlineColor = Colors.Black; // Add the new MapRouteView to the Routes collection // of the MapControl. mojaMapa.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await mojaMapa.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); } } else { //CoreApplication.Exit(); } }
private async void Button_Click_4(object sender, RoutedEventArgs e) { // Start at Microsoft in Redmond, Washington. BasicGeoposition startLocation = new BasicGeoposition() { Latitude = 47.643, Longitude = -122.131 }; // End at the city of Seattle, Washington. BasicGeoposition endLocation = new BasicGeoposition() { Latitude = 47.604, Longitude = -122.329 }; MapRouteFinderResult result = await MapRouteFinder.GetDrivingRouteAsync(new Geopoint(startLocation), new Geopoint(endLocation)); if(result.Status == MapRouteFinderStatus.Success) { MapRouteView mapRouteVIew = new MapRouteView(result.Route); mapRouteVIew.RouteColor = Colors.Red; MapControl1.Routes.Add(mapRouteVIew); StringBuilder sb = new StringBuilder(); foreach (var legs in result.Route.Legs) { foreach (var m in legs.Maneuvers) { sb.AppendLine(m.InstructionText); } } var msgDialog = new MessageDialog(sb.ToString()); await msgDialog.ShowAsync(); } }
private async void click_CalcularRuta(object sender, RoutedEventArgs e) { if (text_Origen.Text != "" && text_Destino.Text != "") { try { // Obtenemos la dirección inicial mediante Geocode Geopoint startLocation = await geocodeDireccion(text_Origen.Text); // Obtenemos la dirección destino mediante Geocode Geopoint endLocation = await geocodeDireccion(text_Destino.Text); MapRouteFinderResult routeResult = null; if (toggle_Desplazamiento.IsOn == true) { // Para conseguir la ruta entre 2 destinos especificados Coche routeResult = await MapRouteFinder.GetDrivingRouteAsync( startLocation, endLocation, MapRouteOptimization.Time, MapRouteRestrictions.None); } else { // Para conseguir la ruta entre 2 destinos especificados Andando. Suele Fallar routeResult = await MapRouteFinder.GetWalkingRouteAsync( startLocation, endLocation); } if (routeResult.Status == MapRouteFinderStatus.Success) { System.Text.StringBuilder routeInfo = new System.Text.StringBuilder(); // Se muestra la información obtenida de la ruta string tiempo = string.Format("{0} horas {1} min", routeResult.Route.EstimatedDuration.Hours, routeResult.Route.EstimatedDuration.Minutes); routeInfo.Append("\nTiempo en minutos = " + tiempo); routeInfo.Append("\nTotal Km = " + (routeResult.Route.LengthInMeters / 1000).ToString()); // Se muestra las direcciones de la ruta routeInfo.Append("\n\nDIRECCIONES\n"); foreach (MapRouteLeg leg in routeResult.Route.Legs) { foreach (MapRouteManeuver maneuver in leg.Maneuvers) { routeInfo.AppendLine(maneuver.InstructionText); Debug.WriteLine(maneuver.InstructionText); } } // Mostramos la información de la ruta en el Texto asignado para ver las indicaciones de la ruta TextIndicacionesRuta.Text = routeInfo.ToString(); // Usamos la ruta para inicializar MapRouteView MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = colors[ColorsCombo.SelectedIndex]; viewOfRoute.OutlineColor = Colors.Red; // Añadimos el nuevo MapRouteView a las rutas del Mapa if (MapControl.Routes.Count > 0)//Si ya hay mostrada una ruta, la limpio (ejemplo: misma ruta con distinto color) { MapControl.Routes.Clear(); } MapControl.Routes.Add(viewOfRoute); // Mostramos la ruta en el Mapa await MapControl.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); //Coloco los POIs de Inicio y Destino ColocarPOIs(endLocation, "Destino", true); ColocarPOIs(startLocation, "Inicio", true); } else { TextIndicacionesRuta.Text = "A ocurrido un problema al cargar el mapa: " + routeResult.Status.ToString(); } } catch { TextIndicacionesRuta.Text = "Error obteniendo una de las posiciones especificadas (DIRECCIÓN NO ENCONTRADA)"; Debug.WriteLine("Error haciendo obteniendo la posición de una dirección mediante Geocode (DIRECCIÓN NO ENCONTRADA) "); } } else { ContentDialog noWifiDialog = new ContentDialog { Title = "No has rellenado todos los campos", Content = "Rellena los campos Origen y Destino para poder calcular una ruta.", CloseButtonText = "Ok" }; ContentDialogResult result = await noWifiDialog.ShowAsync(); } }
private async void GetRouteAndDirections(Geopoint startPoint, Geopoint endPoint, Color color) { // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None); //Check if making the route is completed if (routeResult.Status == MapRouteFinderStatus.Success) { Summary.Text = ""; Summary.Inlines.Add(new Run() { Text = "Total time: " + routeResult.Route.EstimatedDuration.TotalMinutes.ToString() + " min" }); Summary.Inlines.Add(new LineBreak()); Summary.Inlines.Add(new Run() { Text = "Total length: " + (routeResult.Route.LengthInMeters / 1000).ToString() + " km" }); } else { Summary.Text = "Er is een probleem opgetreden: " + routeResult.Status.ToString(); } //Draw the route on the map if (routeResult.Status == MapRouteFinderStatus.Success) { MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = color; viewOfRoute.OutlineColor = Colors.Black; InputMap.Routes.Add(viewOfRoute); await InputMap.TrySetViewBoundsAsync(routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); } }
private async void mostrarRutaEnMapa(double latIni, double longIni, double latFin, double longFin, Color color) { BasicGeoposition startLocation = new BasicGeoposition() { Latitude = latIni, Longitude = longIni }; BasicGeoposition endLocation = new BasicGeoposition() { Latitude = latFin, Longitude = longFin }; MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( new Geopoint(startLocation), new Geopoint(endLocation), MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = color;// Colors.Orange; viewOfRoute.OutlineColor = Colors.Black; mcMapa.Routes.Add(viewOfRoute); await mcMapa.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); BasicGeoposition cityPosition = new BasicGeoposition() { Latitude = latIni, Longitude = longIni }; Geopoint cityCenter = new Geopoint(cityPosition); Windows.UI.Core.DispatchedHandler Lectura_PosicionIni = () => { MapIcon myPOI = new MapIcon { Location = cityCenter, NormalizedAnchorPoint = new Point(0.5, 1.0), Title = txtOrigen.Text, ZIndex = 0, Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/ubicacion-start.png")) }; mcMapa.MapElements.Add(myPOI); }; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Lectura_PosicionIni); BasicGeoposition cityPositionEnd = new BasicGeoposition() { Latitude = latFin, Longitude = longFin }; Geopoint cityCenterEnd = new Geopoint(cityPositionEnd); Windows.UI.Core.DispatchedHandler Lectura_PosicionEnd = () => { MapIcon myPOI = new MapIcon { Location = cityCenterEnd, NormalizedAnchorPoint = new Point(0.5, 1.0), Title = txtDestino.Text, ZIndex = 0, Image = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/ubicacion-end.png")) }; mcMapa.MapElements.Add(myPOI); }; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, Lectura_PosicionEnd); } }
async void DrawRouteBetweenMeAndSpecificPoint(double _lat, double _long) { try { ClearMap(); BasicGeoposition startLocation = new BasicGeoposition(); startLocation.Latitude = MyPositionLatitude; startLocation.Longitude = MyPositionLongitude; Geopoint startPoint = new Geopoint(startLocation); BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Latitude = _lat; endLocation.Longitude = _long; Geopoint endPoint = new Geopoint(endLocation); string from = MyPositionLatitude.ToString() + "," + MyPositionLongitude.ToString(); string to = _lat.ToString() + "," + _long.ToString(); if (!string.IsNullOrWhiteSpace(from)) { if (!string.IsNullOrWhiteSpace(to)) { // Get a route as shown previously. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None); MapIcon MeAsMapIcon = new Windows.UI.Xaml.Controls.Maps.MapIcon(); MeAsMapIcon.Location = new Geopoint(new BasicGeoposition() { Latitude = MyPositionLatitude, Longitude = MyPositionLongitude }); MeAsMapIcon.NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0); MeAsMapIcon.Title = "أنا"; MyMap.MapElements.Add(MeAsMapIcon); MapIcon thereAsMapIcon = new Windows.UI.Xaml.Controls.Maps.MapIcon(); thereAsMapIcon.Location = new Geopoint(new BasicGeoposition() { Latitude = _lat, Longitude = _long }); thereAsMapIcon.NormalizedAnchorPoint = new Windows.Foundation.Point(0.5, 1.0); thereAsMapIcon.Title = "المكان التانى"; MyMap.MapElements.Add(thereAsMapIcon); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.DarkBlue; viewOfRoute.OutlineColor = Colors.White; // Add the new MapRouteView to the Routes collection // of the MapControl. MyMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await MyMap.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); } } else { ShowMessage("Invalid 'To' location."); } } else { ShowMessage("Invalid 'From' location."); } } catch { } }
private async void ucitajMapu() { await getLocationByGeolocatorAsync(); Lat1 = startPosition.Coordinate.Point.Position.Latitude; Long1 = startPosition.Coordinate.Point.Position.Longitude; //Lat1 = SearchRestaurants.position.Coordinate.Point.Position.Latitude; //Long1 = SearchRestaurants.position.Coordinate.Point.Position.Longitude; Long2 = SearchRestaurants.novaLokacija.Item2; Lat2 = SearchRestaurants.novaLokacija.Item1; BasicGeoposition startLocation = new BasicGeoposition() { Latitude = Lat1, Longitude = Long1 }; BasicGeoposition endLocation = new BasicGeoposition() { Latitude = Lat2, Longitude = Long2 }; // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( new Geopoint(startLocation), new Geopoint(endLocation), MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Yellow; viewOfRoute.OutlineColor = Colors.Black; // Add the new MapRouteView to the Routes collection // of the MapControl. myMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await myMap.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); System.Text.StringBuilder routeInfo = new System.Text.StringBuilder(); // Display summary info about the route. routeInfo.Append("Total estimated time (minutes) = "); double time = Math.Round(routeResult.Route.EstimatedDuration.TotalMinutes, 1); routeInfo.Append(time.ToString()); routeInfo.Append("\nTotal length (meters) = "); routeInfo.Append((Math.Round(routeResult.Route.LengthInMeters, 0)).ToString()); // Display the directions. routeInfo.Append("\n\nDIRECTIONS\n\n"); foreach (MapRouteLeg leg in routeResult.Route.Legs) { foreach (MapRouteManeuver maneuver in leg.Maneuvers) { routeInfo.AppendLine(maneuver.InstructionText); } } // Load the text box. tbOutputText.Text = routeInfo.ToString(); } else { tbOutputText.Text = "A problem occurred: " + routeResult.Status.ToString(); } }
private async void findShortestRoute(Geopoint wayPoints1, Geopoint wayPoints2) { var routeResult = await MapRouteFinder.GetDrivingRouteAsync(wayPoints1, wayPoints2); if (routeResult.Status == MapRouteFinderStatus.Success) { MyMap.MapElements.Clear(); // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Yellow; viewOfRoute.OutlineColor = Colors.Black; // Add the new MapRouteView to the Routes collection // of the MapControl. MyMap.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await MyMap.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); } else { MessageDialogHelper.Show("Không tìm thấy đường", "Lỗi"); } }
private async void btnFindParkingspace_Click(object sender, RoutedEventArgs e) { MapService.ServiceToken = "PP-GfLf36HgHjM8ZVPl2GA"; mapWithMyLocation.MapElements.Clear(); Geoposition startPosition = await getLocation(); if (parkingspace != null) { Geoposition endPosition = parkingspace; MapIcon mapIconPark2 = new MapIcon(); mapIconPark2.NormalizedAnchorPoint = new Point(0.25, 0.9); mapIconPark2.Location = endPosition.Coordinate.Point; mapIconPark2.Title = "Parkingspace"; mapWithMyLocation.MapElements.Add(mapIconPark2); } else { var messageDialog = new MessageDialog("No parkingspace saved."); await messageDialog.ShowAsync(); } BasicGeoposition startLocation = new BasicGeoposition(); startLocation.Latitude = startPosition.Coordinate.Point.Position.Latitude; startLocation.Longitude = startPosition.Coordinate.Point.Position.Longitude; Geopoint startPoint = new Geopoint(startLocation); BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Latitude = parkingspace.Coordinate.Point.Position.Latitude; endLocation.Longitude = parkingspace.Coordinate.Point.Position.Longitude; Geopoint endPoint = new Geopoint(endLocation); mapWithMyLocation.Center = startPosition.Coordinate.Point; MapIcon mapIconStart = new MapIcon(); mapIconStart.NormalizedAnchorPoint = new Point(0.25, 0.9); mapIconStart.Location = startPosition.Coordinate.Point; mapIconStart.Title = "You are here"; mapWithMyLocation.MapElements.Add(mapIconStart); mapWithMyLocation.ZoomLevel = 12; MapRouteFinderResult routeResult = await MapRouteFinder.GetWalkingRouteAsync(startPoint, endPoint); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Blue; viewOfRoute.OutlineColor = Colors.Blue; // Add the new MapRouteView to the Routes collection // of the MapControl. mapWithMyLocation.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await mapWithMyLocation.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); } }
private async void GetRouteAndDirections(object sender, TappedRoutedEventArgs e) { if (tbx1.Text == "" || tbx2.Text == "") { MessageDialog md1 = new MessageDialog("Please Enter Source and Destination!"); await md1.ShowAsync(); } var startAddressToGeocode = tbx1.Text; var endAddressToGeocode = tbx2.Text; var startLocationString = startAddressToGeocode; var endLocationString = endAddressToGeocode; // List<string> startResults = new List<string>(); startResults.Add(startLocationString); rs.Add("Blue"); colors.Add("Green"); var startResults = await MapLocationFinder.FindLocationsAsync(startLocationString, null); var endResults = await MapLocationFinder.FindLocationsAsync(endLocationString, null); var lat = 0.0; //= 28.6; var lon = 0.0; // 77.209; var endlat = 0.0; //= 28.6; var endlon = 0.0; // 77.209; if (startResults.Status == MapLocationFinderStatus.Success) { try { lat = startResults.Locations[0].Point.Position.Latitude; lon = startResults.Locations[0].Point.Position.Longitude; } catch { MessageDialog md = new MessageDialog("Please Enter a Valid Source"); await md.ShowAsync(); } } BasicGeoposition startLocation = new BasicGeoposition(); startLocation.Latitude = lat; startLocation.Longitude = lon; // Geopoint hintPoint = new Geopoint(startLocation); // Geopoint pt = new Geopoint() MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync(startAddressToGeocode, null); Geopoint startPoint = new Geopoint(startLocation); /* //check * * BasicGeoposition queryHint = new BasicGeoposition(); * queryHint.Latitude = 47.643; * queryHint.Longitude = -122.131; * Geopoint hintPoint = new Geopoint(queryHint); * * MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync(addressToGeoCode, hintPoint, 3); */ if (endResults.Status == MapLocationFinderStatus.Success) { try { endlat = endResults.Locations[0].Point.Position.Latitude; endlon = endResults.Locations[0].Point.Position.Longitude; } catch { MessageDialog md = new MessageDialog("Please Enter a Valid Destination"); await md.ShowAsync(); } } BasicGeoposition endLocation = new BasicGeoposition(); endLocation.Latitude = endlat; endLocation.Longitude = endlon; Geopoint endHintPoint = new Geopoint(endLocation); MapLocationFinderResult endResult = await MapLocationFinder.FindLocationsAsync(endAddressToGeocode, null); Geopoint endPoint = new Geopoint(endLocation); /* // End at the city of Seattle, Washington. * BasicGeoposition endLocation = new BasicGeoposition(); * endLocation.Latitude = 28.6139; * endLocation.Longitude = 70.2090; * Geopoint endPoint = new Geopoint(endLocation); */ // Get the route between the points. MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( startPoint, endPoint, MapRouteOptimization.Time, MapRouteRestrictions.None); if (routeResult.Status == MapRouteFinderStatus.Success) { // Display summary info about the route. distance = (routeResult.Route.LengthInMeters / 1000).ToString(); tbOutputText.Inlines.Add(new Run() { Text = "Total estimated time (minutes) = " + routeResult.Route.EstimatedDuration.TotalMinutes.ToString() }); tbOutputText.Inlines.Add(new LineBreak()); tbOutputText.Inlines.Add(new Run() { Text = "Total length (kilometers) = " + (routeResult.Route.LengthInMeters / 1000).ToString() }); tbOutputText.Inlines.Add(new LineBreak()); tbOutputText.Inlines.Add(new LineBreak()); // Display the directions. tbOutputText.Inlines.Add(new Run() { Text = "DIRECTIONS" }); tbOutputText.Inlines.Add(new LineBreak()); foreach (MapRouteLeg leg in routeResult.Route.Legs) { foreach (MapRouteManeuver maneuver in leg.Maneuvers) { tbOutputText.Inlines.Add(new Run() { Text = maneuver.InstructionText }); tbOutputText.Inlines.Add(new LineBreak()); } } } else { tbOutputText.Text = "Please Give Proper Source and Destination: " + routeResult.Status.ToString(); } if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Yellow; viewOfRoute.OutlineColor = Colors.Black; // Add the new MapRouteView to the Routes collection // of the MapControl. Display.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await Display.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); } }
private async void ShowRouteOnMap(List<Geopoint> listGeopoint,Color color) { if (listGeopoint.Count > 1) { MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteFromWaypointsAsync(listGeopoint); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = color; viewOfRoute.OutlineColor =Colors.Black; // Add the new MapRouteView to the Routes collection // of the MapControl. mapControl.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await mapControl.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, MapAnimationKind.None); } } }
public async void mapItem_Party(object param) { if ((App.Current as App).UserLocation != null) { //Locatie uit gekozen feestje halen. Party item = param as Party; //Tijdelijke locatie aanmaken try { BasicGeoposition tempbasic = new BasicGeoposition(); //Feestlocatie opsplitsen (word opgeslagen als string) Location location = (Location)item.Location; //Locaties omzetten en in de tijdelijke posities opslaan. tempbasic.Latitude = location.Latitude; tempbasic.Longitude = location.Longitude; //Om de route aan te vragen, heb je een start en een eindpunt nodig. Die moeten er zo uit zien: "waypoint.1=47.610,-122.107". //We gaan deze zelf aanmaken. /*string startstring = "http://dev.virtualearth.net/REST/v1/Routes?wayPoint.1=";//Eerste deel van de url startstring += (App.Current as App).UserLocation.Coordinate.Point.Position.Latitude.ToString() + "," + (App.Current as App).UserLocation.Coordinate.Point.Position.Longitude.ToString(); startstring += "&waypoint.2=";//Start van het eindpunt startstring += tempbasic.Latitude.ToString() + "," + tempbasic.Longitude.ToString();//Endpoint startstring += URL.URLBINGKEY + URL.BINGKEY;*/ Geopoint startpunt; //Start en eindpunt ophalen en klaarzetten voor onderstaande vraag if (VindRitFilterVM.SelectedDestination != null) { BasicGeoposition tempDest = new BasicGeoposition(); tempDest.Latitude = ((Location)VindRitFilterVM.SelectedDestination.Location).Latitude; tempDest.Longitude = ((Location)VindRitFilterVM.SelectedDestination.Location).Longitude; startpunt = new Geopoint(tempDest); } else { startpunt = (App.Current as App).UserLocation.Coordinate.Point; } Geopoint eindpunt = new Geopoint(tempbasic); //De route tussen 2 punten opvragen MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync(startpunt, eindpunt); if (routeResult.Status == MapRouteFinderStatus.Success)//Het is gelukt, we hebben een antwoord gekregen. { MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Color.FromArgb(255, 62, 94, 148); if (item.RouteCommandText == "Toon route") { this.Map.Routes.Clear(); } var items = this.Map.Routes; if (items.Count() > 0) { item.RouteCommandText = "Toon route"; this.Map.Routes.Clear(); } else { item.RouteCommandText = "Clear route"; this.Map.Routes.Add(viewOfRoute); } //MapRouteView toevoegen aan de Route Collectie //Fit de mapcontrol op de route await this.Map.TrySetViewBoundsAsync(routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.Bow); } } catch (Exception ex) { } } UpdateMapOfType(typeof(List<Party>)); }
private async void getJson(object sender, RoutedEventArgs e) { this.textError.Text = ""; MapService.ServiceToken = "An6jjlTc8XcKjbHJlVFiKlA6hAjJ9fjpehAR73y9pVtW9ldcu06EyU70hqcBa_rZ"; if (this.Mapa.Routes.Count > 0) { this.Mapa.Routes.Clear(); } var httpClient = new HttpClient(); String origen = this.origen.Text; String destino = this.destino.Text; Uri uri = new Uri("http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0=" + origen + "&wp.1=" + destino + "&avoid=minimizeTolls&output=json&key=An6jjlTc8XcKjbHJlVFiKlA6hAjJ9fjpehAR73y9pVtW9ldcu06EyU70hqcBa_rZ"); String jsonString = await httpClient.GetStringAsync(uri); Debug.WriteLine(jsonString); JsonValue jsonValue = JsonValue.Parse(jsonString); List <double> lat = new List <double>(); List <double> lon = new List <double>(); JsonArray itineraryItems = jsonValue.GetObject().GetNamedArray("resourceSets").GetObjectAt(0).GetNamedArray("resources").GetObjectAt(0).GetNamedArray("routeLegs").GetObjectAt(0).GetNamedArray("itineraryItems"); foreach (JsonValue jv in itineraryItems) { lat.Add(jv.GetObject().GetNamedObject("maneuverPoint").GetNamedArray("coordinates").GetNumberAt(0)); lon.Add(jv.GetObject().GetNamedObject("maneuverPoint").GetNamedArray("coordinates").GetNumberAt(1)); } double[] latArray = lat.ToArray(); double[] lonArray = lon.ToArray(); List <Geopoint> wayPoints = new List <Geopoint>(); for (int i = 0; i < latArray.Length; i++) { Debug.WriteLine(latArray[i].ToString() + ", " + lonArray[i].ToString()); wayPoints.Add(new Geopoint(new BasicGeoposition { Latitude = latArray[i], Longitude = lonArray[i] })); } MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteFromWaypointsAsync(wayPoints); if (routeResult.Status == MapRouteFinderStatus.Success) { // Use the route to initialize a MapRouteView. MapRouteView viewOfRoute = new MapRouteView(routeResult.Route); viewOfRoute.RouteColor = Colors.Red; viewOfRoute.OutlineColor = Colors.Blue; // Add the new MapRouteView to the Routes collection // of the MapControl. this.Mapa.Routes.Add(viewOfRoute); // Fit the MapControl to the route. await this.Mapa.TrySetViewBoundsAsync( routeResult.Route.BoundingBox, null, Windows.UI.Xaml.Controls.Maps.MapAnimationKind.None); } else { this.textError.Text = "No se ha encontrado la ruta"; } }