コード例 #1
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            mapView = new MKMapView(View.Bounds);
            mapView.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
            mapView.MapType          = MKMapType.Standard;
            View.AddSubview(mapView);

            double latitude  = 50.846732;
            double longitude = 4.352413;

            var raysPlace = new CLLocationCoordinate2D(latitude, longitude);

            var zoomRegion = MKCoordinateRegion.FromDistance(raysPlace, 2000, 2000);

            mapView.CenterCoordinate = raysPlace;
            mapView.Region           = zoomRegion;

            mapView.Delegate = new RayMapDelegate();

            locationManager.RequestWhenInUseAuthorization();

            mapView.ShowsUserLocation = true;

            mapView.AddAnnotation(new MKPointAnnotation()
            {
                Title      = "Ray's Hot Dogs",
                Coordinate = new CLLocationCoordinate2D(latitude, longitude)
            });

            mapView.AddAnnotation(new RayAnnotation("Ray's Hot Dogs", raysPlace));
        }
コード例 #2
0
        public void CenterToCurrentLocation(MKMapView map, Event currentEvent)
        {
            var target        = new CLLocationCoordinate2D(currentEvent.Lat, currentEvent.Long);
            var currentregion = MKCoordinateRegion.FromDistance(target, 9000, 9000);

            map.SetRegion(currentregion, animated: false);
        }
コード例 #3
0
        public void ZoomToCurrentLocation(MKMapView map, CLLocationManager LM)
        {
            var target        = new CLLocationCoordinate2D(LM.Location.Coordinate.Latitude, LM.Location.Coordinate.Longitude);
            var currentregion = MKCoordinateRegion.FromDistance(target, 15000, 15000);

            map.SetRegion(currentregion, animated: true);
        }
コード例 #4
0
ファイル: MapaBase.cs プロジェクト: kristiandamian/tacocat
        protected void AgregoMapa()
        {
            map.MapType = MKMapType.Standard;
            map.Bounds  = UIScreen.MainScreen.Bounds;           //full screen baby

            map.ShowsUserLocation = false;

            MKReverseGeocoder geo      = new MKReverseGeocoder(locationManager.Location.Coordinate);
            CLGeocoder        geocoder = new CLGeocoder();

            Task.Factory.StartNew(async() =>
            {
                var res = await geocoder.ReverseGeocodeLocationAsync(locationManager.Location);
                Console.WriteLine(res[0].AdministrativeArea);

                pais   = res[0].Country;
                ciudad = res[0].Locality;
            });

            // centro el mapa y pongo el zoom en la region
            mapCenter = new CLLocationCoordinate2D(locationManager.Location.Coordinate.Latitude,
                                                   locationManager.Location.Coordinate.Longitude);
            var mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 2000, 2000);

            map.CenterCoordinate = mapCenter;
            map.Region           = mapRegion;
        }
コード例 #5
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            window = new UIWindow(UIScreen.MainScreen.Bounds);

            // Create the 'Shows' tab.
            dvc1 = new DialogViewController(null)
            {
                Root = new RootElement("")
                {
                    new Section(), new Section(), new Section(),
                    new Section()
                    {
                        new StringElement("House of Cards"),
                        new StringElement("Game of Thrones"),
                        new StringElement("Person of Interest")
                    }
                }
            };

            // Create the 'Games' tab.
            dvc2 = new DialogViewController(null)
            {
                Root = new RootElement("")
                {
                    new Section(), new Section(), new Section(),
                    new Section()
                    {
                        new StringElement("Braid"),
                        new StringElement("Super Meat Boy"),
                        new StringElement("Fez")
                    }
                }
            };

            // Create the 'Atlanta' tab.
            var mapView = new MKMapView(UIScreen.MainScreen.Bounds);
            var atlanta = new MKCoordinateRegion(new CLLocationCoordinate2D(33.748893, -84.388046), new MKCoordinateSpan(0.35, 0.35));

            mapView.SetRegion(atlanta, false);
            mapViewController             = new UIViewController();
            mapViewController.View.Bounds = UIScreen.MainScreen.Bounds;
            mapViewController.View.AddSubview(mapView);

            // Create and display the floating tab bar controller.
            ftbc = new FloatingTabBarController()
            {
                TabTitles = new List <string> ()
                {
                    "Shows", "Games", "Atlanta"
                },
                ViewControllers = new List <UIViewController> ()
                {
                    dvc1, dvc2, mapViewController
                }
            };
            window.RootViewController = ftbc;
            window.MakeKeyAndVisible();

            return(true);
        }
コード例 #6
0
 void AnimateToPlace()
 {
     var worldCity = SelectedCity;
     var region = new MKCoordinateRegion (new CLLocationCoordinate2D (worldCity.Latitude, worldCity.Longitude),
         new MKCoordinateSpan (0.4, 0.4));
     MapView.SetRegion (region, true);
 }
コード例 #7
0
        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();
            mpMapa.ShowsUserLocation = true;
            var Localizador = CrossGeolocator.Current;
            var Posicion    = await Localizador.GetPositionAsync(TimeSpan.FromSeconds(10), null, true); //obtener la posición cada 10 segundos.

            var Ubicacion     = new CLLocation(Posicion.Latitude, Posicion.Longitude);
            var Georeferencia = new CLGeocoder();
            var DatosGeo      = await Georeferencia.ReverseGeocodeLocationAsync(Ubicacion);


            Latitud  = Posicion.Latitude;
            Longitud = Posicion.Longitude;

            lblCiudad.Text       = DatosGeo[0].Locality;
            lblDepartamento.Text = DatosGeo[0].AdministrativeArea;
            lblLatitud.Text      = Latitud.ToString();
            lblLongitud.Text     = Longitud.ToString();
            lblMunicipio.Text    = DatosGeo[0].SubLocality;
            lblPais.Text         = DatosGeo[0].Country;
            txtDescripcion.Text  = DatosGeo[0].Description;

            mpMapa.MapType = MapKit.MKMapType.HybridFlyover; //Se establece el tipo de mapa
            var CentrarMapa = new CLLocationCoordinate2D(Latitud, Longitud);
            var AlturaMapa  = new MKCoordinateSpan(.003, .003);
            var Region      = new MKCoordinateRegion(CentrarMapa, AlturaMapa);

            mpMapa.SetRegion(Region, true);
        }
コード例 #8
0
        /// <summary>
        /// Load the map data from the properties retreived
        /// </summary>
        private void LoadMapData()
        {
            // value to determin where to zoom in
            var topLeft     = new CLLocationCoordinate2D(-90, 180);
            var bottomRight = new CLLocationCoordinate2D(90, -180);

            // loop through all the properties and add them to the list
            foreach (var item in Properties)
            {
                // create the pin and add the annoation
                var pin = new HeritagePropertyAnnotation(item);
                _mapView.AddAnnotation(pin);

                // determin the topleft and right
                topLeft.Longitude     = Math.Min(topLeft.Longitude, pin.Coordinate.Longitude);
                topLeft.Latitude      = Math.Max(topLeft.Latitude, pin.Coordinate.Latitude);
                bottomRight.Longitude = Math.Max(bottomRight.Longitude, pin.Coordinate.Longitude);
                bottomRight.Latitude  = Math.Min(bottomRight.Latitude, pin.Coordinate.Latitude);
            }

            // zoom in on the annotations
            var region = new MKCoordinateRegion();

            region.Center = new CLLocationCoordinate2D(
                topLeft.Latitude - (topLeft.Latitude - bottomRight.Latitude) * 0.5,
                topLeft.Longitude + (bottomRight.Longitude - topLeft.Longitude) * 0.5);
            region.Span.LatitudeDelta  = Math.Abs(topLeft.Latitude - bottomRight.Latitude) * 1.1;
            region.Span.LongitudeDelta = Math.Abs(bottomRight.Longitude - topLeft.Longitude) * 1.1;

            // set the region
            region = _mapView.RegionThatFits(region);
            _mapView.SetRegion(region, true);
        }
コード例 #9
0
        ///<inheritdoc/>
        public async Task<IEnumerable<IPlaceResult>> GetPredictions(string query, MapSpan bounds)
        {
            List<IPlaceResult> result = new List<IPlaceResult>();

            var region = new MKCoordinateRegion(bounds.Center.ToLocationCoordinate(), new MKCoordinateSpan(0.25, 0.25));

            var request = new MKLocalSearchRequest 
            {
                NaturalLanguageQuery = query,
                Region = region
            };

            MKLocalSearch search = new MKLocalSearch(request);
            var nativeResult = await search.StartAsync();

            if (nativeResult != null && nativeResult.MapItems != null)
            {
                result.AddRange(nativeResult.MapItems.Select(i =>
                    new TKNativeiOSPlaceResult
                    {
                        Description =  string.Format("{0}, {1} {2}", i.Placemark.Title, i.Placemark.AdministrativeArea, i.Placemark.SubAdministrativeArea),
                        Details = new TKPlaceDetails 
                        {
                            Coordinate = i.Placemark.Coordinate.ToPosition()
                        }
                    }));
                return result;
            }
            return null;
        }
