コード例 #1
0
            void GetRoute()
            {
                var fromPlace = new MKMapItem(new MKPlacemark(_userLocation));
                var toPlace   = new MKMapItem(new MKPlacemark(_destination));

                var request = new MKDirectionsRequest
                {
                    Source                  = fromPlace,
                    Destination             = toPlace,
                    RequestsAlternateRoutes = false,
                    TransportType           = MKDirectionsTransportType.Any
                };

                var directions = new MKDirections(request);

                directions.CalculateDirections((r, e) =>
                {
                    if (r == null || !r.Routes.Any())
                    {
                        return;
                    }

                    var route = r.Routes[0];

                    _mapView.AddOverlay(route.Polyline);
                });
            }
コード例 #2
0
        public void showDirection(CLLocationCoordinate2D userCoordinate, CLLocationCoordinate2D destinationCoordinate)
        {
            var req = new MKDirectionsRequest()
            {
                Source                  = new MKMapItem(new MKPlacemark(userCoordinate)),
                Destination             = new MKMapItem(new MKPlacemark(destinationCoordinate)),
                TransportType           = MKDirectionsTransportType.Automobile,
                RequestsAlternateRoutes = true
            };
            var dir = new MKDirections(req);

            dir.CalculateDirections((response, error) =>
            {
                if (error == null)
                {
                    //Add each Polyline from route to map as overlay
                    foreach (var route in response.Routes)
                    {
                        map.AddOverlay(route.Polyline);
                    }
                }
                else
                {
                    Console.WriteLine(error.LocalizedDescription);
                }
            });
        }
コード例 #3
0
        void ShowDirections(MKMapItem destination, MKMapView mapView)
        {
            var source = new MKMapItem(new MKPlacemark(ViewController.currentLocation, (MKPlacemarkAddress)null));

            var request = new MKDirectionsRequest()
            {
                Destination             = destination,
                Source                  = source,
                RequestsAlternateRoutes = false,
            };

            var directions = new MKDirections(request);

            directions.CalculateDirections((MKDirectionsResponse response, NSError e) => {
                if (this.route != null)
                {
                    mapView.RemoveOverlay(this.route);
                }

                if (response == null || response.Routes.Length == 0)
                {
                    return;
                }

                //save the overlay so we can remove it next time we draw
                route = response.Routes[0].Polyline;

                mapView.AddOverlay(route, MKOverlayLevel.AboveRoads);
            });
        }
コード例 #4
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);
        }
コード例 #5
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);
        }
コード例 #6
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            try
            {
                if (_posiciones.Count >= 2)
                {
                    var primera = _posiciones[0];
                    var ultima  = _posiciones[_posiciones.Count - 1];

                    var Centrar = new CLLocationCoordinate2D(primera.Coordenada.Latitud, primera.Coordenada.Longitud);
                    var Altura  = new MKCoordinateSpan(.1, .1);
                    var Region  = new MKCoordinateRegion(Centrar, Altura);

                    Mapa.SetRegion(Region, true);

                    _posiciones.ForEach(x => Mapa.AddAnnotation(
                                            new MKPointAnnotation()
                    {
                        Title      = x.ViajeId.ToString(),
                        Coordinate = new CLLocationCoordinate2D()
                        {
                            Latitude  = x.Coordenada.Latitud,
                            Longitude = x.Coordenada.Longitud
                        }
                    }));

                    var origen        = new CLLocationCoordinate2D(primera.Coordenada.Latitud, primera.Coordenada.Longitud);
                    var destino       = new CLLocationCoordinate2D(ultima.Coordenada.Latitud, ultima.Coordenada.Longitud);
                    var Info          = new NSDictionary();
                    var OrigenDestino = new MKDirectionsRequest()
                    {
                        Source      = new MKMapItem(new MKPlacemark(origen, Info)),
                        Destination = new MKMapItem(new MKPlacemark(destino, Info))
                    };
                    var Direcciones = new MKDirections(OrigenDestino);
                    Direcciones.CalculateDirections((response, error) =>
                    {
                        var ruta  = response.Routes[0];
                        var Linea = new MKPolylineRenderer(ruta.Polyline)
                        {
                            LineWidth   = 5.0f,
                            StrokeColor = UIColor.Orange
                        };
                        Mapa.OverlayRenderer = (mapView, overlay) => Linea;
                        Mapa.AddOverlay(ruta.Polyline, MKOverlayLevel.AboveRoads);
                    });
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex);
                MostrarMensaje("Error: ", ex.Message);
            }
        }
