Ejemplo n.º 1
0
        static Task OpenPlacemark(MKPlacemark placemark, MapsLaunchOptions options)
        {
            var mapItem = new MKMapItem(placemark)
            {
                Name = options.Name ?? string.Empty
            };

            var mode = MKDirectionsMode.Default;

            switch (options.MapDirectionsMode)
            {
            case MapDirectionsMode.Driving:
                mode = MKDirectionsMode.Driving;
                break;

            case MapDirectionsMode.Transit:
                mode = MKDirectionsMode.Transit;
                break;

            case MapDirectionsMode.Walking:
                mode = MKDirectionsMode.Walking;
                break;
            }

            var launchOptions = new MKLaunchOptions
            {
                DirectionsMode = mode
            };

            var mapItems = new[] { mapItem };

            MKMapItem.OpenMaps(mapItems, launchOptions);
            return(Task.CompletedTask);
        }
        void CalculateRoute(object sender, EventArgs e)
        {
            CLLocationCoordinate2D sourceLocation      = new CLLocationCoordinate2D(CustomMapView.RouteSource.Latitude, CustomMapView.RouteSource.Longitude);
            CLLocationCoordinate2D destinationLocation = new CLLocationCoordinate2D(CustomMapView.RouteDestination.Latitude, CustomMapView.RouteDestination.Longitude);

            MKPlacemark sourcePlacemark      = new MKPlacemark(coordinate: sourceLocation);
            MKPlacemark destinationPlacemark = new MKPlacemark(coordinate: destinationLocation);

            sourceMapItem      = new MKMapItem(sourcePlacemark);
            destinationMapItem = new MKMapItem(destinationPlacemark);

            MKPointAnnotation sourceAnnotation = new MKPointAnnotation();

            //sourceAnnotation.Title = "Source";
            sourceAnnotation.Coordinate = sourcePlacemark.Location.Coordinate;

            MKPointAnnotation destinationAnnotation = new MKPointAnnotation();

            //destinationAnnotation.Title = "Destination";
            destinationAnnotation.Coordinate = destinationPlacemark.Location.Coordinate;

            //save annotations so they can be removed later if requested
            annotationsList.Add(sourceAnnotation);
            annotationsList.Add(destinationAnnotation);

            NativeMapView.AddAnnotation(sourceAnnotation);
            NativeMapView.AddAnnotation(destinationAnnotation);

            CalculateRouteDetails();
        }
        void FindRouteToSafeZone()
        {
            MKPlacemarkAddress address = null;

            //Start at our current location
            var fromLocation = new MKPlacemark (CDC.Coordinates, address);

            //Go to the safe zone
            var destinationLocation = new MKPlacemark (new CLLocationCoordinate2D (Cheyenne.Latitude, Cheyenne.Longitude), address);

            var request = new MKDirectionsRequest {
                Source = new MKMapItem (fromLocation),
                Destination = new MKMapItem (destinationLocation),
                RequestsAlternateRoutes = false
            };

            var directions = new MKDirections (request);

            //Async network call to Apple's servers
            directions.CalculateDirections ((response, error) => {
                if (error != null) {
                    Console.WriteLine (error.LocalizedDescription);
                } else {

                    foreach (var route in response.Routes) {
                        map.AddOverlay (route.Polyline);
                    }
                }
            });

            map.OverlayRenderer = (mapView, overlay) => {
                if (overlay is MKCircle) {
                    if (circleRenderer == null) {
                        circleRenderer = new MKCircleRenderer (overlay as MKCircle) {
                            FillColor = UIColor.Red,
                            Alpha = 0.5f
                        };
                    }
                    return circleRenderer;
                } else if (overlay is MKPolygon) {
                    if (polyRenderer == null) {
                        polyRenderer = new MKPolygonRenderer (overlay as MKPolygon);
                        polyRenderer.FillColor = UIColor.Green;
                        polyRenderer.Alpha = 0.5f;
                    }
                    return polyRenderer;
                } else if (overlay is MKPolyline) {
                    var route = (MKPolyline)overlay;
                    var renderer = new MKPolylineRenderer (route) {
                        StrokeColor = UIColor.Blue
                    };
                    return renderer;
                }
                return null;
            };

            Helpers.CenterOnUnitedStates (map);
        }