コード例 #10
0
        public async override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //Get Location using GeoLocator
            var location = CrossGeolocator.Current;
            var position = await location.GetPositionAsync();

            CLLocationManager locationManager = new CLLocationManager();

            locationManager.RequestWhenInUseAuthorization();

            mapView1.MapType       = MKMapType.Standard;
            mapView1.ZoomEnabled   = true;
            mapView1.ScrollEnabled = true;

            //Set location to mapview
            CLLocationCoordinate2D mapCenter = new CLLocationCoordinate2D(position.Latitude, position.Longitude);
            MKCoordinateRegion     mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 8000, 8000);

            mapView1.CenterCoordinate  = mapCenter;
            mapView1.Region            = mapRegion;
            mapView1.ShowsUserLocation = true;

            lblLatitude.Text  = "Latitude:" + position.Latitude.ToString();
            lblLongitude.Text = "Longitude:" + position.Longitude.ToString();
        }
コード例 #11
0
        private void MoveToRegion(MapSpan mapSpan)
        {
            Xamarin.Forms.Maps.Position center = mapSpan.Center;
            var region = new MKCoordinateRegion(new CLLocationCoordinate2D(center.Latitude, center.Longitude), new MKCoordinateSpan(mapSpan.LatitudeDegrees, mapSpan.LongitudeDegrees));

            Control.SetRegion(region, true);
        }
コード例 #12
0
        private void OnDirectionsCalculated(MKDirectionsResponse response, NSError error)
        {
            if (error != null)
            {
                Console.WriteLine($"Error while calculating directions, error: {error}");
                return;
            }

            if (response == null || !response.Routes.Any())
            {
                Console.WriteLine($"Couldn't calculate directions.");
                return;
            }

            if (map.Overlays != null && map.Overlays.Any())
            {
                map.RemoveOverlays(map.Overlays);
            }

            var route = response.Routes.First();

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

            var rect = route.Polyline.BoundingMapRect;

            map.SetRegion(MKCoordinateRegion.FromMapRect(rect), animated: true);
        }
コード例 #13
0
        void ZoomInToMyLocation(CLLocationCoordinate2D location)
        {
            const double delta  = 2;
            var          region = MKCoordinateRegion.FromDistance(location, delta, delta);

            MapView.SetRegion(region, false);
        }
コード例 #14
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            locationManager.RequestWhenInUseAuthorization();

            // set map type and show user location
            map.MapType           = MKMapType.Standard;
            map.ShowsUserLocation = true;

            map.Bounds = View.Bounds;

            // set map center and region
            const double lat       = 42.374260;
            const double lon       = -71.120824;
            var          mapCenter = new CLLocationCoordinate2D(lat, lon);
            var          mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 2000, 2000);

            //map.CenterCoordinate = mapCenter;
            //map.Region = mapRegion;

            // add an annotation
            map.AddAnnotation(new MKPointAnnotation {
                Title      = "MyAnnotation",
                Coordinate = new CLLocationCoordinate2D(42.364260, -71.120824)
            });

            // set the map delegate
            mapDel       = new MyMapDelegate();
            map.Delegate = mapDel;

            // add a custom annotation
            map.AddAnnotation(new MonkeyAnnotation("Xamarin", mapCenter));

            // add an overlay
            var circleOverlay = MKCircle.Circle(mapCenter, 1000);

            map.AddOverlay(circleOverlay);

            var searchResultsController = new SearchResultsViewController(map);


            var searchUpdater = new SearchResultsUpdator();

            searchUpdater.UpdateSearchResults += searchResultsController.Search;

            //add the search controller
            searchController = new UISearchController(searchResultsController)
            {
                SearchResultsUpdater = searchUpdater
            };

            searchController.SearchBar.SizeToFit();
            searchController.SearchBar.SearchBarStyle = UISearchBarStyle.Minimal;
            searchController.SearchBar.Placeholder    = "Enter a search query";

            searchController.HidesNavigationBarDuringPresentation = false;
            NavigationItem.TitleView   = searchController.SearchBar;
            DefinesPresentationContext = true;
        }
コード例 #15
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            _map.MapType           = MKMapType.Standard;
            _map.ShowsUserLocation = true;
            _map.ZoomEnabled       = true;
            _map.ScrollEnabled     = true;

            var mapCenter = new CLLocationCoordinate2D(Tweet.GpsCoordinates.Latitude, Tweet.GpsCoordinates.Longitude);
            var mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 200, 00);

            _map.CenterCoordinate = mapCenter;
            _map.Region           = mapRegion;

            _delegate     = new MapDelegate();
            _map.Delegate = _delegate;

            var mkPointAnnotation = new MKPointAnnotation
            {
                Title    = Tweet.User,
                Subtitle = Tweet.Text
            };

            mkPointAnnotation.SetCoordinate(new CLLocationCoordinate2D(Tweet.GpsCoordinates.Latitude, Tweet.GpsCoordinates.Longitude));
            _map.AddAnnotation(mkPointAnnotation);
        }
        private MKCoordinateRegion BuildVisibleRegion(LocationCoordinate currentLocation)
        {
            var span   = new MKCoordinateSpan(0.003125, 0.003125);
            var region = new MKCoordinateRegion(new CLLocationCoordinate2D(currentLocation.Latitude, currentLocation.Longitude), span);

            return(region);
        }
コード例 #17
0
        public void check(double lon, double lat)
        {
            var mapCenter = new CLLocationCoordinate2D(lat, lon);
            var mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 3000, 3000);

            map.CenterCoordinate = mapCenter;
            map.Region           = mapRegion;
            if ((lon <= ((-34 * 0.0005) - 106.48694)) && (lat >= ((15 * 0.0005) + 31.739444)) && fuera)
            {
                fuera = false;

                var notification = new UILocalNotification();

                // set the fire date (the date time in which it will fire)
                notification.FireDate = NSDate.Now.AddSeconds(5);                 //DateTime.Now.AddSeconds(10));
                notification.TimeZone = NSTimeZone.DefaultTimeZone;
                // configure the alert stuff
                notification.AlertTitle  = "Peligro";
                notification.AlertAction = "Alert Action";
                notification.AlertBody   = "¡Has entrado en una zona de peligro!";

                notification.UserInfo = NSDictionary.FromObjectAndKey(new NSString("UserInfo for notification"), new NSString("Notification"));

                notification.SoundName = UILocalNotification.DefaultSoundName;

                // schedule it
                UIApplication.SharedApplication.ScheduleLocalNotification(notification);
            }
        }
コード例 #18
0
        void GetAnnotationOfStation()
        {
            if (ActiveStation != null)
            {
                double            result;
                MKPointAnnotation anno = new MKPointAnnotation();
                var coord = anno.Coordinate;
                if (double.TryParse(ActiveStation.Latitude, out result))
                {
                    //anno.Coordinate.Latitude = result;
                    coord.Latitude = result;
                }

                if (double.TryParse(ActiveStation.Longitude, out result))
                {
                    //anno.Coordinate.Longitude = result;
                    coord.Longitude = result;
                }
                anno.Coordinate = coord;
                mapView.AddAnnotation(anno);

                var region = MKCoordinateRegion.FromDistance(anno.Coordinate, 1000, 1000);
                mapView.SetRegion(region, true);
            }
        }
コード例 #19
0
        public void setUpMapView()
        {
            // set the map view
            mapView                   = new MKMapView(UIScreen.MainScreen.Bounds);
            mapView.MapType           = MKMapType.Standard;
            mapView.ShowsUserLocation = true;
            View.AddSubview(mapView);
            // Add annotations
            var userCoordinate      = new CLLocationCoordinate2D(-35.3160, 149.1070);
            var currentUserLocation = new MKPointAnnotation()
            {
                Title = "Your Location", Coordinate = userCoordinate
            };
            var driverUserLocation = new DriverAnnotation(("Driver's location"), new CLLocationCoordinate2D(-35.3169, 149.1075));

            mapView.AddAnnotation(currentUserLocation);
            mapView.AddAnnotation(driverUserLocation);
            // set the map delegate
            mapDelegate      = new MapViewDelegate();
            mapView.Delegate = mapDelegate;
            // Add map center
            const double lat       = -35.3160;
            const double lon       = 149.1070;
            var          mapCenter = new CLLocationCoordinate2D(lat, lon);
            var          mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 100, 100);

            mapView.CenterCoordinate = mapCenter;
            mapView.Region           = mapRegion;
        }