コード例 #7
0
        public Task <GeoDirection> GetDirectionsAsync(double originLat, double originLng, double destLat, double destLng, DateTime?date)
        {
            var tcs    = new TaskCompletionSource <GeoDirection>();
            var result = new GeoDirection();

            var o = new NSObject();

            o.InvokeOnMainThread(() =>
            {
                try
                {
                    var origin      = new CLLocationCoordinate2D(originLat, originLng);
                    var destination = new CLLocationCoordinate2D(destLat, destLng);

                    var emptyDict = new NSDictionary();
                    var req       = new MKDirectionsRequest
                    {
                        Source        = new MKMapItem(new MKPlacemark(origin, emptyDict)),
                        Destination   = new MKMapItem(new MKPlacemark(destination, emptyDict)),
                        TransportType = MKDirectionsTransportType.Automobile,
                    };

                    if (date.HasValue)
                    {
                        req.DepartureDate = DateTimeToNSDate(date.Value);
                    }

                    var dir = new MKDirections(req);
                    dir.CalculateDirections((response, error) =>
                    {
                        if (error == null)
                        {
                            var route       = response.Routes [0];
                            result.Distance = Convert.ToInt32(route.Distance);
                            result.Duration = Convert.ToInt32(route.ExpectedTravelTime);
                        }
                        else
                        {
                            _logger.LogMessage("Error with CalculateDirections");
                            _logger.LogMessage("Error Code: " + error.Code);
                            _logger.LogMessage("Description: " + error.LocalizedDescription);
                        }

                        tcs.TrySetResult(result);
                    });
                }
                catch (Exception ex)
                {
                    _logger.LogMessage("Exception in AppleDirectionProvider");
                    _logger.LogError(ex);
                    tcs.TrySetResult(result);
                }
            });

            return(tcs.Task);
        }
コード例 #8
0
        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);
        }
コード例 #9
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //SE CREA LA LISTA  Y MANDA LLAMAR EL METOOO DE CARGAR DATOS Y SE LO ASIGNA
            var Lista = CargarDatos();


            //EMPIEZA A CREAR LAS NUEVAS ANOTACIONES DE UNA FORMA DINAMICA
            Lista.ForEach(x => Mapa.AddAnnotation(new MKPointAnnotation()
            {
                Title      = x.Titulo,
                Coordinate = new CLLocationCoordinate2D()
                {
                    Latitude  = x.Latitud,
                    Longitude = x.Longitud
                }
            }));


            //DIRECCIONES
            var bajio  = new CLLocationCoordinate2D(21.152676, -101.711698);
            var laguna = new CLLocationCoordinate2D(25.510326, -103.453235);
            var Info   = new NSDictionary();


            var OrigenDestino = new MKDirectionsRequest()
            {
                Source      = new MKMapItem(new MKPlacemark(bajio, Info)),
                Destination = new MKMapItem(new MKPlacemark(laguna, Info)),
            };
            //SE CREA LA INSTANCIA PARA LAS DIRECCIONES
            var Direcciones = new MKDirections(OrigenDestino);

            //NOS AYUDARA A CARGAR LAS DIRECCIONES Y MARCARLO EN EL MAPA
            Direcciones.CalculateDirections((response, error) =>
            {
                if (error == null)
                {
                    var ruta  = response.Routes[0];
                    var Linea = new MKPolylineRenderer(ruta.Polyline)
                    {
                        LineWidth   = 5.0f,
                        StrokeColor = UIColor.Blue
                    };

                    //	SE CREA UN NUEVA CAPA
                    Mapa.OverlayRenderer = (res, err) => Linea;
                    // SE AGREGA LA NUEVA CAPA AL MAPA
                    Mapa.AddOverlay(ruta.Polyline, MKOverlayLevel.AboveRoads);
                }
            });
        }