Ejemplo n.º 4
0
        public override async Task <IEnumerable <Geoposition> > CalculateRoute(Geoposition from, Geoposition to)
        {
            IEnumerable <Geoposition> result = Enumerable.Empty <Geoposition>();

            var nativeFrom = CoordinateConverter.ConvertToNative(from);
            var nativeTo   = CoordinateConverter.ConvertToNative(to);

            var userPlaceMark      = new MKPlacemark(nativeFrom, new Foundation.NSDictionary());
            var incidencePlaceMark = new MKPlacemark(nativeTo, new Foundation.NSDictionary());

            var sourceItem = new MKMapItem(userPlaceMark);
            var destItem   = new MKMapItem(incidencePlaceMark);

            var request = new MKDirectionsRequest
            {
                Source        = sourceItem,
                Destination   = destItem,
                TransportType = MKDirectionsTransportType.Automobile
            };

            var directions = new MKDirections(request);

            MKPolyline polyRoute = null;

            directions.CalculateDirections((response, error) =>
            {
                if (error != null)
                {
                    System.Diagnostics.Debug.WriteLine(error.LocalizedDescription);
                }
                else
                {
                    if (response.Routes.Any())
                    {
                        var firstRoute = response.Routes.First();
                        polyRoute      = firstRoute.Polyline;
                    }
                }
            });

            do
            {
                await Task.Delay(100);
            }while (directions.Calculating);

            if (polyRoute != null)
            {
                result = polyRoute.Points.Select(s =>
                {
                    CLLocationCoordinate2D coordinate = MKMapPoint.ToCoordinate(s);
                    return(CoordinateConverter.ConvertToAbstraction(coordinate));
                });
            }

            return(result);
        }
        private async Task <IEnumerable <Position> > RequestMKMapRoutePoints(RouteModel route, CLLocationCoordinate2D from, CLLocationCoordinate2D to)
        {
            IEnumerable <Position> result = Enumerable.Empty <Position>();

            var userPlaceMark      = new MKPlacemark(from, new Foundation.NSDictionary());
            var incidencePlaceMark = new MKPlacemark(to, new Foundation.NSDictionary());

            var sourceItem = new MKMapItem(userPlaceMark);
            var destItem   = new MKMapItem(incidencePlaceMark);

            var request = new MapKit.MKDirectionsRequest
            {
                Source        = sourceItem,
                Destination   = destItem,
                TransportType = MKDirectionsTransportType.Automobile
            };

            var directions = new MKDirections(request);

            MKPolyline polyRoute = null;

            directions.CalculateDirections((response, error) =>
            {
                if (error != null)
                {
                    System.Diagnostics.Debug.WriteLine(error.LocalizedDescription);
                }
                else
                {
                    if (response.Routes.Any())
                    {
                        var firstRoute  = response.Routes.First();
                        polyRoute       = firstRoute.Polyline;
                        route.Distance += firstRoute.Distance;
                        route.Duration += firstRoute.ExpectedTravelTime / 60;
                    }
                }
            });

            do
            {
                await Task.Delay(100);
            }while (directions.Calculating);

            if (polyRoute != null)
            {
                result = polyRoute.Points.Select(s =>
                {
                    CLLocationCoordinate2D coordinate = MKMapPoint.ToCoordinate(s);
                    return(CoordinateConverter.ConvertToAbstraction(coordinate));
                });
            }

            return(result);
        }
Ejemplo n.º 6
0
        internal static Task PlatformOpenMapsAsync(double latitude, double longitude, MapsLaunchOptions options)
        {
            if (string.IsNullOrWhiteSpace(options.Name))
            {
                options.Name = string.Empty;
            }

            NSDictionary dictionary = null;
            var          placemark  = new MKPlacemark(new CLLocationCoordinate2D(latitude, longitude), dictionary);

            return(OpenPlacemark(placemark, options));
        }
Ejemplo n.º 7
0
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            //Load the placemark and by default zoom into the placemark
            MKPlacemark placemark = assignmentViewModel.SelectedAssignment.ToPlacemark();
            var         span      = new MKCoordinateSpan(1, 1);
            var         region    = new MKCoordinateRegion(placemark.Coordinate, span);

            mapView.ClearPlacemarks();
            mapView.AddAnnotation(placemark);
            mapView.SetRegion(region, false);
        }
        static void OpenIOSMap(Place place)
        {
            double latitude = place.Latitude;
            double longitude = place.Longitude;
            CLLocationCoordinate2D center = new CLLocationCoordinate2D (latitude, longitude);

            MKPlacemark placemark = new MKPlacemark (center, null);
            MKMapItem mapItem = new MKMapItem (placemark);
            mapItem.Name = place.Name;
            MKLaunchOptions options = new MKLaunchOptions ();
            options.MapSpan = MKCoordinateRegion.FromDistance (center, 200, 200).Span;
            mapItem.OpenInMaps (options);
        }
Ejemplo n.º 9
0
        public void ShowGmaps(double lat, double lon)
        {
            CLLocationCoordinate2D coordinate_end = new CLLocationCoordinate2D(lat, lon);
            MKPlacemark            placeMark_end  = new MKPlacemark(coordinate_end, new MKPlacemarkAddress());
            MKMapItem mapItem_end = new MKMapItem(placeMark_end);

            MKMapItem mapItem_start = MKMapItem.MapItemForCurrentLocation();

            MKLaunchOptions options = new MKLaunchOptions();

            options.DirectionsMode = MKDirectionsMode.Driving;

            MKMapItem.OpenMaps(new MKMapItem[] { mapItem_start, mapItem_end }, options);
        }
Ejemplo n.º 10
0
            public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
            {
                // add item to map
                CLLocationCoordinate2D coord = MapItems[indexPath.Row].Placemark.Location.Coordinate;

                map.AddAnnotations(new MKPointAnnotation()
                {
                    Title      = MapItems[indexPath.Row].Name,
                    Coordinate = coord
                });
                map.SetCenterCoordinate(coord, true);

                CLLocationCoordinate2D coords  = map.UserLocation.Coordinate;
                NSDictionary           marker1 = new NSDictionary();
                var orignPlaceMark             = new MKPlacemark((coords), marker1);
                var sourceItem = new MKMapItem(orignPlaceMark);


                var destPlaceMark = new MKPlacemark((coord), marker1);
                var destItem      = new MKMapItem(destPlaceMark);

                var go = new MKDirectionsRequest
                {
                    Source                  = sourceItem,
                    Destination             = destItem,
                    RequestsAlternateRoutes = true
                };

                var line = new MKDirections(go);

                line.CalculateDirections((response, error) =>
                {
                    if (error != null)
                    {
                        Console.WriteLine(error.LocalizedDescription);
                    }
                    else
                    {
                        foreach (var route in response.Routes)
                        {
                            map.AddOverlay(route.Polyline);
                        }
                    }
                    var save = new NSString();
                });

                DismissViewController(false, null);
            }