コード例 #20
0
        public LocationPrivacyViewController()
        {
            CheckAccess   = LocationAccessStatus;
            RequestAccess = RequestLocationServicesAuthorization;

            locationManager = new CLLocationManager();
            //If previously allowed, start location manager
            if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse)
            {
                locationManager.StartUpdatingLocation();
            }

            locationManager.Failed += delegate {
                locationManager.StopUpdatingLocation();
            };
            locationManager.LocationsUpdated += delegate {
                var loc = locationManager.Location.ToString();
                locationMessage.Text = loc;

                //MapView
                MKCoordinateRegion region = new MKCoordinateRegion(locationManager.Location.Coordinate, new MKCoordinateSpan(0.1, 0.1));
                mapView.SetRegion(region, true);
            };
            locationManager.AuthorizationChanged += delegate(object sender, CLAuthorizationChangedEventArgs e) {
                accessStatus.Text = e.Status.ToString();
                if (e.Status == CLAuthorizationStatus.AuthorizedWhenInUse)
                {
                    mapView.ShowsUserLocation = true;
                    locationManager.StartUpdatingLocation();
                }
            };
        }
コード例 #21
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Get the region for North America
            MKCoordinateRegion region = new MKCoordinateRegion(
                new CLLocationCoordinate2D(37.37, -96.24),
                new MKCoordinateSpan(28.49, 31.025)
                );

            mapView.SetRegion(region, false);

            // Connect to the RegionChanged event so we can update the displayed forecasts
            // depending on what area of the map is shown.
            mapView.RegionChanged += (sender, e) => {
                // Remove the current annotations
                if (annotations != null)
                {
                    mapView.RemoveAnnotations(annotations);
                }

                // Get and set our new list of WeatherForecastAnnotations
                annotations = weatherServer.GetForecastAnnotations(mapView.Region, 4);
                mapView.AddAnnotation(annotations);
            };

            mapView.GetViewForAnnotation += GetWeatherAnnotationView;
        }
コード例 #22
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // change map type and show user location
            map.MapType           = MKMapType.Hybrid;
            map.ShowsUserLocation = true;

            // set map center and region
            double lat       = 42.374260;
            double lon       = -71.120824;
            var    mapCenter = new CLLocationCoordinate2D(lat, lon);
            var    mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 2000, 2000);

            map.CenterCoordinate = mapCenter;
            map.Region           = mapRegion;

            // add an annotation
            map.AddAnnotation(new MKPointAnnotation()
            {
                Title = "MyAnnotation", Coordinate = new CLLocationCoordinate2D(42.364260, -71.120824)
            });

            // set the map delegate
            mapDel       = new MyMapDelegate();
            map.Delegate = mapDel;

            // add a custom annotation
            map.AddAnnotation(new MonkeyAnnotation("Xamarin", mapCenter));

            // add an overlay
            var circleOverlay = MKCircle.Circle(mapCenter, 1000);

            map.AddOverlay(circleOverlay);
        }
        private void DropGeofenceCircle(PointF point)
        {
            CLLocationCoordinate2D convertedPoint = this.mapView.ConvertPoint(point, this.mapView);
            String pinTitle       = String.Format("Centre of geofence.");
            String subCoordinates = String.Format("{0},{1}", convertedPoint.Latitude.ToString(), convertedPoint.Longitude.ToString());

            if (this.droppedPin != null)
            {
                this.mapView.RemoveAnnotation(this.droppedPin);
            }

            this.droppedPin = new SimpleAnnotation(convertedPoint, pinTitle, subCoordinates);
            this.mapView.AddAnnotation(droppedPin);


            if (this.GeofenceMapDelegate.Circle != null)
            {
                this.mapView.RemoveOverlay(this.GeofenceMapDelegate.Circle);
            }

            this.GeofenceMapDelegate.Circle = MKCircle.Circle(convertedPoint, this.GeofenceService.RadiusOfGeofenceInMeters);
            this.mapView.AddOverlay(this.GeofenceMapDelegate.Circle);

            if (!this.mapView.VisibleMapRect.Contains(this.GeofenceMapDelegate.Circle.BoundingMap))
            {
                this.mapView.SetRegion(MKCoordinateRegion.FromMapRect(this.GeofenceMapDelegate.Circle.BoundingMap), true);
            }
        }
コード例 #24
0
        ///<inheritdoc/>
        public async Task <IEnumerable <IPlaceResult> > GetPredictions(string query, MapSpan bounds)
        {
            List <IPlaceResult> result = new List <IPlaceResult>();

            var region = new MKCoordinateRegion(bounds.Center.ToLocationCoordinate(), new MKCoordinateSpan(0.25, 0.25));

            var request = new MKLocalSearchRequest
            {
                NaturalLanguageQuery = query,
                Region = region
            };

            MKLocalSearch search       = new MKLocalSearch(request);
            var           nativeResult = await search.StartAsync();

            if (nativeResult != null && nativeResult.MapItems != null)
            {
                result.AddRange(nativeResult.MapItems.Select(i =>
                                                             new TKNativeiOSPlaceResult
                {
                    Description = string.Format("{0}, {1} {2}", i.Placemark.Title, i.Placemark.AdministrativeArea, i.Placemark.SubAdministrativeArea),
                    Details     = new TKPlaceDetails
                    {
                        Coordinate               = i.Placemark.Coordinate.ToPosition(),
                        FormattedAddress         = i.Placemark.Title,
                        InternationalPhoneNumber = i.PhoneNumber.ToString(),
                        Website = i.Url.ToString()
                    }
                }));
                return(result);
            }
            return(null);
        }
コード例 #25
0
        public async void MapViewInit()
        {
            CLLocationManager manager = new CLLocationManager();

            manager.RequestWhenInUseAuthorization();

            IGeolocator locator = CrossGeolocator.Current;

            locator.DesiredAccuracy = 50;

            Position position = await locator.GetPositionAsync(timeoutMilliseconds : 20000);

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

            CLLocationCoordinate2D mapCenter = new CLLocationCoordinate2D(position.Latitude, position.Longitude);

            //CLLocationCoordinate2D mapCenter = new CLLocationCoordinate2D(22.617193, 120.3032346);

            CenterLocation = map.CenterCoordinate = mapCenter;

            map.Region = MKCoordinateRegion.FromDistance(mapCenter, 1000, 1000);

            //map.ShowsUserLocation = true;

            CustomMapViewDelegate customDelegate = new CustomMapViewDelegate();

            customDelegate.OnRegionChanged += MapViewOnRegionChanged;
            map.Delegate = customDelegate;
        }
コード例 #26
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            mapView = new MKMapView(View.Bounds);
            mapView.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
            mapView.MapType          = MKMapType.Standard;      // this is the default
            View.AddSubview(mapView);

            double latitude  = 50.846732;
            double longitude = 4.352413;

            var raysPlace = new CLLocationCoordinate2D(latitude, longitude);

            var zoomRegion = MKCoordinateRegion.FromDistance(raysPlace, 2000, 2000);

            mapView.CenterCoordinate = raysPlace;
            mapView.Region           = zoomRegion;

            mapView.Delegate = new RayMapDelegate();

            //Request permission to access device location - necessary on iOS 8.0 and above
            //Don't forget to set NSLocationWhenInUseUsageDescription in Info.plist
            locationManager.RequestWhenInUseAuthorization();

            mapView.ShowsUserLocation = true;

            mapView.AddAnnotation(new MKPointAnnotation()
            {
                Title      = "Ray's Hot Dogs",
                Coordinate = new CLLocationCoordinate2D(latitude, longitude)
            });

            mapView.AddAnnotation(new RayAnnotation("Ray's Hot Dogs", raysPlace));
        }
コード例 #27
0
        private void Map_MapLoaded(object sender, EventArgs e)
        {
            if (count == 1)
            {
                try
                {
                    var span = new MKCoordinateSpan(0.075, 0.075);

                    var region = new MKCoordinateRegion(new CLLocationCoordinate2D(map.UserLocation.Location.Coordinate.Latitude, map.UserLocation.Location.Coordinate.Longitude), span);
                    map.SetRegion(region, true);
                }
                catch (NullReferenceException nre)
                {
                    Debug.WriteLine($"Exception found: {nre}");
                    return;
                }
                catch (SystemException se)
                {
                    Debug.WriteLine($"System Exception found: {se}");
                    return;
                }
            }
            else if (count > 1)
            {
                return;
            }
            count++;
        }
コード例 #28
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			// Get the region for North America
			MKCoordinateRegion region = new MKCoordinateRegion (
				new CLLocationCoordinate2D (37.37, -96.24),
				new MKCoordinateSpan (28.49, 31.025)
			);

			// Connect to the RegionChanged event so we can update the displayed forecasts
			// depending on what area of the map is shown.
			mapView.RegionChanged += (sender, e) => {
				// Remove the current annotations
				if (annotations != null)
					mapView.RemoveAnnotations (annotations);

				// Get and set our new list of WeatherForecastAnnotations
				annotations = weatherServer.GetForecastAnnotations (mapView.Region, 4);
				mapView.AddAnnotations (annotations);
			};

			mapView.GetViewForAnnotation += GetWeatherAnnotationView;

			mapView.SetRegion (region, false);
		}