コード例 #10
0
ファイル: SecondView.cs プロジェクト: Be-jordan/MapTestFinal
            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);
            }
コード例 #11
0
        //CODE FOR GETTING DIRECTIONS
        public void getDirections(CLLocationCoordinate2D source, CLLocationCoordinate2D destination)
        {
//			var gg = new CLLocationCoordinate2D(37.8197, -122.4786);
//			var sfo = new CLLocationCoordinate2D(37.6189, -122.3750);
            var ggAnnotation = new MKPointAnnotation()
            {
                Title = "Starting Point", Coordinate = source
            };
            var sfoAnnotation = new MKPointAnnotation()
            {
                Title = "My Car", Coordinate = destination
            };

            ParkingMap.ShowAnnotations(new MKPointAnnotation[] { ggAnnotation, sfoAnnotation }, false);

            var emptyDict = new NSDictionary();
            var req       = new MKDirectionsRequest()
            {
                Source        = new MKMapItem(new MKPlacemark(source, emptyDict)),
                Destination   = new MKMapItem(new MKPlacemark(destination, emptyDict)),
                TransportType = MKDirectionsTransportType.Automobile
            };

            var dir = new MKDirections(req);

            dir.CalculateDirections((response, error) => {
                if (error == null)
                {
                    var route   = response.Routes[0];
                    var rteLine = new MKPolylineRenderer(route.Polyline)
                    {
                        LineWidth   = 5.0f,
                        StrokeColor = UIColor.Purple
                    };

                    ParkingMap.OverlayRenderer = (mv, ol) => rteLine;
                    ParkingMap.AddOverlay(route.Polyline, MKOverlayLevel.AboveRoads);
                }
                else
                {
                    Console.WriteLine(error);
                }
            });
        }
コード例 #12
0
        private async void OnDidSelectAnnotationViewAsync(object sender, MKAnnotationViewEventArgs e)
        {
            var nativeMap = Control as MKMapView;

            // Get user's location
            var userLocation = nativeMap.UserLocation.Location.Coordinate;

            //System.Diagnostics.Debug.WriteLine("Pin clicked");
            var start = new Position(userLocation.Latitude, userLocation.Longitude);
            var end   = e.View.Annotation.Coordinate;

            var emptyDict = new NSDictionary();
            var request   = new MKDirectionsRequest()
            {
                Source = new MKMapItem(new MKPlacemark(
                                           new CLLocationCoordinate2D(start.Latitude, start.Longitude), emptyDict)),
                Destination = new MKMapItem(new MKPlacemark(
                                                new CLLocationCoordinate2D(end.Latitude, end.Longitude), emptyDict)),
                TransportType = MKDirectionsTransportType.Walking
            };

            var directions = new MKDirections(request);
            var response   = await directions.CalculateDirectionsAsync();

            var r      = response.Routes[0];
            var coords = r.Polyline.GetCoordinates(0, (int)r.Polyline.PointCount);

            foreach (var point in coords)
            {
                System.Diagnostics.Debug.WriteLine("" + point.Latitude + "/" + point.Longitude);
            }


            nativeMap.DeselectAnnotation(e.View.Annotation, false);

            if (nativeMap.Overlays != null)
            {
                nativeMap.RemoveOverlays(nativeMap.Overlays);
            }

            MKPolyline polyline = response.Routes[0].Polyline;

            nativeMap.AddOverlay(polyline);
        }
コード例 #13
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);
            }
        }
コード例 #14
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);
                    }
                }
            });
        }