Ejemplo n.º 11
0
		/// <summary>
		/// When the reverse geocode finds a location, it calls this method
		/// which puts the placemark on the map as an Annotation
		/// </summary>
		public override void FoundWithPlacemark (MKReverseGeocoder geocoder, MKPlacemark placemark)
		{
			if (OnFoundWithPlacemark == null)
			{							
				try 
				{
					_MapPresenter.MapView.AddAnnotationObject (placemark);
				} 
				catch (Exception ex) 
				{
					Console.WriteLine ("FoundWithPlacemark" + ex.Message);
				}
			}
			else
				OnFoundWithPlacemark(geocoder, placemark);
					
		}
Ejemplo n.º 12
0
        public Task <bool> TryOpenAsync(double latitude, double longitude, MapLaunchOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (string.IsNullOrWhiteSpace(options.Name))
            {
                options.Name = string.Empty;
            }

            NSDictionary dictionary = null;
            var          placemark  = new MKPlacemark(new CLLocationCoordinate2D(latitude, longitude), dictionary);

            return(OpenPlacemark(placemark, options));
        }
        void Directions_TouchUpInside(object sender, EventArgs e)
        {
            var location = new CLLocationCoordinate2D(this.Cinema.Latitude, this.Cinema.Longitute);
            MKPlacemarkAddress address = null;
            var placemark = new MKPlacemark(location, address);

            var mapItem = new MKMapItem(placemark);

            mapItem.Name = String.Format("Cineworld {0}", this.Cinema.Name);

            var launchOptions = new MKLaunchOptions();

            launchOptions.DirectionsMode = (sender == this.btnWalkingDirections) ? MKDirectionsMode.Walking : MKDirectionsMode.Driving;
            launchOptions.ShowTraffic    = (sender == this.btnDrivingDirections);
            launchOptions.MapType        = MKMapType.Standard;

            mapItem.OpenInMaps(launchOptions);
        }
Ejemplo n.º 14
0
        public static void LoadMapItem(this CLLocation self, MapItemLoadCompletionHandler completionHandler)
        {
            var geocoder = new CLGeocoder();

            geocoder.ReverseGeocodeLocation(self, (placemarks, error) => {
                if (placemarks == null)
                {
                    completionHandler(null, error);
                    return;
                }
                if (placemarks.Length == 0)
                {
                    completionHandler(null, error);
                    return;
                }
                var mkPlacement = new MKPlacemark(placemarks[0].Location.Coordinate);
                completionHandler(new MKMapItem(mkPlacement), null);
            });
        }
Ejemplo n.º 15
0
        private Task <MKPlacemark[]> SearchAsync(string query, double?lat, double?lng, double radiusInMeters)
        {
            var tcs    = new TaskCompletionSource <MKPlacemark[]>();
            var result = new MKPlacemark[0];

            var o = new NSObject();

            o.InvokeOnMainThread(async() =>
            {
                try
                {
                    var searchRequest = new MKLocalSearchRequest {
                        NaturalLanguageQuery = query
                    };

                    if (lat.HasValue && lng.HasValue &&
                        lat.Value != 0 && lng.Value != 0)
                    {
                        // You can use this parameter to narrow the list of search results to those inside or close to the specified region.
                        // Specifying a region does not guarantee that the results will all be inside the region. It is merely a hint to the search engine.

                        var region           = MKCoordinateRegion.FromDistance(new CLLocationCoordinate2D(lat.Value, lng.Value), radiusInMeters * 2, radiusInMeters * 2);
                        searchRequest.Region = region;
                    }

                    var search = new MKLocalSearch(searchRequest);

                    var searchResult = await search.StartAsync();
                    result           = searchResult.MapItems.Select(x => x.Placemark).ToArray();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    tcs.TrySetResult(result);
                }
            });

            return(tcs.Task);
        }
Ejemplo n.º 16
0
        private void OnDidSelectAnnotationView(object sender, MKAnnotationViewEventArgs e)
        {
            var annotation = map.SelectedAnnotations.First();

            if (annotation is BikeStationAnnotation bikeStationAnnotation)
            {
                var selectedBikeStation = new MKPlacemark(bikeStationAnnotation.Coordinate);

                var directionRequest = new MKDirectionsRequest
                {
                    Source                  = MKMapItem.MapItemForCurrentLocation(),
                    Destination             = new MKMapItem(selectedBikeStation),
                    RequestsAlternateRoutes = false,
                    TransportType           = MKDirectionsTransportType.Walking
                };

                var direction = new MKDirections(directionRequest);
                direction.CalculateDirections(OnDirectionsCalculated);
            }
        }
Ejemplo n.º 17
0
        private async void AddRouteView(Route route)
        {
            if (mapControl == null)
            {
                return;
            }

            var startPlace = new MKPlacemark(
                new CLLocationCoordinate2D(
                    route.StartLocation.Latitude,
                    route.StartLocation.Longitude),
                (MKPlacemarkAddress)null);

            var endPlace = new MKPlacemark(
                new CLLocationCoordinate2D(
                    route.EndLocation.Latitude,
                    route.EndLocation.Longitude),
                (MKPlacemarkAddress)null);

            var request = new MKDirectionsRequest
            {
                Source                  = new MKMapItem(startPlace),
                Destination             = new MKMapItem(endPlace),
                RequestsAlternateRoutes = false,
            };

            var directions = new MKDirections(request);

            directions.CalculateDirections((response, error) =>
            {
                if (error == null)
                {
                    foreach (var item in response.Routes)
                    {
                        mapControl.AddOverlay(item.Polyline);
                        renderedRoute.Add(route, item.Polyline);
                    }
                }
            });
        }