コード例 #29
0
        public override void ViewDidLoad()
        {
            var mapView = new MKMapView();

            mapView.Delegate = new MyDelegate();
            View             = mapView;

            base.ViewDidLoad();

            // ios7 layout
            if (RespondsToSelector(new Selector("edgesForExtendedLayout")))
            {
                EdgesForExtendedLayout = UIRectEdge.None;
            }

            var thirdViewModel = (ThirdViewModel)ViewModel;

            _zombieManager = new ZombieManager(mapView);

            mapView.SetRegion(MKCoordinateRegion.FromDistance(
                                  new CLLocationCoordinate2D(51.4, 0.4),
                                  50000,
                                  50000), true);

            var set = this.CreateBindingSet <ThirdView, Core.ViewModels.ThirdViewModel>();

            set.Bind(_zombieManager).For(z => z.ItemsSource).To(vm => vm.Yarp);
            set.Apply();
        }
コード例 #30
0
        private void showUserMap()
        {
            map.MapType           = MKMapType.HybridFlyover;
            map.ShowsUserLocation = true;
            map.ZoomEnabled       = true;
            map.ScrollEnabled     = true;
            map.ShowsBuildings    = true;
            map.PitchEnabled      = true;
            map.ShowsCompass      = false;
            double lat = 30.2652233534254;
            double lon = -97.73815460962083;
            CLLocationCoordinate2D mapCenter = new CLLocationCoordinate2D(lat, lon);
            CLLocationCoordinate2D viewPoint = new CLLocationCoordinate2D(lat + 0.0050, lon - 0.0072);
            MKCoordinateRegion     mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 1500, 1500);

            map.CenterCoordinate = mapCenter;
            map.Region           = mapRegion;
            var camera = MKMapCamera.CameraLookingAtCenterCoordinate(mapCenter, viewPoint, 500);

            map.Camera   = camera;
            mapDelegate  = new MapDelegate();
            map.Delegate = mapDelegate;
            askUserPermissions();

            var tapRecogniser     = new UITapGestureRecognizer(this, new Selector("MapTapSelector:"));
            var longTapRecogniser = new UILongPressGestureRecognizer(this, new Selector("MapLongTapSelector:"));

            map.AddGestureRecognizer(tapRecogniser);
            map.AddGestureRecognizer(longTapRecogniser);
            var hotelOverlay = MKCircle.Circle(mapCenter, 1000);

            map.AddOverlay(hotelOverlay);
        }
コード例 #31
0
        internal static MKCoordinateRegion CreateRegion(Geopoint centerCoordinate, double zoomLevel, CGSize size)
        {
            // convert center coordinate to pixel space
            double centerPixelX = LongitudeToPixelSpaceX(centerCoordinate.Position.Longitude);
            double centerPixelY = LatitudeToPixelSpaceY(centerCoordinate.Position.Latitude);

            // determine the scale value from the zoom level
            var    zoomExponent = 21 - zoomLevel;
            double zoomScale    = Math.Pow(2, zoomExponent);

            // scale the map’s size in pixel space
            var    mapSizeInPixels = size;
            double scaledMapWidth  = mapSizeInPixels.Width * zoomScale;
            double scaledMapHeight = mapSizeInPixels.Height * zoomScale;

            // figure out the position of the top-left pixel
            double topLeftPixelX = centerPixelX - (scaledMapWidth / 2);
            double topLeftPixelY = centerPixelY - (scaledMapHeight / 2);

            // find delta between left and right longitudes
            var minLng         = PixelSpaceXToLongitude(topLeftPixelX);
            var maxLng         = PixelSpaceXToLongitude(topLeftPixelX + scaledMapWidth);
            var longitudeDelta = maxLng - minLng;

            // find delta between top and bottom latitudes
            var minLat        = PixelSpaceYToLatitude(topLeftPixelY);
            var maxLat        = PixelSpaceYToLatitude(topLeftPixelY + scaledMapHeight);
            var latitudeDelta = -1 * (maxLat - minLat);

            // create and return the lat/lng span
            var span   = new MKCoordinateSpan(latitudeDelta, longitudeDelta);
            var region = new MKCoordinateRegion(centerCoordinate.ToLocation(), span);

            return(region);
        }
コード例 #32
0
        void MoveToRegion(MapSpan mapSpan, bool animated = true)
        {
            Position center    = mapSpan.Center;
            var      mapRegion = new MKCoordinateRegion(new CLLocationCoordinate2D(center.Latitude, center.Longitude), new MKCoordinateSpan(mapSpan.LatitudeDegrees, mapSpan.LongitudeDegrees));

            ((MKMapView)Control).SetRegion(mapRegion, animated);
        }
コード例 #33
0
        private void UserLocationSubscription(Location location)
        {
            if (location == lastLocation)
            {
                return;
            }
            lastLocation = location;

            Position position = new Position(location.Latitude, location.Longitude);

            if (formsMap.Pins.Any())
            {
                formsMap.Pins[0].Position = position;
            }
            else
            {
                formsMap.Pins.Add(new Pin {
                    Position = position, Label = "UserLocation", Type = PinType.Generic
                });
            }

            if (userAnnotationView != null)
            {
                userAnnotationView.Transform = CGAffineTransform.MakeRotation((float)UnitConverters.DegreesToRadians(lastLocation?.Course ?? 0));
            }

            //formsMap.MoveToRegion(MapSpan.FromCenterAndRadius(position, Distance.FromKilometers(1)));
            nativeMap.SetRegion(MKCoordinateRegion.FromDistance(new CLLocationCoordinate2D(position.Latitude, position.Longitude), 1000, 1000), false);
        }
コード例 #34
0
		partial void ZoomIn (NSObject obj)
		{
			var span = new MKCoordinateSpan (currentSpan.LatitudeDelta * 0.5f, currentSpan.LongitudeDelta * 0.5f);
			var region = new MKCoordinateRegion (currentRegion.Center, span);

			currentSpan = span;
			map.SetRegion (region);
		}
コード例 #35
0
		void AnimateToWorld ()
		{
			var worldCity = SelectedCity;
			var current = MapView.Region;
			var zoomOut = new MKCoordinateRegion (new CLLocationCoordinate2D ((current.Center.Latitude + worldCity.Latitude) / 2.0, (current.Center.Longitude + worldCity.Longitude) / 2.0),
				new MKCoordinateSpan (90, 90));
			MapView.SetRegion (zoomOut, true);
		}
コード例 #36
0
		void OnLocationsUpdated (object sender, CLLocationsUpdatedEventArgs e)
		{
			Region = new MKCoordinateRegion(LocationManager.Location.Coordinate, new MKCoordinateSpan(0.1, 0.1));

			var handler = LocationChanged;
			if (handler != null)
				handler (this, EventArgs.Empty);
		}
コード例 #37
0
ファイル: MapElement.cs プロジェクト: escoz/MonoMobile.Forms
		public void UpdateLocation(CLLocationCoordinate2D newLocation, bool animated){
            var span = new MKCoordinateSpan(0.1,0.1);
			var region = new MKCoordinateRegion(newLocation, span);
			_mapView.SetRegion(region, animated);
			if (_geocodeAnnotation!=null)
				_mapView.RemoveAnnotation(_geocodeAnnotation);
			_geocodeAnnotation = new MapViewAnnotation(newLocation);
			_mapView.AddAnnotationObject(_geocodeAnnotation);
		}
コード例 #38
0
		void SetMapToCoordinate (CLLocationCoordinate2D coordinate)
		{
			var region = new MKCoordinateRegion (coordinate, currentSpan);
			currentRegion = region;

			var newCenterPoint = MKMapPoint.FromCoordinate (coordinate);

			map.SetVisible (new MKMapRect (newCenterPoint.X, newCenterPoint.Y, currentSpan.LatitudeDelta, currentSpan.LongitudeDelta));
			map.SetRegion (region);
		}
コード例 #39
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);
        }
コード例 #40
0
ファイル: Main.cs プロジェクト: runegri/MuPP
        private void SelectStop(StopInfo selectedStop)
        {
            var center = new CLLocationCoordinate2D(selectedStop.LatLon.Latitude, selectedStop.LatLon.Longtitude);
            var region = new MKCoordinateRegion(center, new MKCoordinateSpan(0.003, 0.003));
            var marker = new BusStopMarker(selectedStop.StopName, center);

            BusStopMap.SetRegion(BusStopMap.RegionThatFits(region), true);
            if(BusStopMap.Annotations.Length > 0)
            {
                var annotation = (MKAnnotation)BusStopMap.Annotations[0];
                BusStopMap.RemoveAnnotation(annotation);
            }
            BusStopMap.AddAnnotationObject(marker);

            BusStopCode.Text = selectedStop.StopName;
        }