コード例 #15
0
ファイル: vcMap.cs プロジェクト: pauZc/8_iOS
        private void Do_Rute(MKDirectionsRequest req, UIColor color, CLLocationCoordinate2D[] coord, MKMapView mapView)
        {
            var dir = new MKDirections(req);

            dir.CalculateDirections((response, error) =>
            {
                if (error == null)
                {
                    var rute = response.Routes[0];
                    var rteL = new MKPolylineRenderer(rute.Polyline)
                    {
                        LineWidth   = 5.0f,
                        StrokeColor = color
                    };
                    mapView.OverlayRenderer = (mv, ol) => rteL;
                    var circleoverlay       = MKCircle.Circle(mapView.CenterCoordinate, 1000);
                    mapView.AddOverlay(circleoverlay);

                    int index = 0;

                    foreach (var position in coord)
                    {
                        coord[index] = new CLLocationCoordinate2D(position.Latitude, position.Longitude);
                        index++;
                    }
                    var routeOverlay = MKPolyline.FromCoordinates(coord);


                    mapView.AddOverlay(routeOverlay);
                    mapView.SetCenterCoordinate(coord[1], true);

                    //mapView.AddOverlay(rute.Polyline, MKOverlayLevel.AboveRoads);
                }
                else
                {
                    Console.WriteLine("Error");
                }
            });
        }
コード例 #16
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);
                    }
                }
            });
        }
コード例 #17
0
        void ShowDirections(MKMapItem destination, MKMapView mapView)
        {
            var source = new MKMapItem(new MKPlacemark(ViewController.currentLocation, (MKPlacemarkAddress)null));

            var request = new MKDirectionsRequest()
            {
                Destination             = destination,
                Source                  = source,
                RequestsAlternateRoutes = false,
            };

            var directions = new MKDirections(request);

            directions.CalculateDirections((MKDirectionsResponse response, NSError e) => {
                if (response == null || response.Routes.Length == 0)
                {
                    return;
                }

                //TODO - remove old route

                //TODO - save the polyline and add it to the map view
            });
        }
コード例 #18
0
        public MKRoute NewRoute(MKMapItem start, MKMapItem finish)
        {
            MKDirectionsRequest drivingRouteRequest = new MKDirectionsRequest();

            drivingRouteRequest.TransportType = MKDirectionsTransportType.Automobile;
            drivingRouteRequest.Source        = start;
            drivingRouteRequest.Destination   = finish;

            MKRoute drivingRoute = null;

            MKDirections drivingRouteDirections = new MKDirections(drivingRouteRequest);

            drivingRouteDirections.CalculateDirections((drivingRouteResponse, drivingRouteError) =>
            {
                if (drivingRouteError != null)
                {
                    drivingRoute = null;
                }
                else
                {
                    // The code doesn't request alternate routes, so add the single calculated route to
                    // a previously declared MKRoute property called walkingRoute.
                    drivingRoute = drivingRouteResponse.Routes[0];
                }
            });
            return(drivingRoute);

            var rteLine = new MKPolylineRenderer(drivingRoute.Polyline)
            {
                LineWidth   = 5.0f,
                StrokeColor = UIColor.Purple
            };

            mapView.GetRendererForOverlay = (mv, ol) => rteLine;
            mapView.AddOverlay(route.Polyline, MKOverlayLevel.AboveRoads);
        }