Ejemplo n.º 18
0
        private void CreateRoute()
        {
            //Create Origin and Dest Place Marks and Map Items to use for directions
            //Start at Xamarin SF Office
            var orignPlaceMark = new MKPlacemark(new CLLocationCoordinate2D(37.797530, -122.402590), null);
            var sourceItem     = new MKMapItem(orignPlaceMark);

            //End at Xamarin Cambridge Office
            var destPlaceMark = new MKPlacemark(new CLLocationCoordinate2D(42.374172, -71.120639), null);
            var destItem      = new MKMapItem(destPlaceMark);

            //Create Directions request using the source and dest items
            var request = new MKDirectionsRequest
            {
                Source                  = sourceItem,
                Destination             = destItem,
                RequestsAlternateRoutes = true
            };

            var directions = new MKDirections(request);

            //Hit Apple Directions server
            directions.CalculateDirections((response, error) =>
            {
                if (error != null)
                {
                    Console.WriteLine(error.LocalizedDescription);
                }
                else
                {
                    //Add each polyline from route to map as overlay
                    foreach (var route in response.Routes)
                    {
                        _map.AddOverlay(route.Polyline);
                    }
                }
            });
        }
        static async Task DoLaunchDirections(NavigationAddress destination)
        {
            await Thread.UI.Run(async() =>
            {
                CLLocationCoordinate2D?coords;

                if (destination.HasGeoLocation())
                {
                    coords = new CLLocationCoordinate2D(destination.Latitude.Value, destination.Longitude.Value);
                }
                else
                {
                    coords = await FindCoordinates(destination);
                }

                using (var mark = new MKPlacemark(coords.Value, default(NSDictionary)))
                    using (var mapItem = new MKMapItem(mark)
                    {
                        Name = destination.Name.OrEmpty()
                    })
                        MKMapItem.OpenMaps(new[] { mapItem });
            });
        }
			/// <summary>
			/// This pulls out an assignment we placed in a MKPlacemark
			/// </summary>
			private Assignment GetAssignment(MKPlacemark annotation)
			{
				return annotation.AddressDictionary[new NSString("Assignment")].UnwrapObject<Assignment>();
			}
Ejemplo n.º 21
0
 public void AddPlacemark(MKPlacemark placemark)
 {
     AddAnnotationObject (placemark);
 }
Ejemplo n.º 22
0
 /// <summary>
 /// This pulls out an assignment we placed in a MKPlacemark
 /// </summary>
 private Assignment GetAssignment(MKPlacemark annotation)
 {
     return(annotation.AddressDictionary[new NSString("Assignment")].UnwrapObject <Assignment>());
 }
Ejemplo n.º 23
0
 public void AddPlacemark(MKPlacemark placemark)
 {
     AddAnnotationObject(placemark);
 }
Ejemplo n.º 24
0
		private void SetPlacemark(MKPlacemark placemark)
		{
			string address = placemark.SubThoroughfare + " " + placemark.Thoroughfare;
			SetAddress(address);			
		}
Ejemplo n.º 25
0
 public Flyover(MKPlacemark placemark)
 {
     Coordinate = placemark.Coordinate;
 }
Ejemplo n.º 26
0
		void IReverseGeo.HandleGeoCoderDelOnFoundWithPlacemark (MKReverseGeocoder arg1, MKPlacemark placemark)
		{

		}
Ejemplo n.º 27
0
        /// <summary>
        /// Navigate to an address
        /// </summary>
        /// <param name="name">Label to display</param>
        /// <param name="street">Street</param>
        /// <param name="city">City</param>
        /// <param name="state">Sate</param>
        /// <param name="zip">Zip</param>
        /// <param name="country">Country</param>
        /// <param name="countryCode">Country Code if applicable</param>
        /// <param name="navigationType">Navigation type</param>
        public async Task <bool> NavigateTo(string name, string street, string city, string state, string zip, string country, string countryCode, NavigationType navigationType = NavigationType.Default)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                name = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(street))
            {
                street = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(city))
            {
                city = string.Empty;
            }

            if (string.IsNullOrWhiteSpace(state))
            {
                state = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(zip))
            {
                zip = string.Empty;
            }


            if (string.IsNullOrWhiteSpace(country))
            {
                country = string.Empty;
            }


            CLPlacemark[] placemarks = null;
#if __IOS__
            MKPlacemarkAddress placemarkAddress = null;
#elif MAC
            NSDictionary placemarkAddress = null;