コード例 #41
0
        void ZoomToUserLocation(MKMapView mapView, MKUserLocation l)
        {
            var span = new MKCoordinateSpan
            {
                LatitudeDelta = 0.1,
                LongitudeDelta = 0.1,
            };

            var region = new MKCoordinateRegion
            {
                Center = l.Coordinate,
                Span = span,
            };

            mapView.SetRegion (region, true);
        }
コード例 #42
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            // Get the region for North America
            MKCoordinateRegion region = new MKCoordinateRegion (
                new CLLocationCoordinate2D (37.37, -96.24),
                new MKCoordinateSpan (28.49, 31.025)
            );

            mapView.SetRegion (region, false);

            mapView.GetViewForAnnotation += GetAirportAnnotationView;
            mapView.RegionChanged += MapRegionChanged;
            mapType.ValueChanged += MapTypeChanged;
        }
コード例 #43
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            window = new UIWindow (UIScreen.MainScreen.Bounds);

            // Create the 'Shows' tab.
            dvc1 = new DialogViewController (null) {
                Root = new RootElement ("") {
                    new Section (), new Section (), new Section (),
                    new Section () {
                        new StringElement ("House of Cards"),
                        new StringElement ("Game of Thrones"),
                        new StringElement ("Person of Interest")
                    }
                }
            };

            // Create the 'Games' tab.
            dvc2 = new DialogViewController (null) {
                Root = new RootElement ("") {
                    new Section (), new Section (), new Section (),
                    new Section () {
                        new StringElement ("Braid"),
                        new StringElement ("Super Meat Boy"),
                        new StringElement ("Fez")
                    }
                }
            };

            // Create the 'Atlanta' tab.
            var mapView = new MKMapView (UIScreen.MainScreen.Bounds);
            var atlanta = new MKCoordinateRegion (new CLLocationCoordinate2D (33.748893, -84.388046), new MKCoordinateSpan (0.35, 0.35));
            mapView.SetRegion (atlanta, false);
            mapViewController = new UIViewController ();
            mapViewController.View.Bounds = UIScreen.MainScreen.Bounds;
            mapViewController.View.AddSubview (mapView);

            // Create and display the floating tab bar controller.
            ftbc = new FloatingTabBarController () {
                TabTitles = new List<string> () { "Shows", "Games", "Atlanta" },
                ViewControllers = new List<UIViewController> () { dvc1, dvc2, mapViewController }
            };
            window.RootViewController = ftbc;
            window.MakeKeyAndVisible ();

            return true;
        }
コード例 #44
0
        public MapRenderer2iOS()
            : base()
        {
            MessagingCenter.Subscribe<IEnumerable<HeritageProperty>>(this, MapRenderer2.MESSAGE_ADD_AND_ZOOM_ON_PINS, (items) =>
            {
                // wire up the map 
                WireUpMap();

                // value to determin where to zoom in
                var topLeft = new CLLocationCoordinate2D(-90, 180);
                var bottomRight = new CLLocationCoordinate2D(90, -180);

                // loop through all the properties and add them to the list
                foreach (var item in items)
                {
                    // create the pin and add the annoation
                    var pin = new HeritagePropertyAnnotation(item);
                    this.NativeMap.AddAnnotation(pin);

                    // determin the topleft and right
                    topLeft.Longitude = Math.Min(topLeft.Longitude, pin.Coordinate.Longitude);
                    topLeft.Latitude = Math.Max(topLeft.Latitude, pin.Coordinate.Latitude);
                    bottomRight.Longitude = Math.Max(bottomRight.Longitude, pin.Coordinate.Longitude);
                    bottomRight.Latitude = Math.Min(bottomRight.Latitude, pin.Coordinate.Latitude);
                }

                // zoom in on the annotations
                var region = new MKCoordinateRegion();
                region.Center = new CLLocationCoordinate2D(
                    topLeft.Latitude - (topLeft.Latitude - bottomRight.Latitude) * 0.5,
                    topLeft.Longitude + (bottomRight.Longitude - topLeft.Longitude) * 0.5);
                region.Span.LatitudeDelta = Math.Abs(topLeft.Latitude - bottomRight.Latitude) * 1.1;
                region.Span.LongitudeDelta = Math.Abs(bottomRight.Longitude - topLeft.Longitude) * 1.1;

                // set the region
                region = this.NativeMap.RegionThatFits(region);
                this.NativeMap.SetRegion(region, true);

            });

            MessagingCenter.Subscribe<IEnumerable<HeritageProperty>>(this, MapRenderer2.MESSAGE_ZOOM_ON_PINS, (items) =>
            {
                // value to determin where to zoom in
                var topLeft = new CLLocationCoordinate2D(-90, 180);
                var bottomRight = new CLLocationCoordinate2D(90, -180);

                // loop through all the properties and add them to the list
                foreach (var item in items)
                {
                    // determin the topleft and right
                    topLeft.Longitude = Math.Min(topLeft.Longitude, item.Longitude);
                    topLeft.Latitude = Math.Max(topLeft.Latitude, item.Latitude);
                    bottomRight.Longitude = Math.Max(bottomRight.Longitude, item.Longitude);
                    bottomRight.Latitude = Math.Min(bottomRight.Latitude, item.Latitude);
                }

                // zoom in on the annotations
                var region = new MKCoordinateRegion();
                region.Center = new CLLocationCoordinate2D(
                    topLeft.Latitude - (topLeft.Latitude - bottomRight.Latitude) * 0.5,
                    topLeft.Longitude + (bottomRight.Longitude - topLeft.Longitude) * 0.5);
                region.Span.LatitudeDelta = Math.Abs(topLeft.Latitude - bottomRight.Latitude) * 1.1;
                region.Span.LongitudeDelta = Math.Abs(bottomRight.Longitude - topLeft.Longitude) * 1.1;

                // set the region
                region = this.NativeMap.RegionThatFits(region);
                this.NativeMap.SetRegion(region, true);
            });
        }
コード例 #45
0
        private void UpdatedLocation(object sender, CLLocationUpdatedEventArgs args)
        {
            const double LatitudeDelta = 0.002;

            const double LongtitudeDelta = LatitudeDelta;
            var PosAccuracy = args.NewLocation.HorizontalAccuracy;
            if (PosAccuracy >= 0) {
                var Coord = args.NewLocation.Coordinate;
                latitudeLabel.Text = string.Format ("{0:F6}° ± {1} m", Coord.Latitude, PosAccuracy);
                longtitudeLabel.Text = string.Format ("{0:F6}° ± {1} m", Coord.Longitude, PosAccuracy);
                if (Coord.IsValid ()) {
                    var region = new MKCoordinateRegion (Coord, new MKCoordinateSpan (LatitudeDelta, LongtitudeDelta));
                    mapView.SetRegion (region, false);
                    mapView.SetCenterCoordinate (Coord, false);
                    //mapView.SelectedAnnotations (mapView.UserLocation, false);
                }
            } else {
                latitudeLabel.Text = "N/A";
                longtitudeLabel.Text = "N/A";
            }
            if (args.NewLocation.VerticalAccuracy >= 0)
                altitudeLabel.Text = string.Format ("{0:F6} m ± {1:F6} m", args.NewLocation.Altitude, args.NewLocation.VerticalAccuracy);
            else
                altitudeLabel.Text = "N/A";
            if (args.NewLocation.Course >= 0)
                courseLabel.Text = string.Format ("{0}°", args.NewLocation.Course);
            else
                courseLabel.Text = "N/A";
            speedLabel.Text = string.Format ("{0} m/s", args.NewLocation.Speed);
        }
コード例 #46
0
ファイル: IPhoneGeo.cs プロジェクト: jioe/appverse-mobile
 private void ShowMap()
 {
     UIApplication.SharedApplication.InvokeOnMainThread (delegate {
         StartUpdatingLocation();
         IPhoneUIViewController contentController = new IPhoneUIViewController ("Map", "Back");
         if (unityMapView == null) {
                 unityMapView = new UnityMapView ();
         }
         coord = new CLLocationCoordinate2D (unityLocation.Latitude, unityLocation.Longitude);
         coordSpan = new MKCoordinateSpan (latitudeDeltaSpan, longitudeDeltaSpan);
         //0.5 means 0.5 degrees -> 55 km approximately; so it display an area of (55 Km * 55 Km) arround the current coordinates
         coordRegion = new MKCoordinateRegion (coord, coordSpan);
         setMapView ();
         setAnnotationPoints ();
         contentController.AddInnerView (unityMapView);
         IPhoneServiceLocator.CurrentDelegate.MainUIViewController ().PresentModalViewController (contentController, true);
         IPhoneServiceLocator.CurrentDelegate.SetMainUIViewControllerAsTopController(false);
     });
 }