コード例 #19
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            Visor.Image = UIImage.FromFile("fp.jpg");
            string htmlString =
                "<HTML><BODY BGCOLOR=BLUE><p><center><h1>Hola Web Embebido</h1></center></p></body></html>";

            VisorWeb.LoadHtmlString(htmlString, new NSUrl
                                        ("./", true));
            Selector.ValueChanged += (s, e) => {
                switch (Selector.SelectedSegment)
                {
                case 0:
                    Mapa.MapType = MKMapType.Standard;
                    break;

                case 1:
                    Mapa.MapType = MKMapType.Satellite;
                    break;

                case 2:
                    Mapa.MapType = MKMapType.Hybrid;
                    break;
                }
            };
            Lista.ForEach(x => Mapa.AddAnnotation(new MKPointAnnotation()
            {
                Title      = x.Titulo,
                Coordinate = new CLLocationCoordinate2D()
                {
                    Latitude  = x.Latitud,
                    Longitude = x.Longitud
                }
            }));
            var Leon          = new CLLocationCoordinate2D(21.152676, -101.711698);
            var Cancun        = new CLLocationCoordinate2D(21.052743, -86.847242);
            var Tijuana       = new CLLocationCoordinate2D(32.526384, -117.028983);
            var Info          = new NSDictionary();
            var OrigenDestino = new MKDirectionsRequest()
            {
                Source      = new MKMapItem(new MKPlacemark(Leon, Info)),
                Destination = new MKMapItem(new MKPlacemark(Cancun, Info)),
            };
            var OrigenDestino2 = new MKDirectionsRequest()
            {
                Source      = new MKMapItem(new MKPlacemark(Leon, Info)),
                Destination = new MKMapItem(new MKPlacemark(Tijuana, Info)),
            };
            var RutaLeonCancun = new MKDirections(OrigenDestino);

            RutaLeonCancun.CalculateDirections((response, error) => {
                if (error == null)
                {
                    var ruta  = response.Routes [0];
                    var Linea = new MKPolylineRenderer(ruta.Polyline)
                    {
                        LineWidth   = 5.0f,
                        StrokeColor = UIColor.Red,
                    };
                    Mapa.OverlayRenderer = (Res, Err) => Linea;
                    Mapa.AddOverlay(ruta.Polyline, MKOverlayLevel.AboveRoads);
                }
            });
            var RutaLeonTijuana = new MKDirections(OrigenDestino2);

            RutaLeonTijuana.CalculateDirections((response, error) =>
            {
                if (error == null)
                {
                    var ruta  = response.Routes[0];
                    var Linea = new MKPolylineRenderer(ruta.Polyline)
                    {
                        LineWidth   = 5.0f,
                        StrokeColor = UIColor.Blue,
                    };
                    Mapa.OverlayRenderer = (Res, Err) => Linea;
                    Mapa.AddOverlay(ruta.Polyline, MKOverlayLevel.AboveRoads);
                }
            });
        }
コード例 #20
0
ファイル: ViewController.cs プロジェクト: n0rf3n/XamarinIOS
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            Console.WriteLine("N0rf3n - ViewDidLoad - Begin ");

            try
            {
                var CentrarMapa = new CLLocationCoordinate2D(4.6097102, -74.081749);
                var AlturaMapa  = new MKCoordinateSpan(.003, .003);
                var Region      = new MKCoordinateRegion(CentrarMapa, AlturaMapa);
                mpMapa.SetRegion(Region, true);         //Se asigna la región en el mapa.

                Selector.ValueChanged += (sender, e) => //Cuando el selector cambie, se le va asignar un evento.
                {
                    switch (Selector.SelectedSegment)   //Para cuando cambiar el valor del selector.
                    {
                    case 0:                             //Mapa Estandar
                        mpMapa.MapType = MKMapType.Standard;
                        break;

                    case 1:     //Mapa Satellite
                        mpMapa.MapType = MKMapType.Satellite;
                        break;

                    case 2:     //Mapa Hibrido
                        mpMapa.MapType = MKMapType.HybridFlyover;
                        break;
                    }
                };

                Lista.ForEach(x => mpMapa.AddAnnotation(new MKPointAnnotation()    //ciclo para la vista y se agregara un marcador en el mapa
                {
                    Title      = x.Titulo,
                    Coordinate = new CLLocationCoordinate2D()
                    {
                        Latitude  = x.Latitud,
                        Longitude = x.Longitud
                    }
                }));

                var Leon = new CLLocationCoordinate2D(21.1502859, -101.7104848); //origen y destino deseado
                var CDMX = new CLLocationCoordinate2D(19.4329256, -99.1334383);  //origen y destino deseado

                var Info = new NSDictionary();                                   //Variable de tipo diccionario

                var OrigenDestino = new MKDirectionsRequest()
                {
                    Source      = new MKMapItem(new MKPlacemark(Leon, Info)), //Origen
                    Destination = new MKMapItem(new MKPlacemark(CDMX, Info)), //Destino
                };

                MKDirections mKDirections = new MKDirections(OrigenDestino);
                MKDirections Direcciones  = mKDirections;
                Direcciones.CalculateDirections((response, error) => //aqui se realiza el calculo de la ruta
                {
                    //Se empizan a definir las propiedades para el trazo de la ruta.

                    var Ruta  = response.Routes[0];                   //ruta!
                    var Linea = new MKPolylineRenderer(Ruta.Polyline) //Se debe asignar una linea
                    {
                        //Aqui van las propiedades de la linea en la ruta.
                        LineWidth   = 5.0f,        //ancho de la linea
                        StrokeColor = UIColor.Blue //Color de la linea
                    };

                    mpMapa.OverlayRenderer = (mapView, overlay) => Linea; //Asignación de la linea o linea sobre el mapa.
                    mpMapa.AddOverlay(Ruta.Polyline,
                                      MKOverlayLevel.AboveRoads);         //Se agrega la ruta en el mapa y Va pasar por encima de las etiquetas "MKOverlayLevel.AboveRoads"
                });

                Console.WriteLine("N0rf3n - ViewDidLoad - End ");
            }
            catch (Exception ex)
            {
                Console.WriteLine("N0rf3n - ViewDidLoad - End/Catch Error : " + ex.Message);

                var alerta = UIAlertController.Create("Estado",
                                                      ex.Message,
                                                      UIAlertControllerStyle.Alert);


                alerta.AddAction(UIAlertAction.Create("Aceptar", UIAlertActionStyle.Default, null));

                PresentViewController(alerta, true, null);
            }
        }