#endif
            try
            {
#if __IOS__
                placemarkAddress = new MKPlacemarkAddress
                {
                    City        = city,
                    Country     = country,
                    State       = state,
                    Street      = street,
                    Zip         = zip,
                    CountryCode = countryCode
                };
#elif MAC
                placemarkAddress = new NSDictionary
                {
                    [Contacts.CNPostalAddressKey.City]           = new NSString(city),
                    [Contacts.CNPostalAddressKey.Country]        = new NSString(country),
                    [Contacts.CNPostalAddressKey.State]          = new NSString(state),
                    [Contacts.CNPostalAddressKey.Street]         = new NSString(street),
                    [Contacts.CNPostalAddressKey.PostalCode]     = new NSString(zip),
                    [Contacts.CNPostalAddressKey.IsoCountryCode] = new NSString(countryCode)
                };
#endif

                var coder = new CLGeocoder();

#if __IOS__
                placemarks = await coder.GeocodeAddressAsync(placemarkAddress.Dictionary);
#elif MAC
                placemarks = await coder.GeocodeAddressAsync(placemarkAddress);
#endif
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to get geocode address from address: " + ex);
                return(false);
            }

            if ((placemarks?.Length ?? 0) == 0)
            {
                Debug.WriteLine("No locations exist, please check address.");
                return(false);
            }

            try
            {
                var placemark   = placemarks[0];
                var mkPlacemark = new MKPlacemark(placemark.Location.Coordinate, placemarkAddress);

                var mapItem = new MKMapItem(mkPlacemark)
                {
                    Name = name
                };

                MKLaunchOptions launchOptions = null;
                if (navigationType != NavigationType.Default)
                {
                    launchOptions = new MKLaunchOptions
                    {
                        DirectionsMode = navigationType == NavigationType.Driving ? MKDirectionsMode.Driving : MKDirectionsMode.Walking
                    };
                }

                var mapItems = new[] { mapItem };
                MKMapItem.OpenMaps(mapItems, launchOptions);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to launch maps: " + ex);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 28
0
        /*private async void FindRouteAndDrawRoute (double sourceLat, double sourceLng, double destinationLat, double destinationLng, DirectionsMode directionsMode = DirectionsMode.Driving)
         *      {
         *  if (CLLocationManager.Status == CLAuthorizationStatus.NotDetermined ||  CLLocationManager.Status == CLAuthorizationStatus.Denied)
         *      return;
         *
         *  //get current location
         *  Geolocator locator = new Geolocator(){ DesiredAccuracy = 100};
         *  var location = await locator.GetPositionAsync(50000);
         *
         *  Console.WriteLine("Position Status: {0}", location.Timestamp);
         *  Console.WriteLine("Position Latitude: {0}", location.Latitude);
         *  Console.WriteLine("Position Longitude: {0}", location.Longitude);
         *
         *  MKPlacemark source = new MKPlacemark (new CLLocationCoordinate2D (sourceLat, sourceLng), new NSDictionary ());
         *              MKMapItem sourceItem = new MKMapItem (source);
         *
         *              desCoordinate = new CLLocationCoordinate2D (destinationLat, destinationLng);
         *              MKPlacemark destination = new MKPlacemark (new CLLocationCoordinate2D (destinationLat, destinationLng), new NSDictionary ());
         *              MKMapItem destinationItem = new MKMapItem (destination);
         *
         *              MKDirectionsRequest request = new MKDirectionsRequest ();
         *              request.Source = sourceItem;
         *              request.Destination = destinationItem;
         *              request.TransportType = directionsMode == DirectionsMode.Driving ? MKDirectionsTransportType.Automobile : MKDirectionsTransportType.Walking;
         *
         *              MKDirections direction = new MKDirections (request);
         *
         *              direction.CalculateDirections (delegate(MKDirectionsResponse response, NSError error) {
         *                      if (error == null) {
         *                              //remove all routes that has been drawn on map
         *                              if (mapView.Overlays != null && mapView.Overlays.Length != 0) {
         *                                      foreach (var overlay in mapView.Overlays) {
         *                                              mapView.RemoveOverlay (overlay);
         *                                      }
         *                              }
         *
         *                              //check if have route
         *                              if (response.Routes.Length == 0) {
         *                                      Mvx.Resolve<IMvxMessenger> ().Publish (new ToastMessage (this.ViewModel, "Cannot find the route"));
         *                              }
         *
         *                              //add new route
         *                              foreach (var route in response.Routes) {
         *                                      MKPolyline polyline = route.Polyline;
         *                                      mapView.AddOverlay (polyline);
         *
         *                                      ViewModel.TotalDistance = route.Distance;
         *                                      ViewModel.ExpectedTime = TimeSpan.FromSeconds(route.ExpectedTravelTime);
         *
         *                                      foreach (var step in route.Steps) {
         *                                              ViewModel.Routes.Add (new FlexyPark.Core.Models.RouteItem () {
         *                                                      Instruction = step.Instructions,
         *                                                      Distance = step.Distance,
         *                                                      Long = step.Polyline.Coordinate.Longitude,
         *                                                      Lat = step.Polyline.Coordinate.Latitude
         *                                              });
         *
         *                                              Console.WriteLine (step.Instructions);
         *                                              Console.WriteLine (step.Distance);
         *                                      }
         *                                      break;
         *                              }
         *
         *                      } else {
         *                              Console.WriteLine (error.LocalizedDescription);
         *                      }
         *              });
         *
         *              MKMapPoint userPoint = MKMapPoint.FromCoordinate (new CLLocationCoordinate2D (sourceLat, sourceLng));
         *              MKMapRect zoomRect = new MKMapRect (userPoint.X, userPoint.Y, 0.1, 0.1);
         *
         *              MKMapPoint annotationPoint = MKMapPoint.FromCoordinate (new CLLocationCoordinate2D (destinationLat, destinationLng));
         *              MKMapRect pointRect = new MKMapRect (annotationPoint.X, annotationPoint.Y, 0.1, 0.1);
         *
         *              zoomRect = MKMapRect.Union (zoomRect, pointRect);
         *
         *  overviewRegion = MKCoordinateRegion.FromMapRect (zoomRect);
         *  overviewRegion.Span.LatitudeDelta += 0.05;
         *  overviewRegion.Span.LongitudeDelta += 0.05;
         *
         *              StepAnnotation annotationSoure = new StepAnnotation ();
         *              annotationSoure.SetCoordinate (new CLLocationCoordinate2D (sourceLat, sourceLng));
         *              mapView.AddAnnotation (annotationSoure);
         *
         *              MKPointAnnotation annotationDest = new MKPointAnnotation ();
         *              annotationDest.SetCoordinate (new CLLocationCoordinate2D (destinationLat, destinationLng));
         *              mapView.AddAnnotation (annotationDest);
         *
         *              destinationAnnotation = annotationDest;
         *
         *  mapView.SetRegion (overviewRegion, true);
         *
         *  isShowRoute = true;
         *      }*/

        private async void FindRouteAndDrawRoute(double destinationLat, double destinationLng, DirectionsMode directionsMode = DirectionsMode.Driving)
        {
            if (CLLocationManager.Status == CLAuthorizationStatus.NotDetermined || CLLocationManager.Status == CLAuthorizationStatus.Denied)
            {
                return;
            }

            //get current location
            Geolocator locator = new Geolocator()
            {
                DesiredAccuracy = 100
            };
            var location = await locator.GetPositionAsync(50000);

            Console.WriteLine("Position Status: {0}", location.Timestamp);
            Console.WriteLine("Position Latitude: {0}", location.Latitude);
            Console.WriteLine("Position Longitude: {0}", location.Longitude);

            var sourceLat = location.Latitude;
            var sourceLng = location.Longitude;

            MKPlacemark source     = new MKPlacemark(new CLLocationCoordinate2D(sourceLat, sourceLng), new NSDictionary());
            MKMapItem   sourceItem = new MKMapItem(source);

            desCoordinate = new CLLocationCoordinate2D(destinationLat, destinationLng);
            MKPlacemark destination     = new MKPlacemark(new CLLocationCoordinate2D(destinationLat, destinationLng), new NSDictionary());
            MKMapItem   destinationItem = new MKMapItem(destination);

            MKDirectionsRequest request = new MKDirectionsRequest();

            request.Source        = sourceItem;
            request.Destination   = destinationItem;
            request.TransportType = directionsMode == DirectionsMode.Driving ? MKDirectionsTransportType.Automobile : MKDirectionsTransportType.Walking;

            MKDirections direction = new MKDirections(request);

            direction.CalculateDirections(delegate(MKDirectionsResponse response, NSError error) {
                if (error == null)
                {
                    //remove all routes that has been drawn on map
                    if (mapView.Overlays != null && mapView.Overlays.Length != 0)
                    {
                        foreach (var overlay in mapView.Overlays)
                        {
                            mapView.RemoveOverlay(overlay);
                        }
                    }

                    //check if have route
                    if (response.Routes.Length == 0)
                    {
                        Mvx.Resolve <IMvxMessenger> ().Publish(new ToastMessage(this.ViewModel, "Cannot find the route"));
                    }

                    //add new route
                    foreach (var route in response.Routes)
                    {
                        MKPolyline polyline = route.Polyline;
                        mapView.AddOverlay(polyline);

                        ViewModel.TotalDistance = route.Distance;
                        ViewModel.ExpectedTime  = TimeSpan.FromSeconds(route.ExpectedTravelTime);

                        foreach (var step in route.Steps)
                        {
                            ViewModel.Routes.Add(new FlexyPark.Core.Models.RouteItem()
                            {
                                Instruction = step.Instructions,
                                Distance    = step.Distance,
                                Long        = step.Polyline.Coordinate.Longitude,
                                Lat         = step.Polyline.Coordinate.Latitude
                            });

                            Console.WriteLine(step.Instructions);
                            Console.WriteLine(step.Distance);
                        }
                        break;
                    }
                }
                else
                {
                    Mvx.Resolve <IMvxMessenger>().Publish(new ToastMessage(this.ViewModel, error.LocalizedDescription));
                }
            });

            MKMapPoint userPoint = MKMapPoint.FromCoordinate(new CLLocationCoordinate2D(sourceLat, sourceLng));
            MKMapRect  zoomRect  = new MKMapRect(userPoint.X, userPoint.Y, 0.1, 0.1);

            MKMapPoint annotationPoint = MKMapPoint.FromCoordinate(new CLLocationCoordinate2D(destinationLat, destinationLng));
            MKMapRect  pointRect       = new MKMapRect(annotationPoint.X, annotationPoint.Y, 0.1, 0.1);

            zoomRect = MKMapRect.Union(zoomRect, pointRect);

            overviewRegion = MKCoordinateRegion.FromMapRect(zoomRect);
            overviewRegion.Span.LatitudeDelta  += 0.05;
            overviewRegion.Span.LongitudeDelta += 0.05;

            StepAnnotation annotationSoure = new StepAnnotation();

            annotationSoure.SetCoordinate(new CLLocationCoordinate2D(sourceLat, sourceLng));
            mapView.AddAnnotation(annotationSoure);

            MKPointAnnotation annotationDest = new MKPointAnnotation();

            annotationDest.SetCoordinate(new CLLocationCoordinate2D(destinationLat, destinationLng));
            mapView.AddAnnotation(annotationDest);

            destinationAnnotation = annotationDest;

            mapView.SetRegion(overviewRegion, true);

            isShowRoute = true;
        }
Ejemplo n.º 29
0
        private void CreateRoute()
        {
            //Create Origin and Dest Place Marks and Map Items to use for directions
            //Start at Xamarin SF Office
            var orignPlaceMark = new MKPlacemark(new CLLocationCoordinate2D(37.797530, -122.402590), null);
            var sourceItem = new MKMapItem(orignPlaceMark);

            //End at Xamarin Cambridge Office
            var destPlaceMark = new MKPlacemark(new CLLocationCoordinate2D(42.374172, -71.120639), null);
            var destItem = new MKMapItem(destPlaceMark);

            //Create Directions request using the source and dest items
            var request = new MKDirectionsRequest
            {
                Source = sourceItem,
                Destination = destItem,
                RequestsAlternateRoutes = true
            };

            var directions = new MKDirections(request);

            //Hit Apple Directions server
            directions.CalculateDirections((response, error) =>
            {
                if (error != null)
                {
                    Console.WriteLine(error.LocalizedDescription);
                }
                else
                {
                    //Add each polyline from route to map as overlay
                    foreach (var route in response.Routes)
                    {
                        _map.AddOverlay(route.Polyline);
                    }
                }
            });
        }
Ejemplo n.º 30
0
		/// <summary>
		/// Открытие станции в приложении "Карты" от iOS
		/// </summary>
		public void OpenMapForPlace ()
		{
			const int regionDistance = 10000;
			var point = station.Point;
			var coord = new CLLocationCoordinate2D (point.Latitude, point.Longitude);
			var region = MKCoordinateRegion.FromDistance (coord, regionDistance, regionDistance);
			MKPlacemarkAddress address = null;
			var placemark = new MKPlacemark(coord,address);
			var mapItem = new MKMapItem (placemark);
			var option = new MKLaunchOptions ();
			option.MapCenter = region.Center;
			option.MapSpan = region.Span;
			mapItem.Name =station.StationTitle;
			mapItem.OpenInMaps (option);
		}
Ejemplo n.º 31
0
 /// <summary>
 /// MKReverseGeocoderDelegate calls this method when it finds a match
 /// for the latitude,longitude passed to MKReverseGeocoder() constructor
 /// </summary>
 public override void FoundWithPlacemark(MKReverseGeocoder reverseGeoCoder, MKPlacemark placeMark)
 {
     #if DEBUG
     SystemLogger.Log (SystemLogger.Module.PLATFORM, "Inside FoundWithPlacemark ");
     #endif
     geoDecoderAttributes.AdditionalStreetLevelInfo = placeMark.SubThoroughfare;
     geoDecoderAttributes.StreetAddress = placeMark.Thoroughfare;
     geoDecoderAttributes.Locality = placeMark.Locality;
     geoDecoderAttributes.AdditionalCityLevelInfo = placeMark.SubLocality;
     geoDecoderAttributes.Country = placeMark.Country;
     geoDecoderAttributes.CountryCode = placeMark.CountryCode;
     geoDecoderAttributes.PostalCode = placeMark.PostalCode;
     geoDecoderAttributes.AdministrativeArea = placeMark.AdministrativeArea;
     geoDecoderAttributes.SubAdministrativeArea = placeMark.SubAdministrativeArea;
 }
Ejemplo n.º 32
0
        private void CreateRoute()
        {
            //Create Origin and Dest Place Marks and Map Items to use for directions

            //Start at Vantage Office Norwest
            origin_latlong = new CLLocationCoordinate2D(-33.732711, 150.9618983);

            //19A Cook Street Baulkham Hills 2153
            destination_latlong = new CLLocationCoordinate2D(-33.762764, 150.9987214);

            //6 Forest Knoll Castle Hill
            destination_latlong = new CLLocationCoordinate2D(-33.7359772, 151.0202179);

            //Sydney Opera House
            destination_latlong = new CLLocationCoordinate2D(-33.8567844, 151.2131027);

            //Sydney International Airport
            destination_latlong = new CLLocationCoordinate2D(-33.9353852, 151.1633858);

            //ON Stationers Rockdale
            destination_latlong = new CLLocationCoordinate2D(-33.9604298, 151.1425861);


            orignPlaceMark = new MKPlacemark(origin_latlong);
            destPlaceMark  = new MKPlacemark(destination_latlong);

            var sourceItem = new MKMapItem(orignPlaceMark);
            var destItem   = new MKMapItem(destPlaceMark);

            if (start_pin != null)
            {
                map_view.RemoveAnnotation(start_pin);
            }

            if (finish_pin != null)
            {
                map_view.RemoveAnnotation(finish_pin);
            }

            start_pin = new BasicMapAnnotation(origin_latlong, "Start", "This is where we start");
            map_view.AddAnnotation(start_pin);

            finish_pin = new BasicMapAnnotation(destination_latlong, "Finish", "You have reached your destination");
            map_view.AddAnnotation(finish_pin);


            //Create Directions request using the source and dest items
            var request = new MKDirectionsRequest {
                Source                  = sourceItem,
                Destination             = destItem,
                RequestsAlternateRoutes = true
            };

            var directions = new MKDirections(request);

            //Hit Apple Directions server
            directions.CalculateDirections((response, error) => {
                if (error != null)
                {
                    Console.WriteLine(error.LocalizedDescription);
                }
                else
                {
                    var newRegion = new MKCoordinateRegion(orignPlaceMark.Coordinate, InitialZoomSpan);
                    map_view.SetRegion(newRegion, true);

                    Console.WriteLine($"_________________________________________________________________________________________");
                    Console.WriteLine($"We found {response.Routes.Length} routes:");
                    var i = 1;
                    foreach (var route in response.Routes)
                    {
                        Console.WriteLine($"   {i}) {route.Name}  {route.Distance}m  {route.ExpectedTravelTime}seconds");
                        i++;
                    }

                    //Add each polyline from route to map as overlay
                    foreach (var route in response.Routes)
                    {
                        map_view.AddOverlay(route.Polyline);

                        Console.WriteLine($"_________________________________________________________________________________________");
                        Console.WriteLine($"ROUTE INSTRUCTIONS:  {route.Name}   {route.Distance}m  {route.ExpectedTravelTime}seconds");

                        if ((route.AdvisoryNotices != null) && (route.AdvisoryNotices.Length > 0))
                        {
                            Console.WriteLine($"                     Route Notices:");
                            foreach (var notice in route.AdvisoryNotices)
                            {
                                Console.WriteLine($"                         {notice}");
                            }
                        }

                        Console.WriteLine($"_________________________________________________________________________________________");
                        foreach (var step in route.Steps)
                        {
                            Console.WriteLine($"    {step.Distance}  {step.Instructions}     : {step.Polyline.Coordinate.ToString()}");
                            if (step.Notice != null)
                            {
                                Console.WriteLine($"                     Notice: {step.Notice} ");
                            }
                        }
                        Console.WriteLine($"_________________________________________________________________________________________");
                    }
                }
            });
        }
Ejemplo n.º 33
0
 public void AddAnnotation(MKPlacemark [] placemarks)
 {
     AddAnnotationObjects (placemarks);
 }
Ejemplo n.º 34
0
		public void HandleGeoCoderDelOnFoundWithPlacemark (MKReverseGeocoder arg1, MKPlacemark placemark)
		{
			SetPlacemark(placemark);
		}
Ejemplo n.º 35
0
        void CreateRoute(string select)
        {
            //start
            OverlayOptions ();

            List <Order> selectedColor = new List<Order> ();
            foreach (var l in ViewModel.Markers) {
                if (Enum.GetName(typeof(HamsterColor),l.Color) == select)
                    selectedColor.Add (l);

            }
            if(select.Equals(All))
                selectedColor = ViewModel.Markers;

            for (int i = 0; i < selectedColor.Count -1;i++) {

                var orignPlaceMark = new MKPlacemark (new CLLocationCoordinate2D (
                    double.Parse (selectedColor [i].HamsterLatitude, System.Globalization.CultureInfo.InvariantCulture),
                    double.Parse (selectedColor [i].HamsterLongitude, System.Globalization.CultureInfo.InvariantCulture)),
                    new MKPlacemarkAddress ());
                var sourceItem = new MKMapItem (orignPlaceMark);
                int itemNext = i + 1;
                var destPlaceMark = new MKPlacemark (new CLLocationCoordinate2D (
                    double.Parse (selectedColor [itemNext].HamsterLatitude, System.Globalization.CultureInfo.InvariantCulture),
                    double.Parse (selectedColor [itemNext].HamsterLongitude, System.Globalization.CultureInfo.InvariantCulture)),
                    new MKPlacemarkAddress ());

                var destItem = new MKMapItem (destPlaceMark);

                //Create Directions request using the source and dest items
                var request = new MKDirectionsRequest {
                    Source = sourceItem,
                    Destination = destItem,
                    RequestsAlternateRoutes = false
                };

                var directions = new MKDirections (request);

                //Hit Apple Directions server
                directions.CalculateDirections ((response, error) => {
                    if (error != null) {
                        RouteAlert ();
                    } else {
                        //Add each polyline from route to map as overlay
                        foreach (var route in response.Routes) {
                            map.AddOverlay (route.Polyline);
                        }
                    }
                });
            }
            _loadPop.Hide ();
            _loadPop.Dispose ();
        }
Ejemplo n.º 36
0
        void FindRouteToSafeZone()
        {
            MKPlacemarkAddress address = null;

            //Start at our current location
            var fromLocation = new MKPlacemark(CDC.Coordinates, address);

            //Go to the safe zone
            var destinationLocation = new MKPlacemark(new CLLocationCoordinate2D(Cheyenne.Latitude, Cheyenne.Longitude), address);

            var request = new MKDirectionsRequest {
                Source                  = new MKMapItem(fromLocation),
                Destination             = new MKMapItem(destinationLocation),
                RequestsAlternateRoutes = false
            };

            var directions = new MKDirections(request);

            //Async network call to Apple's servers
            directions.CalculateDirections((response, error) => {
                if (error != null)
                {
                    Console.WriteLine(error.LocalizedDescription);
                }
                else
                {
                    foreach (var route in response.Routes)
                    {
                        map.AddOverlay(route.Polyline);
                    }
                }
            });

            map.OverlayRenderer = (mapView, overlay) => {
                if (overlay is MKCircle)
                {
                    if (circleRenderer == null)
                    {
                        circleRenderer = new MKCircleRenderer(overlay as MKCircle)
                        {
                            FillColor = UIColor.Red,
                            Alpha     = 0.5f
                        };
                    }
                    return(circleRenderer);
                }
                else if (overlay is MKPolygon)
                {
                    if (polyRenderer == null)
                    {
                        polyRenderer           = new MKPolygonRenderer(overlay as MKPolygon);
                        polyRenderer.FillColor = UIColor.Green;
                        polyRenderer.Alpha     = 0.5f;
                    }
                    return(polyRenderer);
                }
                else if (overlay is MKPolyline)
                {
                    var route    = (MKPolyline)overlay;
                    var renderer = new MKPolylineRenderer(route)
                    {
                        StrokeColor = UIColor.Blue
                    };
                    return(renderer);
                }
                return(null);
            };

            Helpers.CenterOnUnitedStates(map);
        }