コード例 #47
0
        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear (animated);

            // Default to the region for North America
            double minLatitude = 37.37 - (28.49 / 2);
            double maxLatitude = 37.37 + (28.49 / 2);
            double minLongitide = -96.24 - (31.025 / 2);
            double maxLongitude = -96.24 + (31.025 / 2);
            bool initialized = false;

            foreach (var code in LogBook.GetVisitedAirports ()) {
                Airport airport = Airports.GetAirport (code, AirportCode.FAA);
                if (airport == null)
                    continue;

                if (!initialized) {
                    minLongitide = maxLongitude = airport.Longitude;
                    minLatitude = maxLatitude = airport.Latitude;
                    initialized = true;
                } else {
                    minLongitide = Math.Min (minLongitide, airport.Longitude);
                    maxLongitude = Math.Max (maxLongitude, airport.Longitude);
                    minLatitude = Math.Min (minLatitude, airport.Latitude);
                    maxLatitude = Math.Max (maxLatitude, airport.Latitude);
                }
            }

            coordinates = new CLLocationCoordinate2D ((minLatitude + maxLatitude) / 2, (minLongitide + maxLongitude) / 2);
            double spanLongitude = Math.Abs (maxLongitude - minLongitide);
            double spanLatitude = Math.Abs (maxLatitude - minLatitude);

            if (initialized) {
                spanLongitude = Math.Max (spanLongitude, 1.0) * 1.25;
                spanLatitude = Math.Max (spanLatitude, 1.0) * 1.25;
            }

            // Get the region for North America
            var region = new MKCoordinateRegion (
                coordinates, new MKCoordinateSpan (spanLatitude, spanLongitude)
            );

            mapView.SetRegion (region, animated);
        }
コード例 #48
0
        public void FocusOnLocation(BikeLocation bike)
        {
            HideDistanceView();

            RemoveRouteAnnotation();

            foreach(CycleAnnotation an in mapView.Annotations)
            {
                if (an.Bike == bike)
                {

                    MKCoordinateRegion region = new MKCoordinateRegion(an.Bike.Location, new MKCoordinateSpan(0.01, 0.01));

                    region = mapView.RegionThatFits(region);

                    mapView.SetRegion(region, true);
                    mapView.SelectAnnotation(an, true);

                    mapView.ShowsUserLocation = true;
                    return;
                }
            }
        }
コード例 #49
0
		void HandleUpdatedLocation (CLLocation newLocation)
		{
			if (ignoreMapUpdate)
				return;
			
			if (newLocation == null)
			{
				if (localisationRetryCount == 0)
				{
					localisationRetryCount++;
					
					Action action = () =>
					{
						Util.RequestLocation(HandleUpdatedLocation);
					};
					Util.ShowAlertSheet("No reply from network! Give another try? :)", View, action);				
				}
				else
				{
					localisationRetryCount++;
					Thread.Sleep(300);					
					Util.RequestLocation(HandleUpdatedLocation);
					
					if (localisationRetryCount == 4)
						localisationRetryCount = 0;
				}		
			}
			else
			{
				loaded = true;
				PhotoLocation = newLocation;
				
				var spanLocal = new MKCoordinateSpan (0.02, 0.02);
				var span = firstUpdate ? spanLocal : mapView.Region.Span;
				firstUpdate = false;
				
				var region = new MKCoordinateRegion (newLocation.Coordinate, span);
				mapView.SetRegion (region, false);
				mapView.SetCenterCoordinate (newLocation.Coordinate, false);
				//mapView.SelectAnnotation(mapView.UserLocation, false);				
				
				double radiusInMeters = 100d;    
				MKCircle circle = MKCircle.Circle(newLocation.Coordinate, radiusInMeters);
				mapView.AddOverlay(circle);					
				
				RepositionAnnotation(newLocation.Coordinate);
			}
		}
コード例 #50
0
        IEnumerable<Airport> GetAirports(MKCoordinateRegion region)
        {
            if (visited) {
                foreach (var code in LogBook.GetVisitedAirports ()) {
                    Airport airport = Airports.GetAirport (code, AirportCode.FAA);
                    if (airport != null)
                        yield return airport;
                }
            } else {
                foreach (var airport in Airports.GetAirports (region))
                    yield return airport;
            }

            yield break;
        }
コード例 #51
0
			/// <summary>
			/// Center the map when the user is located
			/// </summary>
			public override void DidUpdateUserLocation (MKMapView mapView, MKUserLocation userLocation)
			{
				if (userLocation != null) {
					var span = new MKCoordinateSpan (15, 15);
					var region = new MKCoordinateRegion (userLocation.Coordinate, span);
					mapView.SetRegion (region, true);
				}
			}
コード例 #52
0
        void UpdateLocation(CLLocation location)
        {
            var region = new MKCoordinateRegion (
                location.Coordinate, new MKCoordinateSpan (1.0, 1.0)
            );

            coordinates = location.Coordinate;

            if (!visited)
                mapView.SetRegion (region, true);
        }
コード例 #53
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            mapView = new MKMapView()
            {
                ShowsUserLocation = true
            };

            labelDistance = new UILabel()
            {
                Frame = new RectangleF (0, 0, 320, 49),
                Lines = 2,
                BackgroundColor = UIColor.Black,
                TextColor = UIColor.White
            };

            var segmentedControl = new UISegmentedControl();
            var topOfSegement = View.Frame.Height - 120;
            segmentedControl.Frame = new RectangleF(20, topOfSegement, 282, 30);
            segmentedControl.InsertSegment("Map", 0, false);
            segmentedControl.InsertSegment("Satellite", 1, false);
            segmentedControl.InsertSegment("Hybrid", 2, false);
            segmentedControl.SelectedSegment = 0;
            segmentedControl.ControlStyle = UISegmentedControlStyle.Bar;
            segmentedControl.TintColor = UIColor.DarkGray;

            if(UIDevice.CurrentDevice.CheckSystemVersion(6,0))
                segmentedControl.InsertSegment ("Directions", 3, false);

            segmentedControl.ValueChanged += delegate {
                if (segmentedControl.SelectedSegment == 0)
                    mapView.MapType = MonoTouch.MapKit.MKMapType.Standard;
                else if (segmentedControl.SelectedSegment == 1)
                    mapView.MapType = MonoTouch.MapKit.MKMapType.Satellite;
                else if (segmentedControl.SelectedSegment == 2)
                    mapView.MapType = MonoTouch.MapKit.MKMapType.Hybrid;
                else if (segmentedControl.SelectedSegment == 3) {
                    var conferenceMapItem = new MKMapItem(new MKPlacemark(ConferenceLocation, null));
                    conferenceMapItem.Name = "MonkeySpace";

                    var conferenceHotel = new MKMapItem(new MKPlacemark(new CLLocationCoordinate2D(42.36346, -71.0863), null));
                    conferenceHotel.Name = "MonkeySpace Hotel";

                    var mapItems = new MKMapItem[] { conferenceMapItem, conferenceHotel };
                    MKMapItem.OpenMaps(mapItems, new MKLaunchOptions() {
                        DirectionsMode = MKDirectionsMode.Walking
                    });
                }
            };

            mapView.Delegate = new MapViewDelegate(this);

            // Set the web view to fit the width of the app.
            mapView.SizeToFit();

            // Reposition and resize the receiver
            mapView.Frame = new RectangleF (0, 50, View.Frame.Width, View.Frame.Height - 100);

            MKCoordinateSpan span = new MKCoordinateSpan(0.01,0.01);
            MKCoordinateRegion region = new MKCoordinateRegion(ConferenceLocation,span);
            mapView.SetRegion(region, true);

            ConferenceAnnotation a = new ConferenceAnnotation(ConferenceLocation
                                , "MonkeySpace"
                                , "NERD Center"
                              );
            mapView.AddAnnotationObject(a);

            locationManager = new CLLocationManager();
            locationManager.Delegate = new LocationManagerDelegate(mapView, this);
            locationManager.StartUpdatingLocation();

            // Add the table view as a subview
            View.AddSubview(mapView);
            View.AddSubview(labelDistance);
            View.AddSubview(segmentedControl);

            // Add the 'info' button to flip
            var flipButton = UIButton.FromType(UIButtonType.InfoLight);
            flipButton.Frame = new RectangleF(290,17,20,20);
            flipButton.Title (UIControlState.Normal);
            flipButton.TouchDown += delegate {
                _mfvc.Flip();
            };
            View.AddSubview(flipButton);
        }