コード例 #21
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.
            string html = "<html><body><p><center><h1>Web Embebido</h1></center></p></body></html>";

            ivwVisor.Image = UIImage.FromFile("img/fp.png");
            wvwVisorWeb.LoadHtmlString(html, new NSUrl("./", true));
            mvwMap.CenterCoordinate = new CLLocationCoordinate2D(21.152676, -101.711698);

            sgmSelector.ValueChanged += (sender, e) =>
            {
                switch (sgmSelector.SelectedSegment)
                {
                case 0:
                    mvwMap.MapType = MKMapType.Standard;
                    break;

                case 1:
                    mvwMap.MapType = MKMapType.Satellite;
                    break;

                case 2:
                    mvwMap.MapType = MKMapType.Hybrid;
                    break;
                }
            };

            List.ForEach(x =>
            {
                mvwMap.AddAnnotation(new MKPointAnnotation()
                {
                    Title      = x.Name,
                    Coordinate = new CLLocationCoordinate2D()
                    {
                        Latitude  = x.Latitude,
                        Longitude = x.Longitude
                    }
                });
            });

            var cond = List.Count;
            // Defininito of routes to MKMap
            Place leMX = List.FirstOrDefault(x => x.Key == "LEMX");
            Place caMX = List.FirstOrDefault(x => x.Key == "CAMX");
            Place tjMX = List.FirstOrDefault(x => x.Key == "TJMX");

            // Coordinates
            var leon    = new CLLocationCoordinate2D(leMX.Latitude, leMX.Longitude);
            var cancun  = new CLLocationCoordinate2D(caMX.Latitude, caMX.Longitude);
            var tijuana = new CLLocationCoordinate2D(tjMX.Latitude, tjMX.Longitude);

            var info     = new NSDictionary();
            var request1 = new MKDirectionsRequest()
            {
                Source      = new MKMapItem(new MKPlacemark(leon, info)),
                Destination = new MKMapItem(new MKPlacemark(cancun, info)),
            };

            var request2 = new MKDirectionsRequest()
            {
                Source      = new MKMapItem(new MKPlacemark(leon, info)),
                Destination = new MKMapItem(new MKPlacemark(tijuana, info)),
            };

            var routeLeonCancun = new MKDirections(request1);

            routeLeonCancun.CalculateDirections((response, error) =>
            {
                if (error == null)
                {
                    var route = response.Routes[0];
                    var line  = new MKPolylineRenderer(route.Polyline)
                    {
                        LineWidth   = 5.0f,
                        StrokeColor = UIColor.Red
                    };

                    mvwMap.OverlayRenderer = (res, err) => line;
                    mvwMap.AddOverlay(route.Polyline, MKOverlayLevel.AboveRoads);
                }
            });

            var routeLeonTijuana = new MKDirections(request2);

            routeLeonTijuana.CalculateDirections((response, error) =>
            {
                if (error == null)
                {
                    var route = response.Routes[0];
                    var line  = new MKPolylineRenderer(route.Polyline)
                    {
                        LineWidth   = 5.0f,
                        StrokeColor = UIColor.Blue
                    };

                    mvwMap.OverlayRenderer = (res, err) => line;
                    mvwMap.AddOverlay(route.Polyline, MKOverlayLevel.AboveRoads);
                }
            });
        }