コード例 #54
0
        public MapViewController()
            : base()
        {
            BuildView();

            NavigationItem.Title = "Map";

            segmentControl = new UISegmentedControl(new RectangleF(0,0,200,25));
            segmentControl.InsertSegment("Find bikes", 0, false);
            segmentControl.InsertSegment("Find docks", 1, false);
            segmentControl.SelectedSegment = 0;
            segmentControl.ControlStyle = UISegmentedControlStyle.Bar;
            segmentControl.ValueChanged += delegate(object sender, EventArgs e) {
                if (segmentControl.SelectedSegment == 0)
                {
                    CurrentDisplayMode = DisplayMode.Bikes;
                    Analytics.TrackEvent(Analytics.CATEGORY_ACTION, Analytics.ACTION_MAP_BIKES, "", 1);
                } else
                {
                    CurrentDisplayMode = DisplayMode.Docks;
                    Analytics.TrackEvent(Analytics.CATEGORY_ACTION, Analytics.ACTION_MAP_DOCKS, "", 1);
                }

                RefreshPinColours();

                BikeLocation.UpdateFromWebsite(delegate {
                        InvokeOnMainThread(delegate{
                            RefreshPinColours();
                            //RefreshData();
                        });
                    });
            };

            NavigationItem.TitleView = segmentControl;

            NavigationItem.LeftBarButtonItem = new UIBarButtonItem(Resources.Routing, UIBarButtonItemStyle.Bordered, delegate {

                //nulls, think about the nulls!

                if (!CLLocationManager.LocationServicesEnabled)
                {
                    alert = new UIAlertView("No Location Available", "Sorry, no location services are available. However, you may still be able to use the timer and map.", null, "Ok");
                    alert.Show();
                    return;
                }

                if (mapView.UserLocation == null || mapView.UserLocation.Location == null)
                {
                    alert = new UIAlertView("No Location Available", "Sorry, your location is not yet available.", null, "Ok");
                    alert.Show();
                    return;
                }

                NSObject[] selectedPins = mapView.SelectedAnnotations;

                if (selectedPins == null || selectedPins.Length > 1)
                {
                    alert = new UIAlertView("Select a dock", "Please pick a cycle docking station to route to.", null, "Ok");
                    alert.Show();
                    return;
                }

                if (selectedPins.Length == 1)
                {
                    CycleAnnotation ca = selectedPins[0] as CycleAnnotation;
                    if (ca != null)
                    {
                        HideDistanceView();

                        var location = mapView.UserLocation.Location.Coordinate;
            #if DEBUG
                    location = Locations.BanksideMix;
            #endif

                        double distance = BikeLocation.CalculateDistanceInMeters(location, ca.Coordinate);
                        if (distance > 50000)
                        {
                            alert = new UIAlertView("Sorry, your route is too long", "We can only plot cycle routes up to 50km.", null, "Ok");
                            alert.Show();

                            return;
                        }

                        loadingView = new ActivityIndicatorLoadingView();
                        loadingView.Show("Finding your route");
                        Util.TurnOnNetworkActivity();

                        RemoveRouteAnnotation();

                        ThreadPool.QueueUserWorkItem(delegate {

                            using (NSAutoreleasePool newPool = new NSAutoreleasePool())
                            {
                                location = mapView.UserLocation.Location.Coordinate;
            #if DEBUG
                    location = Locations.BanksideMix;
            #endif

                                MapRouting routing = new MapRouting(location, ca.Coordinate);

                                //routing.FindRoute(delegate {
                                routing.FindRoute(delegate {
                                    InvokeOnMainThread(delegate {
                                        //Console.WriteLine("updating");
                                        loadingView.Hide();
                                        Util.TurnOffNetworkActivity();
                                        if (routing.HasRoute)
                                        {

                                            routeAnnotation = new CSRouteAnnotation(routing.PointsList);
                                            mapView.AddAnnotation(routeAnnotation);

                                            var region = routeAnnotation.Region;

                                            region.Span = new MKCoordinateSpan(region.Span.LatitudeDelta * 1.1f, region.Span.LongitudeDelta * 1.1f);

                                            mapView.SetRegion(region, true);

                                            //need to animate the distance etc here.

                                            ShowDistanceView(routing.DistanceForDisplay, routing.TimeForDisplay);

                                            BikeLocation.LogRoute();

                                        } else {
                                            alert = new UIAlertView("No route found", "Sorry, no route could be found or the route is too long.", null, "Ok");
                                            alert.Show();

                                        }
                                    });
                                });

                            }

                        });

                    }
                }
            });

            //NavigationController.NavigationBar.TintColor = Resources.DarkBlue;
            gpsButton = new UIBarButtonItem(Resources.Gps, UIBarButtonItemStyle.Bordered, delegate {

                if (!CLLocationManager.LocationServicesEnabled)
                {
                    alert = new UIAlertView("No Location Available", "Sorry, no location services are available. However, you may still be able to use the timer and map.", null, "Ok");
                    alert.Show();
                    return;
                }

                if (mapView.UserLocation != null)
                {
                    if (mapView.UserLocation.Location != null)
                    {
                        //NavigationItem.RightBarButtonItem = activityButton;

                        BikeLocation.UpdateFromWebsite(delegate {
                        InvokeOnMainThread(delegate{
                                RefreshPinColours();
                                //NavigationItem.RightBarButtonItem = gpsButton;
                            });
                        });

                        CLLocationCoordinate2D location = mapView.UserLocation.Location.Coordinate;
            #if DEBUG
                    location = Locations.BanksideMix;
            #endif
                        MKCoordinateRegion region = new MKCoordinateRegion(location, new MKCoordinateSpan(0.01, 0.01));

                        region = mapView.RegionThatFits(region);
                        mapView.SetRegion(region, true);

                    }
                }
            });

            NavigationItem.RightBarButtonItem = gpsButton;
        }
コード例 #55
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();
            mapView = new MKMapView()
            {
                ShowsUserLocation = true
            };

            labelDistance = new UILabel()
            {
                Frame = new RectangleF (0, 0, 320, 49),
                Lines = 2,
                BackgroundColor = UIColor.Black,
                TextColor = UIColor.White
            };

            var segmentedControl = new UISegmentedControl();
            var topOfSegement = View.Frame.Height - 120;
            segmentedControl.Frame = new RectangleF(20, topOfSegement, 282, 30);
            segmentedControl.InsertSegment("Map".GetText(), 0, false);
            segmentedControl.InsertSegment("Satellite".GetText(), 1, false);
            segmentedControl.InsertSegment("Hybrid".GetText(), 2, false);
            segmentedControl.SelectedSegment = 0;
            segmentedControl.ControlStyle = UISegmentedControlStyle.Bar;
            segmentedControl.TintColor = UIColor.DarkGray;

            segmentedControl.ValueChanged += delegate {
                if (segmentedControl.SelectedSegment == 0)
                    mapView.MapType = MonoTouch.MapKit.MKMapType.Standard;
                else if (segmentedControl.SelectedSegment == 1)
                    mapView.MapType = MonoTouch.MapKit.MKMapType.Satellite;
                else if (segmentedControl.SelectedSegment == 2)
                    mapView.MapType = MonoTouch.MapKit.MKMapType.Hybrid;
            };

            mapView.Delegate = new MapViewDelegate(this);

            // Set the web view to fit the width of the app.
            mapView.SizeToFit();

            // Reposition and resize the receiver
            mapView.Frame = new RectangleF (0, 50, View.Frame.Width, View.Frame.Height - 100);

            MKCoordinateSpan span = new MKCoordinateSpan(0.01,0.01);
            MKCoordinateRegion region = new MKCoordinateRegion(ConferenceLocation,span);
            mapView.SetRegion(region, true);

            ConferenceAnnotation a = new ConferenceAnnotation(ConferenceLocation
                                , "CodeCampSDQ"
                                , "INTEC"
                              );
            mapView.AddAnnotationObject(a);

            locationManager = new CLLocationManager();
            locationManager.Delegate = new LocationManagerDelegate(mapView, this);
            locationManager.StartUpdatingLocation();

            // Add the table view as a subview
            View.AddSubview(mapView);
            View.AddSubview(labelDistance);
            View.AddSubview(segmentedControl);

            // Add the 'info' button to flip
            var flipButton = UIButton.FromType(UIButtonType.InfoLight);
            flipButton.Frame = new RectangleF(290,17,20,20);
            flipButton.Title (UIControlState.Normal);
            flipButton.TouchDown += delegate {
                _mfvc.Flip();
            };
            View.AddSubview(flipButton);
        }
コード例 #56
0
ファイル: MapRenderer.cs プロジェクト: ytn3rd/Xamarin.Forms
		void MoveToRegion(MapSpan mapSpan, bool animated = true)
		{
			Position center = mapSpan.Center;
			var mapRegion = new MKCoordinateRegion(new CLLocationCoordinate2D(center.Latitude, center.Longitude), new MKCoordinateSpan(mapSpan.LatitudeDegrees, mapSpan.LongitudeDegrees));
			((MKMapView)Control).SetRegion(mapRegion, animated);
		}