コード例 #22
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            Image.Image = UIImage.FromFile("xamarin_logo.png");
            string htmlString =
                "<HTML><BODY BGCOLOR=WHITE><p><center><h2>Oi Web</h2></center></p></body></html>";

            Web.LoadHtmlString(htmlString, new NSUrl
                                   ("./", true));
            Selector.ValueChanged += (s, e) =>
            {
                switch (Selector.SelectedSegment)
                {
                case 0:
                    Map.MapType = MKMapType.Standard;
                    break;

                case 1:
                    Map.MapType = MKMapType.Satellite;
                    break;

                case 2:
                    Map.MapType = MKMapType.Hybrid;
                    break;
                }
            };
            Lista.ForEach(x => Map.AddAnnotation(new MKPointAnnotation()
            {
                Title      = x.Titulo,
                Coordinate = new CLLocationCoordinate2D()
                {
                    Latitude  = x.Latitude,
                    Longitude = x.Longitude
                }
            }));
            var salvador     = new CLLocationCoordinate2D(-12.9016148, -38.4898474);
            var rioDeJaneiro = new CLLocationCoordinate2D(-22.9111721, -43.5884176);
            var saoPaulo     = new CLLocationCoordinate2D(-23.6821604, -46.8754826);
            var info         = new NSDictionary();

            var origemDestino = new MKDirectionsRequest()
            {
                Source      = new MKMapItem(new MKPlacemark(salvador, info)),
                Destination = new MKMapItem(new MKPlacemark(rioDeJaneiro, info)),
            };

            var origemDestino2 = new MKDirectionsRequest()
            {
                Source      = new MKMapItem(new MKPlacemark(rioDeJaneiro, info)),
                Destination = new MKMapItem(new MKPlacemark(saoPaulo, info)),
            };

            var rotaSalvadorRioDeJaneiro = new MKDirections(origemDestino);

            rotaSalvadorRioDeJaneiro.CalculateDirections((response, error) =>
            {
                if (error == null)
                {
                    var rota  = response.Routes[0];
                    var linha = new MKPolylineRenderer(rota.Polyline)
                    {
                        LineWidth   = 5.0f,
                        StrokeColor = UIColor.Red,
                    };
                    Map.OverlayRenderer = (Res, Err) => linha;
                    Map.AddOverlay(rota.Polyline, MKOverlayLevel.AboveRoads);
                }
            });

            var rotaRioDeJaneiroSaoPaulo = new MKDirections(origemDestino2);

            rotaRioDeJaneiroSaoPaulo.CalculateDirections((response, error) =>
            {
                if (error == null)
                {
                    var rota  = response.Routes[0];
                    var linha = new MKPolylineRenderer(rota.Polyline)
                    {
                        LineWidth   = 5.0f,
                        StrokeColor = UIColor.Blue,
                    };
                    Map.OverlayRenderer = (Res, Err) => linha;
                    Map.AddOverlay(rota.Polyline, MKOverlayLevel.AboveRoads);
                }
            });
        }
コード例 #23
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;
        }
コード例 #24
0
        void CalculateRouteDetails(bool zoomMapToShowFullRoute = true, bool requestAlternateRoutes = true, MKDirectionsTransportType transportType = MKDirectionsTransportType.Automobile)
        {
            MKDirectionsRequest directionRequest = new MKDirectionsRequest();

            directionRequest.Source                  = sourceMapItem;
            directionRequest.Destination             = destinationMapItem;
            directionRequest.RequestsAlternateRoutes = requestAlternateRoutes;
            directionRequest.TransportType           = transportType;

            MKDirections eta = new MKDirections(directionRequest);

            eta.CalculateETA((MKETAResponse response, Foundation.NSError error) =>
            {
                if (error != null)
                {
                    System.Diagnostics.Debug.WriteLine(error.Description);
                }
                else
                {
                    TimeSpan time = TimeSpan.FromSeconds(response.ExpectedTravelTime);
                    System.Diagnostics.Debug.WriteLine(time.ToString(@"hh\:mm\:ss\:fff"));
                }
            });

            MKDirections directions = new MKDirections(directionRequest);


            directions.CalculateDirections((MKDirectionsResponse response, Foundation.NSError error) =>
            {
                if (error != null)
                {
                    System.Diagnostics.Debug.WriteLine(error.Description);
                }
                else
                {
                    //remove previous route overlays
                    ClearOverlays();

                    currentRouteOverlay = response.Routes[0].Polyline;

                    MKRoute route;

                    //loop through backwards so first most route is renderered on top
                    for (int i = response.Routes.Length - 1; i >= 0; i--)
                    {
                        route = response.Routes[i];

                        //save overlay so it can be removed later if requested
                        overlaysList.Add(route.Polyline);

                        NativeMapView.AddOverlay(route.Polyline, MKOverlayLevel.AboveRoads);

                        if (i == 0)
                        {
                            if (zoomMapToShowFullRoute)
                            {
                                MKMapRect rect         = route.Polyline.BoundingMapRect;
                                MKMapRect expandedRect = NativeMapView.MapRectThatFits(rect, new UIEdgeInsets(20, 20, 20, 20));

                                NativeMapView.SetRegion(MKCoordinateRegion.FromMapRect(expandedRect), true);
                            }
                        }
                    }
                }
            });
        }
コード例 #25
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);
                    }
                }
            });
        }
コード例 #26
0
        /// <summary>
        /// Adds a route to the map
        /// </summary>
        /// <param name="route">The route to add</param>
        private void AddRoute(TKRoute route)
        {
            MKDirectionsRequest req = new MKDirectionsRequest();
            req.Source = new MKMapItem(new MKPlacemark(route.Source.ToLocationCoordinate(), new MKPlacemarkAddress()));
            req.Destination = new MKMapItem(new MKPlacemark(route.Destination.ToLocationCoordinate(), new MKPlacemarkAddress()));
            req.TransportType = route.TravelMode.ToTransportType();

            MKDirections directions = new MKDirections(req);
            directions.CalculateDirections(new MKDirectionsHandler((r, e) => 
            {
                if (r != null && r.Routes != null && r.Routes.Any())
                {
                    var nativeRoute = r.Routes.First();

                    this.SetRouteData(route, nativeRoute);

                    this._routes.Add(nativeRoute.Polyline, new TKOverlayItem<TKRoute, MKPolylineRenderer>(route));
                    this.Map.AddOverlay(nativeRoute.Polyline);

                    route.PropertyChanged += OnRoutePropertyChanged;

                    if (this.FormsMap.RouteCalculationFinishedCommand != null && this.FormsMap.RouteCalculationFinishedCommand.CanExecute(route))
                    {
                        this.FormsMap.RouteCalculationFinishedCommand.Execute(route);
                    }
                }
                else
                {
                    if (this.FormsMap.RouteCalculationFailedCommand != null && this.FormsMap.RouteCalculationFailedCommand.CanExecute(route))
                    {
                        this.FormsMap.RouteCalculationFailedCommand.Execute(route);
                    }
                }
            }));
        }
コード例 #27
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);
        }
コード例 #28
0
ファイル: MapView.cs プロジェクト: kosomgua/MapCross
        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 ();
        }
コード例 #29
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($"_________________________________________________________________________________________");
                    }
                }
            });
        }