コード例 #57
0
		private void RepositionMapAndInit(CLLocation newLocation)
		{
			try
			{
				InitList();
				
				double maxLat = - 1000, minLat = 1000, maxLong = -1000, minLong = 1000;
				foreach (ImageInfo imgInfo in _list)
				{
					if (imgInfo.Img != null)
					{
						Image img = imgInfo.Img;
						if (img.Latitude > maxLat)
							maxLat = img.Latitude;
						if (img.Latitude < minLat)
							minLat = img.Latitude;
						
						if (img.Longitude > maxLong)
							maxLong = img.Longitude;
						if (img.Longitude < minLong)
							minLong = img.Longitude;
					}
				}
				
				double d = 0.02;
				double zoomLevel = 30;
				if (minLat == 1000)
				{
					maxLat = d;
					minLat = 0.0;
					maxLong = d;
					minLong = 0.0;
				}
				zoomLevel = Math.Max(maxLat - minLat, maxLong - minLong);				
				
				minLat -= d * zoomLevel;
				maxLat += d * zoomLevel;
				minLong -= d * zoomLevel;
				maxLong += d * zoomLevel;
				
				double latDelta = Math.Max(maxLat - minLat, d);
				double longDelta = Math.Max(maxLong - minLong, d);				
				
				MKCoordinateSpan spanLocal = _MaplocationRequest.LocType == LocalisationType.Global ?					
					new MKCoordinateSpan (latDelta, longDelta) : new MKCoordinateSpan (d, d);
								
				if (newLocation != null)
				{
					var region = new MKCoordinateRegion (newLocation.Coordinate, spanLocal);
					
					this.InvokeOnMainThread(()=>
					{									
						mapView.SetRegion (region, false);
						mapView.SetCenterCoordinate (newLocation.Coordinate, false);				
					});
				}
				else
				{
					var location = new CLLocationCoordinate2D(minLat + latDelta / 2, minLong + longDelta /2);
					var region = new MKCoordinateRegion (location, spanLocal);
					
					this.InvokeOnMainThread(()=>
					{						
						mapView.SetRegion (region, false);
						mapView.SetCenterCoordinate (location, false);
					});
				}
	
				this.InvokeOnMainThread(()=>
				{
					scrollView.ContentSize = new System.Drawing.SizeF (img_cnt * w, h);				
						
					foreach (ImageInfo imageInfo in _list)
					{
						AddImageWithName (imageInfo);
					}
					scrollView.SetNeedsLayout();
				});
			}
			catch (Exception ex)
			{
				Util.LogException("RepositionMapAndInit", ex);
			}			      
		}
コード例 #58
0
		public void SetLocation(CLLocation newLocation, string title, string description)
		{
			if(_mapview.Annotations.Contains(CurrentAnnotation))
			{
				_mapview.RemoveAnnotation(CurrentAnnotation);	
			}
	        MKCoordinateSpan span = new MKCoordinateSpan(0.010, 0.010);
	        MKCoordinateRegion region = new MKCoordinateRegion(newLocation.Coordinate, span);
	        
	        _mapview.SetRegion(region, true);
			
			if(CurrentAnnotation == null)
				CurrentAnnotation = new MyAnnotation(new CLLocationCoordinate2D(newLocation.Coordinate.Latitude, 
				                                                            newLocation.Coordinate.Longitude), 
											                                 title, 
											                                 description);
			else
			{
				CurrentAnnotation.Coordinate = newLocation.Coordinate;
			}
			_mapview.AddAnnotation(CurrentAnnotation);
			_mapview.SelectAnnotation(CurrentAnnotation, false);
		}
コード例 #59
0
ファイル: Airports.cs プロジェクト: jcaudill/FlightLog
        /// <summary>
        /// Gets a list of all airports in the specified map region.
        /// </summary>
        /// <returns>
        /// A list of all airports in the specified map region.
        /// </returns>
        /// <param name='region'>
        /// The map region.
        /// </param>
        public static List<Airport> GetAirports(MKCoordinateRegion region)
        {
            double longMin = region.Center.Longitude - region.Span.LongitudeDelta / 2.0;
            double longMax = region.Center.Longitude + region.Span.LongitudeDelta / 2.0;
            double latMin = region.Center.Latitude - region.Span.LatitudeDelta / 2.0;
            double latMax = region.Center.Latitude + region.Span.LatitudeDelta / 2.0;

            return sqlitedb.Query<Airport> ("select * from Airport where Latitude between ? and ? and Longitude between ? and ?",
                latMin, latMax, longMin, longMax);
        }
コード例 #60
0
        public void BuildView()
        {
            if (mapView == null)
            {

                mapView = new MKMapView();
                RectangleF frame = new RectangleF(0,0,320,367);

                mapView.Frame = frame;

                DV = new DistanceView();

                frame = DV.View.Frame;
                //frame.Y = mapView.Frame.Bottom;
                frame.Y = -DV.View.Frame.Height;

                DV.View.Frame = frame;

                DV.TouchUpInside += delegate(object sender, EventArgs e) {

                    RemoveRouteAnnotation();

                    HideDistanceView();
                };

                mapView.RegionWillChange += delegate(object sender, MKMapViewChangeEventArgs e) {
                    if (routeView != null)
                    {
                        routeView.Hidden = true;
                    }
                };

                mapView.RegionChanged += delegate(object sender, MKMapViewChangeEventArgs e) {
                    if (routeView != null)
                    {
                        routeView.Hidden = false;
                        routeView.RegionChanged();
                    }
                };

                mapView.GetViewForAnnotation = delegate(MKMapView mapViewForAnnotation, NSObject annotation) {
                    if (annotation is MKUserLocation) return null;

                    if (annotation is CycleAnnotation)
                    {
                        var mapAnnotation = annotation as CycleAnnotation;
                        if (mapAnnotation == null) return null;

                        MKPinAnnotationView pinView = (MKPinAnnotationView)mapViewForAnnotation.DequeueReusableAnnotation(MapPin);
                        if (pinView == null)
                        {
                            pinView = new MKPinAnnotationView(mapAnnotation, MapPin);
                        } else {
                            pinView.Annotation = annotation;
                        }

                        int valueToCheck = 0;
                        if (CurrentDisplayMode == DisplayMode.Bikes)
                        {
                            valueToCheck = mapAnnotation.Bike.BikesAvailable;
                        } else {
                            valueToCheck = mapAnnotation.Bike.DocksAvailable;
                        }

                        if ((valueToCheck < 5 && valueToCheck != -1)) {
                            if (valueToCheck == 0)
                            {
                                pinView.PinColor = MKPinAnnotationColor.Red;
                            } else {
                                pinView.PinColor = MKPinAnnotationColor.Purple;
                            }
                        } else {
                            pinView.PinColor = MKPinAnnotationColor.Green;
                        }

                        mapAnnotation.PinView = pinView;

                        pinView.CanShowCallout = true;
                        return pinView;
                    }

                    if (annotation is CSRouteAnnotation)
                    {
                        var routeAnnotation = annotation as CSRouteAnnotation;
                        MKAnnotationView annotationView = null;

                        if (annotationView == null)
                        {
                            routeView = new CSRouteView(new RectangleF (0,0, mapView.Frame.Size.Width, mapView.Frame.Size.Height));
                            routeView.Annotation = routeAnnotation;
                            routeView.MapView = mapViewForAnnotation;
                            annotationView = routeView;
                        }

                        return annotationView;
                    }

                    return null;

                };

                List<MKAnnotation> locations = new List<MKAnnotation>();

                double minLon = 200, minLat = 200, maxLon = -200, maxLat = -200;

                foreach(var bike in BikeLocation.AllBikes)
                {
                    if (bike.Location.Longitude < minLon) minLon = bike.Location.Longitude;
                    if (bike.Location.Latitude < minLat) minLat = bike.Location.Latitude;

                    if (bike.Location.Longitude < maxLon) maxLon = bike.Location.Longitude;
                    if (bike.Location.Latitude > maxLat) maxLat = bike.Location.Latitude;

                    locations.Add(new CycleAnnotation(bike));
                }

                if (locations.Count > 0)
                {
                    mapView.AddAnnotation(locations.ToArray());

                    var tl = new CLLocationCoordinate2D(-90, 180);
                    var br = new CLLocationCoordinate2D(90, -180);

                    foreach(MKAnnotation an in mapView.Annotations)
                    {
                        tl.Longitude = Math.Min(tl.Longitude, an.Coordinate.Longitude);
                        tl.Latitude = Math.Max(tl.Latitude, an.Coordinate.Latitude);

                        br.Longitude = Math.Max(br.Longitude, an.Coordinate.Longitude);
                        br.Latitude = Math.Min(br.Latitude, an.Coordinate.Latitude);

                    }

                    var center = new CLLocationCoordinate2D {
                        Latitude = tl.Latitude - (tl.Latitude - br.Latitude) *0.5,
                        Longitude = tl.Longitude - (tl.Longitude - br.Longitude) *0.5
                    };

                    var span = new MKCoordinateSpan
                    {
                        LatitudeDelta = Math.Abs(tl.Latitude - br.Latitude) *0.5,
                        LongitudeDelta = Math.Abs(tl.Longitude - br.Longitude) *0.5

                    };

                    MKCoordinateRegion region = new MKCoordinateRegion (center, span );

                    region = mapView.RegionThatFits(region);

                    mapView.SetRegion(region, true);
                }

                mapView.ShowsUserLocation = true;

                View.AddSubview(mapView);
            }
        }