Beispiel #1
0
		public void Start ()
		{
			if (CLLocationManager.LocationServicesEnabled) {
				lman = new CLLocationManager {
					DesiredAccuracy = CLLocation.AccuracyBest,
				};

				lman.RequestWhenInUseAuthorization ();

				lman.LocationsUpdated += (sender, e) => {
					var loc = e.Locations [0];
					Timestamp = loc.Timestamp;
					Location = new Location (loc.Coordinate.Latitude, loc.Coordinate.Longitude, loc.Altitude);
//					Console.WriteLine (Location);
					HorizontalAccuracy = loc.HorizontalAccuracy;
					VerticalAccuracy = loc.VerticalAccuracy;
					LocationReceived (this, EventArgs.Empty);
				};

				lman.UpdatedHeading += (sender, e) => {
					Heading = e.NewHeading.TrueHeading;
//					Console.WriteLine ("Heading: {0}", Heading);
				};

				lman.StartUpdatingLocation ();
				lman.StartUpdatingHeading ();
			}
		}
		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			window = new UIWindow (UIScreen.MainScreen.Bounds);

			var what = new EntryElement ("What ?", "e.g. pizza", String.Empty);
			var where = new EntryElement ("Where ?", "here", String.Empty);

			var section = new Section ();
			if (CLLocationManager.LocationServicesEnabled) {
				lm = new CLLocationManager ();
				lm.LocationsUpdated += delegate (object sender, CLLocationsUpdatedEventArgs e) {
					lm.StopUpdatingLocation ();
					here = e.Locations [e.Locations.Length - 1];
					var coord = here.Coordinate;
					where.Value = String.Format ("{0:F4}, {1:F4}", coord.Longitude, coord.Latitude);
				};
				section.Add (new StringElement ("Get Current Location", delegate {
					lm.StartUpdatingLocation ();
				}));
			}

			section.Add (new StringElement ("Search...", async delegate {
				await SearchAsync (what.Value, where.Value);
			}));

			var root = new RootElement ("MapKit Search Sample") {
				new Section ("MapKit Search Sample") { what, where },
				section
			};
			window.RootViewController = new UINavigationController (new DialogViewController (root, true));
			window.MakeKeyAndVisible ();
			return true;
		}
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            int speedSystem = 0;

            kmhourButton.ValueChanged += (sender,e) => {
                speedSystem = kmhourButton.SelectedSegment;
            };

            _iPhoneLocationManager = new CLLocationManager ();
            _iPhoneLocationManager.DesiredAccuracy = 1000; // 1000 meters/1 kilometer

            //update location based on the specified metric system
            _iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                UpdateLocation (speedSystem, e.Locations [e.Locations.Length - 1].Speed);
            };

            if (CLLocationManager.LocationServicesEnabled)
                _iPhoneLocationManager.StartUpdatingLocation ();

            //if viewmap button is touched then display the map
            ViewMap.TouchUpInside += (object sender, EventArgs e) => {
                if (_speedController == null)
                    _speedController = new SpeedController();
                    //_speedController = new MapController();
                NavigationController.PushViewController(_speedController, true);
            };
        }
Beispiel #4
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            global::Xamarin.FormsMaps.Init();

            locationManager = new CLLocationManager
            {
                DesiredAccuracy = CLLocation.AccuracyBest
            };

            locationManager.Failed += (object sender, NSErrorEventArgs e) =>
            {
                var alert = new UIAlertView(){ Title = "Location manager failed", Message = "The location updater has failed" };
                alert.Show();
                locationManager.StopUpdatingLocation();
            };

            locationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) =>
            {
                var newloc = string.Format("{0},{1}", e.Locations[0].Coordinate.Longitude, e.Locations[0].Coordinate.Latitude);
                App.Self.ChangedClass.BroadcastIt("location", newloc);
            };

            locationManager.StartUpdatingLocation();

            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
Beispiel #5
0
        /// <summary>
        /// get the location of user and update to server
        /// </summary>
        public static void DoLocationAndUpdated()
        {
            Location.iPhoneLocationManager = new CLLocationManager ();
            Location.iPhoneLocationManager.DesiredAccuracy = 5; // 1000 meters/1 kilometer
            // if this is iOs6
            if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
                Location.iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                    CLLocation newLocation = e.Locations [e.Locations.Length - 1];
                    Utils.Log("ios6");
                    Location.UpdateLocationToServer(newLocation.Coordinate.Latitude.ToString (), newLocation.Coordinate.Longitude.ToString ());
                    //iPhoneLocationManager.StopUpdatingLocation();
                };
            }
            // if it is iOs 5 or lower
            else {
                Location.iPhoneLocationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => {
                    CLLocation newLocation =  e.NewLocation;
                    Utils.Log("ios5");
                    Location.UpdateLocationToServer(newLocation.Coordinate.Latitude.ToString (), newLocation.Coordinate.Longitude.ToString ());
                    //iPhoneLocationManager.StopUpdatingLocation();
                };
            }

            if (CLLocationManager.LocationServicesEnabled) iPhoneLocationManager.StartUpdatingLocation ();
        }
 public static void RequestLocation(Action<CLLocation> callback)
 {
     locationManager = new CLLocationManager () {
         DesiredAccuracy = CLLocation.AccuracyBest,
         Delegate = new MyCLLocationManagerDelegate (callback),
         DistanceFilter = 1000f
     };
     if (CLLocationManager.LocationServicesEnabled)
         locationManager.StartUpdatingLocation ();
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            // Perform any additional setup after loading the view, typically from a nib.
            iPhoneLocationManager = new CLLocationManager();
            iPhoneLocationManager.Delegate = new LocationDelegate(this);

            iPhoneLocationManager.StartUpdatingLocation();
            iPhoneLocationManager.StartUpdatingHeading();
        }
Beispiel #8
0
		public static void Initialize()
		{
			CoreLocationManager = new CLLocationManager();
			
			CoreLocationManager.StartUpdatingLocation();
			
			CoreLocationManager.UpdatedHeading += HandleCoreLocationManagerUpdatedHeading;
			CoreLocationManager.UpdatedLocation += HandleCoreLocationManagerUpdatedLocation;
			
			UpdateLocationTimer = NSTimer.CreateRepeatingTimer(TimeSpan.FromMinutes(1), InitializeLocationUpdate);
			UpdateHeadingTimer =NSTimer.CreateRepeatingTimer(TimeSpan.FromMinutes(1), InitializeHeadingUpdate);
		}
		public LocationPrivacyManager ()
		{
			locationManager = new CLLocationManager ();

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

			locationManager.Failed += OnFailed;
			locationManager.LocationsUpdated += OnLocationsUpdated;
			locationManager.AuthorizationChanged += OnAuthorizationChanged;
		}
        protected override void PlatformSpecificStart(MvxLocationOptions options)
        {
            lock (this)
            {
                if (_locationManager != null)
                    throw new MvxException("You cannot start the MvxLocation service more than once");

                _locationManager = new CLLocationManager();
                _locationManager.Delegate = new LocationDelegate(this);

                if (options.MovementThresholdInM > 0)
                {
                    _locationManager.DistanceFilter = options.MovementThresholdInM;
                }
                else
                {
                    _locationManager.DistanceFilter = CLLocationDistance.FilterNone;
                }
                _locationManager.DesiredAccuracy = options.Accuracy == MvxLocationAccuracy.Fine ? CLLocation.AccuracyBest : CLLocation.AccuracyKilometer;
                if (options.TimeBetweenUpdates > TimeSpan.Zero)
                {
                    Mvx.Warning("TimeBetweenUpdates specified for MvxLocationOptions - but this is not supported in iOS");
                }


				if (options.TrackingMode == MvxLocationTrackingMode.Background)
				{
					if (IsIOS8orHigher)
					{
						_locationManager.RequestAlwaysAuthorization ();
					}
					else
					{
						Mvx.Warning ("MvxLocationTrackingMode.Background is not supported for iOS before 8");
					}
				}
				else
				{
					if (IsIOS8orHigher)
					{
						_locationManager.RequestWhenInUseAuthorization ();
					}
				}

                if (CLLocationManager.HeadingAvailable)
                    _locationManager.StartUpdatingHeading();

                _locationManager.StartUpdatingLocation();
            }
        }
        protected override void PlatformSpecificStart(MvxGeoLocationOptions options)
        {
            lock (this)
            {
                if (_locationManager != null)
                    throw new MvxException("You cannot start the MvxLocation service more than once");

                _locationManager = new CLLocationManager();
                _locationManager.Delegate = new LocationDelegate(this);

                //_locationManager.DesiredAccuracy = options.EnableHighAccuracy ? Accuracy.Fine : Accuracy.Coarse;
                _locationManager.StartUpdatingLocation();
            }
        }
		public override void ViewDidLoad ()
		{
			// all your base
			base.ViewDidLoad ();
			
			// load the appropriate view, based on the device type
			this.LoadViewForDevice ();

			// initialize our location manager and callback handler
			iPhoneLocationManager = new CLLocationManager ();
			
			// uncomment this if you want to use the delegate pattern:
			//locationDelegate = new LocationDelegate (mainScreen);
			//iPhoneLocationManager.Delegate = locationDelegate;
			
			// you can set the update threshold and accuracy if you want:
			//iPhoneLocationManager.DistanceFilter = 10; // move ten meters before updating
			//iPhoneLocationManager.HeadingFilter = 3; // move 3 degrees before updating
			
			// you can also set the desired accuracy:
			iPhoneLocationManager.DesiredAccuracy = 1000; // 1000 meters/1 kilometer
			// you can also use presets, which simply evalute to a double value:
			//iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;
			
			// handle the updated location method and update the UI
			if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
				iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
					UpdateLocation (mainScreen, e.Locations [e.Locations.Length - 1]);
				};
			} else {
				// this won't be called on iOS 6 (deprecated)
				iPhoneLocationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => {
					UpdateLocation (mainScreen, e.NewLocation);
				};
			}
			
			// handle the updated heading method and update the UI
			iPhoneLocationManager.UpdatedHeading += (object sender, CLHeadingUpdatedEventArgs e) => {
				mainScreen.LblMagneticHeading.Text = e.NewHeading.MagneticHeading.ToString () + "º";
				mainScreen.LblTrueHeading.Text = e.NewHeading.TrueHeading.ToString () + "º";
			};
			
			// start updating our location, et. al.
			if (CLLocationManager.LocationServicesEnabled)
				iPhoneLocationManager.StartUpdatingLocation ();
			if (CLLocationManager.HeadingAvailable)
				iPhoneLocationManager.StartUpdatingHeading ();
		}
Beispiel #13
0
		public void StartLocationManager()
		{
			LocationManager = new CLLocationManager();

			//if (LocationManager.RespondsToSelector(new MonoTouch.ObjCRuntime.Selector("requestWhenInUseAuthorization")))
				LocationManager.RequestWhenInUseAuthorization();

			LocationManager.DistanceFilter = CLLocationDistance.FilterNone;
			LocationManager.DesiredAccuracy = CLLocation.AccuracyBest;
			LocationManager.LocationsUpdated += LocationManager_LocationsUpdated;
			LocationManager.StartUpdatingLocation();


			_isTracking = true;

			System.Diagnostics.Debug.WriteLine("Location manager started ");
		}
		#pragma warning disable 0618
		public void StartLocationUpdates ()
		{
			// We need the user's permission for our app to use the GPS in iOS. This is done either by the user accepting
			// the popover when the app is first launched, or by changing the permissions for the app in Settings

			if (CLLocationManager.LocationServicesEnabled) {

                LocMgr = new CLLocationManager();
				LocMgr.DesiredAccuracy = 1; // sets the accuracy that we want in meters

                // Handle the LocationsUpdated event which is sent with >= iOS6 to indicate
                // our location (position) has changed.  
                if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
                {
                    LocMgr.LocationsUpdated += (sender, e) =>
                    {
                        // fire our custom Location Updated event
                        LocationUpdated(this, new LocationUpdatedEventArgs(e.Locations[e.Locations.Length - 1]));
                    };
                }
                // <= iOS5 used UpdatedLocation which has been deprecated.
                else
                {
                    // This generates a warning.
                    LocMgr.UpdatedLocation += (sender, e) =>
                    {
                        // fire our custom Location Updated event
                        LocationUpdated(this, new LocationUpdatedEventArgs(e.NewLocation));
                    };
                }

				// Start our location updates
				LocMgr.StartUpdatingLocation ();

				// Get some output from our manager in case of failure
				LocMgr.Failed += (sender, e) =>
                {
                    Console.WriteLine("LocationManager failed: {0}", e.Error);
                }; 
				
			} else {

				//Let the user know that they need to enable LocationServices
				Console.WriteLine ("Location services not enabled, please enable this in your Settings");
			}
		}
Beispiel #15
0
	static void Main ()
	{
		NSApplication.Init ();
		
		var locationManager = new CLLocationManager ();
		locationManager.UpdatedLocation += (sender, args) => {
			var coord = args.NewLocation.Coordinate;
			Console.WriteLine ("At {0}", args.NewLocation.Description ());
			locationManager.StopUpdatingLocation ();

			Console.WriteLine (googleUrl, coord.Latitude, coord.Longitude);
			NSWorkspace.SharedWorkspace.OpenUrl (new Uri (String.Format (googleUrl, coord.Latitude, coord.Longitude)));
			
		};
		locationManager.StartUpdatingLocation ();
		NSRunLoop.Current.RunUntil (NSDate.DistantFuture);
	}
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear (animated);

            locationManager = new CLLocationManager ();
            locationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;

            locationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {

                poiData = GeoUtils.GetPoiInformation(e.Locations [e.Locations.Length -1], 20);
                var js = "World.loadPoisFromJsonData(" + this.poiData.ToString() + ")";
                this.arView.CallJavaScript(js);

                locationManager.StopUpdatingLocation();
                locationManager.Delegate = null;
            };
            locationManager.StartUpdatingLocation ();
        }
		public override void ViewDidAppear (bool animated)
		{
			base.ViewDidAppear (animated);

			CLLocationManager locationManager = new CLLocationManager ();
			locationManager.LocationsUpdated += (sender, e) => {
				CLLocation location = locationManager.Location;
				FlurryAgent.SetLocation (
					location.Coordinate.Latitude,
					location.Coordinate.Longitude,
					(float)location.HorizontalAccuracy,
					(float)location.VerticalAccuracy);
				locationManager.StopUpdatingLocation ();

				Debug.WriteLine ("Logged location.");
			};
			locationManager.StartUpdatingLocation ();
		}
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            locMgr = new CLLocationManager();
            locMgr.RequestWhenInUseAuthorization();

            button.TouchUpInside += (s, _) =>
            {
                locMgr.DesiredAccuracy = 1000;
                locMgr.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) =>
                {
                    var location = e.Locations[e.Locations.Length - 1];
                    LatText.Text = "Latitude: " + location.Coordinate.Latitude.ToString();
                    LonText.Text = "Longitude: " + location.Coordinate.Longitude.ToString();
                };
                locMgr.StartUpdatingLocation();
            };
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            var newYorkCity = new CLLocationCoordinate2D(40.716667, -74);

            Map.CenterCoordinate = newYorkCity;
            Map.Region = MKCoordinateRegion.FromDistance(newYorkCity, 5000, 5000);

            var annotation = new MapAnnotation("New York City", newYorkCity);
            Map.AddAnnotation(annotation);

            _locationManager = new CLLocationManager();
            _locationManager.UpdatedLocation += locationUpdated;
            _locationManager.DistanceFilter = 20;
            _locationManager.DesiredAccuracy = CLLocation.AccuracyHundredMeters;

            _locationManager.StartUpdatingLocation();
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			map.GetViewForAnnotation = (mapView, annotation) => {
				return new MKPinAnnotationView (annotation, string.Empty) {
					Draggable = true
				};
			};

			locationManager = new CLLocationManager {
				DistanceFilter = CLLocationDistance.FilterNone,
				DesiredAccuracy = CLLocation.AccuracyBest,
			};

			locationManager.LocationsUpdated += OnLocationsUpdated;

			locationManager.RequestAlwaysAuthorization ();
			locationManager.StartUpdatingLocation ();
		}
Beispiel #21
0
        public void StartListeningForBeacons()
        {
            beaconRegion = new CLBeaconRegion (beaconUUID, "0");
            locationManager = new CLLocationManager ();

            locationManager.Failed += (object sender, NSErrorEventArgs e) => {
                Console.WriteLine ("Failure " + e.ToString ());
            };

            locationManager.DidRangeBeacons += (object sender, CLRegionBeaconsRangedEventArgs args) => {
                List<Beacon> foundBeacons = new List<Beacon> ();

                foreach (CLBeacon clBeacon in args.Beacons) {
                    foundBeacons.Add(new Beacon() { Major = clBeacon.Major.Int32Value, Minor = clBeacon.Minor.Int32Value, Proximity = clBeacon.Proximity, Accuracy = clBeacon.Accuracy });
                }
                this.BeaconsFound (this, new BeaconFoundEventArgs (foundBeacons));
            };
            locationManager.StartRangingBeacons (beaconRegion);
            locationManager.StartUpdatingLocation ();
        }
        protected override void PlatformSpecificStart(MvxGeoLocationOptions options)
        {
            lock (this)
            {
                if (_locationManager != null)
                    throw new MvxException("You cannot start the MvxLocation service more than once");

                _locationManager = new CLLocationManager();
                _locationManager.Delegate = new LocationDelegate(this);

                // more needed here for more filtering
                // _locationManager.DistanceFilter = options. CLLocationDistance.FilterNone

                _locationManager.DesiredAccuracy = options.EnableHighAccuracy ? CLLocation.AccuracyBest : CLLocation.AccuracyKilometer;

                if (CLLocationManager.HeadingAvailable)
                    _locationManager.StartUpdatingHeading();

                _locationManager.StartUpdatingLocation();
            }
        }
		public ScreenController (AppDelegate appDelegate, Cartridge cart, Boolean restore)
		{
			// Save for later use
			this.appDelegate = appDelegate;
			this.cart = cart;
			this.restore = restore;

			// Set color of NavigationBar and NavigationButtons (TintColor)
			if (new Version (UIDevice.CurrentDevice.SystemVersion) >= new Version(7,0)) 
				NavigationBar.SetBackgroundImage (Images.BlueTop, UIBarMetrics.Default);
			else
				NavigationBar.SetBackgroundImage (Images.Blue, UIBarMetrics.Default);

			// Create Location Manager
			locationManager = new CLLocationManager ();
			locationManager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation;
			if (CLLocationManager.LocationServicesEnabled) {
				locationManager.StartUpdatingLocation ();
			}

			// Now check, if location is accurate enough
			checkLocation = new CheckLocation(this, locationManager);
			PushViewController (checkLocation, true);
		}
Beispiel #24
0
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            locationManager = new CLLocationManager();
            locationManager.DesiredAccuracy = 1;

            if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
            {
                locationManager.LocationsUpdated += delegate(object sender, CLLocationsUpdatedEventArgs e) {
                    int pos = e.Locations.Length - 1;

                    LocationUtility.CurrentLocation = new LatLongCoordinate(e.Locations[pos].Coordinate.Latitude, e.Locations[pos].Coordinate.Longitude);
                };
            }
            else
            {
                locationManager.UpdatedLocation += delegate(object sender, CLLocationUpdatedEventArgs e) {
                    LocationUtility.CurrentLocation = new LatLongCoordinate(e.NewLocation.Coordinate.Latitude, e.NewLocation.Coordinate.Longitude);
                };
            }

            locationManager.Failed += delegate(object sender, NSErrorEventArgs e) {
                Console.WriteLine("Location Manager Failed");
            };

            locationManager.StartUpdatingLocation();

            window = new UIWindow(UIScreen.MainScreen.Bounds);

            mainDvc = new MainDialogViewController();
            navigationController =  new UINavigationController(mainDvc);

            window.AddSubview (navigationController.View);
            window.MakeKeyAndVisible ();

            return true;
        }
        public void ExecuteLocationManager(bool IncludeHeading = false)
        {
            locationManager = new CLLocationManager();
            locationManager.AuthorizationChanged += (NSURLAuthenticationChallengeSender, args) =>
            {
            };
            locationManager.DesiredAccuracy = 1000;

            locationManager.ShouldDisplayHeadingCalibration += (CLLocationManager manager) => { return(IncludeHeading && !CLLocationManager.HeadingAvailable); };

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                locationManager.RequestWhenInUseAuthorization();
            }

            if (CLLocationManager.LocationServicesEnabled)
            {
                locationManager.StartUpdatingLocation();
            }
            if (IncludeHeading && CLLocationManager.HeadingAvailable)
            {
                locationManager.StartUpdatingHeading();
            }
        }
        public async Task <GeoCoords> PullCoordinatesAsync()
        {
            var locationManager = new CLLocationManager();

            _locationTaskCompletion = new TaskCompletionSource <CLLocation>();

            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                locationManager.RequestWhenInUseAuthorization();
            }

            locationManager.LocationsUpdated += OnLocationUpdated;

            locationManager.StartUpdatingLocation();

            var location = await _locationTaskCompletion.Task;

            var result = new GeoCoords
            {
                Latitude = location.Coordinate.Latitude, Longitude = location.Coordinate.Longitude
            };

            return(result);
        }
Beispiel #27
0
        public async Task Start()
        {
            var result = await BeaconsUtil.RequestPermissionAsync();

            if (!result)
            {
                return;
            }

            _locationMgr.DidRangeBeacons   += HandleDidRangeBeacons;
            _locationMgr.DidDetermineState += HandleDidDetermineState;
            _locationMgr.PausesLocationUpdatesAutomatically = false;
            _locationMgr.StartUpdatingLocation();

            beacon_operations_queue.DispatchAsync(StartScanningSynchronized);

            var location = await BeaconsUtil.GetCurrentLocationAsync();

            var ibeacons = await BeaconsService.Instance.LoadBeaconsByUserLocation(location.Coordinate.Latitude, location.Coordinate.Longitude);

            //Начинаем мониторинг
            foreach (var ibeacon in ibeacons)
            {
                var clBeaconRegion = new CLBeaconRegion(new NSUuid(ibeacon.UUID), (ushort)ibeacon.Major, (ushort)ibeacon.Minor, $"{BEACONS_REGION_HEADER}.{ibeacon.ToString()}");
                clBeaconRegion.NotifyEntryStateOnDisplay = true;
                clBeaconRegion.NotifyOnEntry             = true;
                clBeaconRegion.NotifyOnExit = true;

                _listOfCLBeaconRegion.Add(clBeaconRegion);

                _locationMgr.StartMonitoring(clBeaconRegion);
                _locationMgr.StartRangingBeacons(clBeaconRegion);

                MvxTrace.TaggedTrace(MvxTraceLevel.Diagnostic, "Beacons", "Start monitoring " + JsonConvert.SerializeObject(ibeacon));
            }
        }
Beispiel #28
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            MapServices.ProvideAPIKey ("AIzaSyA8WOvgGyHaw3rgkeYuUIqkIxhmW9Hrdjc");

            locationManager = new CLLocationManager ();
            locationManager.Delegate = new locationManagerDelegate ();
            locationManager.DesiredAccuracy = CLLocation.AccuracyBest;

            locationManager.RequestAlwaysAuthorization ();

            if (locationManager.RespondsToSelector (new Selector ("requestWhenInUseAuthorization")))
            {
                locationManager.RequestWhenInUseAuthorization ();
            }
            if (CLLocationManager.LocationServicesEnabled) {
                locationManager.StartUpdatingLocation ();
            }

            ProgressHUD.Shared.HudForegroundColor = UIColor.Gray;
            ProgressHUD.Shared.Ring.Color = UIColor.FromRGB(44/255f,146/255f,208/255f);
            ProgressHUD.Shared.HudForegroundColor = UIColor.FromRGB(44/255f,146/255f,208/255f);

            UIApplication.SharedApplication.SetStatusBarStyle (UIStatusBarStyle.LightContent, true);

            this.Window = new UIWindow (UIScreen.MainScreen.Bounds);
            UINavigationController navigation = new UINavigationController(new StartingScreen());
            navigation.NavigationBar.TintColor = UIColor.White;
            navigation.NavigationBar.BarTintColor = UIColor.FromRGB(44/255f,146/255f,208/255f);
            navigation.NavigationBar.BarStyle = UIBarStyle.Black;
            navigation.SetNavigationBarHidden (true,true);

            this.Window.RootViewController = navigation;
            this.Window.MakeKeyAndVisible ();

            return true;
        }
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear (animated);

            //Device Rotation
            if((InterfaceOrientation == UIInterfaceOrientation.LandscapeLeft) || (InterfaceOrientation == UIInterfaceOrientation.LandscapeRight))
                SetupUIForOrientation(InterfaceOrientation);
            //Initialize Map View
            mapView.WillStartLoadingMap += (sender, e) =>
            {
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
            };
            mapView.MapLoaded += (sender, e) =>
            {
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
            };
            mapView.LoadingMapFailed += (sender, e) =>
            {
                UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
            };
            mapView.MapType = MKMapType.Hybrid;
            mapView.ShowsUserLocation = true;
            mapView.UserLocation.Title = "Your are here!";
            mapView.UserLocation.Subtitle = "YES!";

            //Initialize location mananger
            locationManager = new CLLocationManager ();
            locationManager.DesiredAccuracy = -1;
            locationManager.DistanceFilter = 50;
            locationManager.HeadingFilter = 1;
            //Add 2 delegates
            locationManager.UpdatedHeading += UpdatedHeading;
            locationManager.UpdatedLocation += UpdatedLocation;
            locationManager.StartUpdatingLocation ();
            locationManager.StartUpdatingHeading ();
        }
Beispiel #30
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Perform any additional setup after loading the view, typically from a nib.

            /*ESTBeaconManager manager = new ESTBeaconManager();
             * ESTBeaconRegion region = new ESTBeaconRegion("B9407F30-F5F8-466E-AFF9-25556B57FE6D");
             * ESTBeacon beacon = new ESTBeacon();
             *
             * manager.AvoidUnknownStateBeacons = true;
             *
             * manager.StartMonitoringForRegion(region);
             * manager.RequestStateForRegion(region);*/


            // animated images test
            img_animation.AnimationImages = new UIImage[]
            {
                UIImage.FromBundle("animation/astro_anim01.jpg")
                , UIImage.FromBundle("animation/astro_anim01.jpg")
                , UIImage.FromBundle("animation/astro_anim03.jpg")
                , UIImage.FromBundle("animation/astro_anim04.jpg")
                , UIImage.FromBundle("animation/astro_anim05.jpg")
                , UIImage.FromBundle("animation/astro_anim06.jpg")
                , UIImage.FromBundle("animation/astro_anim07.jpg")
                , UIImage.FromBundle("animation/astro_anim08.jpg")
                , UIImage.FromBundle("animation/astro_anim09.jpg")
                , UIImage.FromBundle("animation/astro_anim10.jpg")
                , UIImage.FromBundle("animation/astro_anim11.jpg")
                , UIImage.FromBundle("animation/astro_anim12.jpg")
            };

            img_animation.AnimationRepeatCount = 1;
            img_animation.AnimationDuration    = 1.5;
            btn_askButton.TouchUpInside       += (sender, args) => AskQuestion();
            //------- END ANIMATION

            // Set the background image
            img_background.Image = UIImage.FromBundle("mainbackground.jpg");



            if (!CLLocationManager.LocationServicesEnabled)
            {
                lbl_exibitName.Text = "Location Not Enabled";
            }

            manager.RequestAlwaysAuthorization();
            manager.RequestWhenInUseAuthorization();
            manager.PausesLocationUpdatesAutomatically = false;

            /* manager.DidRangeBeacons += (sender, e) =>
             * {
             *
             *
             *   switch (_ctrl)
             *   {
             *       case 0:
             *           img_exhibit.Image = UIImage.FromBundle("img_radar.png");
             *           lbl_exibitName.Text = "Started Ranging";
             *           txt_basicInfo.Text = "Scanning for Estimotes in the area...";
             *           var bInfo = e.Beacons.Aggregate("", (current, beek) => current + string.Format("{0}-{1}: {4} {2} {5} {3}\n", beek.Major, beek.Minor, beek.Proximity, beek.Accuracy, "Prox: ", "Accuracy: "));
             *           txt_moreInfo.Text = bInfo;
             *           break;
             *       case 1:
             *
             *           if (!e.Beacons.ElementAt(0).Proximity.ToString().Equals("Unknown"))
             *           {
             *               if (e.Beacons.ElementAt(0).Major.ToString().Equals("46350"))
             *               {
             *                   img_exhibit.Image = UIImage.FromBundle("img_saturn.png");
             *                   lbl_exibitName.Text = "Saturn's Rings";
             *                   txt_basicInfo.Text = "This be Saturn! Arrr!";
             *                   txt_moreInfo.Text = "This is filler text that is supposed to be written in Latin but I do not speak Latin so this text will have to do. This"
             +
             +                                       " looks hideous in actual code, but it is not going to be used in the final release so I guess it is ok. Do not blame me as I am not"
             + " the senior developer...";
             +               }
             +               else if (e.Beacons.ElementAt(0).Major.ToString().Equals("24973"))
             +               {
             +                   img_exhibit.Image = UIImage.FromBundle("img_mars.png");
             +                   lbl_exibitName.Text = "Mars Rover";
             +                   txt_basicInfo.Text = "This be some iRobot stuff";
             +                   txt_moreInfo.Text = "This is even more filler text that was written by a developer that is need of a hug. I always work overtime but I never"
             +
             +                                       " get paid anything. I feel like I'm being taken advantage of by the others here. Please if anyone can read this tell my family"
             + " that I want to go home!";
             +               }
             +               else
             +               {
             +                   img_exhibit.Image = UIImage.FromBundle("placeholder.png");
             +                   lbl_exibitName.Text = "Unknown Estimote";
             +                   txt_basicInfo.Text = "What is this???";
             +                   txt_moreInfo.Text = "Which estimote is this? I don't have the ID in my database.";
             +               }
             +           }
             +           break;
             +   }
             +
             +
             + };*/

            btn_left.TouchUpInside += (o, args) =>
            {
                _ctrl = 0;
            };

            btn_right.TouchUpInside += (o, args) =>
            {
                _ctrl = 1;
            };

            manager.StartMonitoring(region);
            manager.StartRangingBeacons(region);
            manager.StartUpdatingLocation();

            btn_map.Clicked += (sender, e) =>
            {
                var newpage = new EstimoteViewController();
                PresentViewController(newpage, true, null);
            };

            // move text up
            Debug.Write(" inside view did load");

            // close keyboard on return NEED to add retun functionality so that ask button is clicked
            txt_askQuestion.ShouldReturn += delegate
            {
                AskQuestion();
                return(true);
            };
        }
		void Initialize ()
		{
			mapView.OnTapped += HandleMapViewOnTouchEnded;
			mapView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
			mapView.WillStartLoadingMap += (s, e) => 
			{ 
				UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; 
			};
			mapView.MapLoaded += (s, e) => 
			{ 
				UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; 
			};
			mapView.LoadingMapFailed += (s, e) => 
			{ 
				UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; 
			};
			
			//mapView.MapType = MKMapType.Hybrid;
			mapView.ShowsUserLocation = false;
			//Set up the text attributes for the user location annotation callout
			string desc = "Your photo is here";
			mapView.UserLocation.Title = desc;
			mapView.UserLocation.Subtitle = "";
			
			locationManager = new CLLocationManager();
			locationManager.DesiredAccuracy = -1;
			//Be as accurate as possible
			locationManager.DistanceFilter = 50;
			//Update when we have moved 50 m			
			locationManager.UpdatedLocation += UpdatedLocation;
			
			/*
			if (!CLLocationManager.LocationServicesEnabled)
				ShowLocalisationFailedMessage();
			else
				locationManager.StartUpdatingLocation();
			*/
				
			locationManager.StartUpdatingLocation();					
		}
 partial void GetCurrentLocation(UIButton sender)
 {
     locationManager.StartUpdatingLocation();
 }
        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);
        }
Beispiel #34
0
        public override void ViewDidLoad()
        {
            UserTrackingReporter.TrackUser(Constant.CATEGORY_LOGIN, "ViewDidLoad");

            base.ViewDidLoad();
            thisController = NavigationController;

            md5Hash = MD5.Create();

                        #if DEBUG
            usernameTextField.Text = "*****@*****.**";
            passwordTextField.Text = "test1234";
                        #endif

            var tap = new UITapGestureRecognizer(() => { View.EndEditing(true); });
            View.AddGestureRecognizer(tap);

            CLLocationManager locationManager;
            locationManager = new CLLocationManager();

            if (locationManager.RespondsToSelector(new Selector("requestWhenInUseAuthorization")))
            {
                locationManager.RequestWhenInUseAuthorization();
            }

            locationManager.DistanceFilter  = CLLocationDistance.FilterNone;
            locationManager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation;
            locationManager.StartUpdatingLocation();

            usernameTextField.ShouldReturn += TextFieldShouldReturn;
            passwordTextField.ShouldReturn += TextFieldShouldReturn;

            btnLogin.TouchUpInside          += BtnLogin_TouchUpInside;
            btnCreateAccount.TouchUpInside  += BtnCreateAccount_TouchUpInside;
            btnCallRoadrunner.TouchUpInside += BtnCallRoadrunner_TouchUpInside;

            #region Facebook

            _facebookLoginButton.TouchUpInside += BtnLogin_Facebook;

            #endregion

            #region Linkedin

            _linkedinLoginButton.TouchUpInside += BtnLogin_Linkedin;

            #endregion

            #region Google+

            signIn          = SignIn.SharedInstance;
            signIn.ClientId = RoadRunner.Shared.Constant.GOOGLECLIENTID;
            signIn.Scopes   = new[] { PlusConstants.AuthScopePlusLogin, PlusConstants.AuthScopePlusMe };
            signIn.ShouldFetchGoogleUserEmail = true;
            signIn.ShouldFetchGoogleUserId    = true;
            signIn.Delegate = this;

            _googleLoginButton.TouchUpInside += BtnLogin_Google;

            #endregion

            #region AutoLogin
            // If the user is already logged in GooglePlus
            if (signIn.ClientId != null && signIn.TrySilentAuthentication)
            {
            }

            // If the user is already logged in Facebook
            if (Facebook.CoreKit.AccessToken.CurrentAccessToken != null)
            {
                FacebookLoggedIn(Facebook.CoreKit.AccessToken.CurrentAccessToken.UserID);
            }

            // If the user is already logged in Linkedin
            if (SessionManager.SharedInstance.Session.AccessToken != null)
            {
                LinkedInLoggedIn();
            }

            if (!String.IsNullOrEmpty(AppSettings.UserLogin) && !String.IsNullOrEmpty(AppSettings.UserPassword))
            {
                usernameTextField.Text = AppSettings.UserLogin;
                passwordTextField.Text = AppSettings.UserPassword;
                BtnLogin_TouchUpInside(new object(), new EventArgs());
            }
            #endregion
        }
 public void StartRequestingLocation()
 {
     _locationManager.StartUpdatingLocation();
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            try{
                var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                _pathToDatabase = Path.Combine(documents, "db_sqlite-net.db");

                using (var db = new SQLite.SQLiteConnection(_pathToDatabase))
                {
                    people = new List <Person> (from p in db.Table <Person> () select p);
                }

                //inicializacion del manejador de localizacion.
                iPhoneLocationManager = new CLLocationManager();
                //Establecer la precision del manejador de localizacion.
                iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;

                iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                    newLocation = e.Locations [e.Locations.Length - 1];
                };

                productSearchDetailService.setProductBarcode(this.barcode, MainView.localityId.ToString(), MainView.userId);
                List <ProductSearchDetailService> tableItems = productSearchDetailService.All();

                this.productImages.Clear();
                foreach (var v in tableItems)
                {
                    Images image = new Images {
                        storeImageUrl = v.imagen
                    };
                    this.productImages.Add(image);
                }

                UIBarButtonItem home = new UIBarButtonItem();
                home.Style  = UIBarButtonItemStyle.Plain;
                home.Target = this;
                home.Image  = UIImage.FromFile("Images/home.png");
                this.NavigationItem.RightBarButtonItem = home;
                UIViewController[] vistas = NavigationController.ViewControllers;
                home.Clicked += (sender, e) => {
                    this.NavigationController.PopToViewController(vistas[0], true);
                };

                btnTiendaCercana.TouchUpInside += (sender, e) => {
                    try{
                        ProductSearchDetailService tiendac = nearestStore(newLocation, tableItems);
                        double distancia = newLocation.DistanceFrom(new CLLocation(Double.Parse(tiendac.tienda_latitud), Double.Parse(tiendac.tienda_longitud))) / 1000;
                        distancia = Math.Round(distancia, 2);
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Tu tienda mas cercana es:", Message = "" + tiendac.tienda_nombre + "\n " + tiendac.tienda_direccion + "\n" + "Distancia: " + distancia.ToString() + "km"
                        };
                        alert.AddButton("Aceptar");
                        alert.AddButton("Mapa");
                        alert.Clicked += (s, o) => {
                            if (o.ButtonIndex == 1)
                            {
                                SecondMapViewController mapView = new SecondMapViewController();
                                mapView.setTienda(tiendac);
                                this.NavigationController.PushViewController(mapView, true);
                            }
                        };
                        alert.Show();
                    }catch (NullReferenceException) {
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Lo Sentimos =(", Message = "FixBuy no pudo obtener tu ubicación por favor ve a Ajustes/Privacidad/Localizacion y verifica que Fixbuy tenga permiso de saber tu ubicación"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                    }
                };

                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                {
                    if (CLLocationManager.LocationServicesEnabled)
                    {
                        this.tblStores.Source = new StoresTableSourceIphone(tableItems, this, iPhoneLocationManager, people.Count);
                    }
                    else
                    {
                        this.tblStores.Source = new StoresTableSourceIphone(tableItems, this, null, people.Count);
                    }
                }
                else
                {
                    if (CLLocationManager.LocationServicesEnabled)
                    {
                        this.tblStores.Source = new StoresTableSource(tableItems, this, iPhoneLocationManager, people.Count);
                    }
                    else
                    {
                        this.tblStores.Source = new StoresTableSource(tableItems, this, null, people.Count);
                    }
                }

                ProductSearchDetailService product = tableItems.ElementAt(0);
                NSUrl  nsUrl = new NSUrl(product.imagen);
                NSData data  = NSData.FromUrl(nsUrl);
                if (data != null)
                {
                    this.imgProduct.Image = UIImage.LoadFromData(data);
                }
                else
                {
                    this.imgProduct.Image = Images.sinImagen;
                }
                this.lblproduct.Text     = product.nombre;
                this.lblDescription.Text = product.descripcion;
                //this.tblStores.TableHeaderView = this.headerView;
                Add(this.tblStores);

                // Manejamos la actualizacion de la localizacion del dispositivo.
                iPhoneLocationManager.RequestAlwaysAuthorization();
                if (CLLocationManager.LocationServicesEnabled)
                {
                    iPhoneLocationManager.StartUpdatingLocation();
                }
            }catch (System.ArgumentOutOfRangeException) {
                didNotFidProduct();
            }catch (Exception ex) {
                Console.WriteLine("ESTA ES LA EXCEPCION: " + ex.ToString());
                this.imgProduct.Image          = UIImage.FromFile("Images/noImage.jpg");
                this.lblproduct.Text           = "Producto no encontrado =S";
                this.lblDescription.Text       = "";
                this.btnTiendaCercana.Hidden   = true;
                this.tblStores.BackgroundColor = UIColor.Clear;
                UIAlertView alert = new UIAlertView()
                {
                    Title = "Ups =(", Message = "Lo sentimos algo salio mal, por favor intentalo de nuevo"
                };
                alert.AddButton("Aceptar");
                alert.Show();
            }
        }
Beispiel #37
0
 public override void ViewDidAppear(bool animated)
 {
     locationManager.StartUpdatingLocation();
 }
        public void UpdateNearestList()
        {
            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();
                updating = false;
                return;
            }

            if (locationManager == null)
            {
                locationManager = new CLLocationManager();
                locationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;



                locationDelegate = new MyLocationManagerDelegate();
                locationDelegate.OnLocationError += delegate(NSError error) {
                    alert = new UIAlertView("No Location Available", "Sorry, but there was an error finding your location. However, you may still be able to use the timer and map.", null, "Ok");
                    alert.Show();

                    updating = false;
                };

                locationDelegate.OnHeadingUpdate += delegate(CLHeading heading) {
                    Util.Log("heading: " + heading.TrueHeading);

                    UpdateCompass((int)heading.TrueHeading);
                };
                locationDelegate.OnLocationUpdate += delegate(CLLocation location) {
                    CLLocationCoordinate2D coord = location.Coordinate;
#if DEBUG
                    coord = Locations.BanksideMix;
#endif


                    var bikeList = BikeLocation.FindClosestBikeList(coord.Latitude, coord.Longitude);

                    RootElement root = new RootElement("Nearest Bikes");
                    HasList = true;



                    Section section = new Section();
                    int     i       = 0;

                    if (location.HorizontalAccuracy > 100)
                    {
                        section.Add(new StringElement("Low GPS accuracy!")
                        {
                            Alignment = UITextAlignment.Center
                        });
                    }



                    foreach (BikeLocation bike in bikeList)
                    {
                        var localBike = bike;



                        section.Add(new BikeElement(localBike, delegate {
                            Util.AppDelegate.SetFocusOnLocation(localBike);
                        }));



                        i++;
                        if (i > 20)
                        {
                            break;
                        }
                    }

                    root.Add(section);


                    Root = root;

                    updating = false;

                    BikeLocation.LogSearch();
                };
                locationManager.Delegate = locationDelegate;
            }

            locationManager.StartUpdatingLocation();
            locationDelegate.StartTimer(locationManager);
            Util.TurnOnNetworkActivity();
        }
Beispiel #39
0
 public void Start()
 {
     _locationManager.StartUpdatingLocation();
     _locationManager.StartUpdatingHeading();
 }
Beispiel #40
0
        protected override IObservable <LocationRecorded> CreateStartLocationUpdates()
        {
            return
                (Observable
                 .Create <LocationRecorded>(subj =>
            {
                CompositeDisposable disp = new CompositeDisposable();
                try
                {
                    IsListeningForChangesImperative = true;
                    if (_locationManager == null)
                    {
                        _locationManager = CreateLocationManager();
                        Observable
                        .FromEventPattern <NSErrorEventArgs>
                        (
                            x => _locationManager.Failed += x,
                            x => _locationManager.Failed -= x
                        )
                        .Select(e => e.EventArgs)
                        .Subscribe(args =>
                        {
                            ExceptionHandling.LogException(
                                new LocationActivationException(
                                    ActivationFailedReasons.CheckExceptionOnPlatform,
                                    args.Error.Description)
                                );
                        });
                    }



                    Disposable.Create(() =>
                    {
                        _locationManager.StopUpdatingLocation();
                        IsListeningForChangesImperative = false;
                    })
                    .DisposeWith(disp);

                    _locationManager.StartUpdatingLocation();
                    Observable.FromEventPattern <CLLocationsUpdatedEventArgs>
                    (
                        x => _locationManager.LocationsUpdated += x,
                        x => _locationManager.LocationsUpdated -= x
                    )
                    .SelectMany(lu => lu.EventArgs.Locations)
                    .Select(lu => PositionFactory(lu))
                    .Where(lu => lu != null)
                    .Subscribe(subj)
                    .DisposeWith(disp);


                    if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
                    {
                        _locationManager.RequestLocation();
                    }

                    return disp;
                }
                catch (Exception exc)
                {
                    subj.OnError(exc);
                    disp.Dispose();
                }

                return Disposable.Empty;
            })
                 .SubscribeOn(Scheduler.Dispatcher));
        }
        public async override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            loadingpage();

            styleElements();

            // you can set the update threshold and accuracy if you want:
            //locationManager.DistanceFilter = 10d; // move ten meters before updating
            //locationManager.HeadingFilter = 3d; // move 3 degrees before updating

            // you can also set the desired accuracy:
            locationManager.DesiredAccuracy = 1000; // 1000 meters/1 kilometer
            // you can also use presets, which simply evalute to a double value:
            //locationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;

            locationManager.Delegate = this;
            locationManager.RequestWhenInUseAuthorization();

            if (CLLocationManager.LocationServicesEnabled)
            {
                locationManager.StartUpdatingLocation();
            }

            if (CLLocationManager.HeadingAvailable)
            {
                locationManager.StartUpdatingHeading();
            }

            //ViewModel.GetProfiles();

            //AccountInfo.first_time = 1;

            ViewModel.ForPropertyChange(x => x.AllProfiles, y =>
            {
                for (int a = 0; a < ViewModel.allprofiles.Count; a++)
                {
                    if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].id) && a.Equals(0))
                    {
                        if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].image_url))
                        {
                            image_profile_1.Image = FromUrl(ViewModel.allprofiles[a].image_url);
                        }

                        else
                        {
                            image_profile_1.Image = FromUrl("https://srendip-dev.s3.amazonaws.com/no-image-icon.png");
                        }

                        image_profile_1.UserInteractionEnabled = true;
                    }
                    else if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].id) && a.Equals(1))
                    {
                        if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].image_url))
                        {
                            image_profile_2.Image = FromUrl(ViewModel.allprofiles[a].image_url);
                        }

                        else
                        {
                            image_profile_2.Image = FromUrl("https://srendip-dev.s3.amazonaws.com/no-image-icon.png");
                        }

                        image_profile_2.UserInteractionEnabled = true;
                    }
                    else if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].id) && a.Equals(2))
                    {
                        if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].image_url))
                        {
                            image_profile_3.Image = FromUrl(ViewModel.allprofiles[a].image_url);
                        }
                        else
                        {
                            image_profile_3.Image = FromUrl("https://srendip-dev.s3.amazonaws.com/no-image-icon.png");
                        }

                        image_profile_3.UserInteractionEnabled = true;
                    }
                    else if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].id) && a.Equals(3))
                    {
                        if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].image_url))
                        {
                            image_profile_4.Image = FromUrl(ViewModel.allprofiles[a].image_url);
                        }

                        else
                        {
                            image_profile_4.Image = FromUrl("https://srendip-dev.s3.amazonaws.com/no-image-icon.png");
                        }

                        image_profile_4.UserInteractionEnabled = true;
                    }
                    else if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].id) && a.Equals(4))
                    {
                        if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].image_url))
                        {
                            image_profile_5.Image = FromUrl(ViewModel.allprofiles[a].image_url);
                        }

                        else
                        {
                            image_profile_5.Image = FromUrl("https://srendip-dev.s3.amazonaws.com/no-image-icon.png");
                        }

                        image_profile_5.UserInteractionEnabled = true;
                    }
                    else if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].id) && a.Equals(5))
                    {
                        if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].image_url))
                        {
                            image_profile_6.Image = FromUrl(ViewModel.allprofiles[a].image_url);
                        }

                        else
                        {
                            image_profile_6.Image = FromUrl("https://srendip-dev.s3.amazonaws.com/no-image-icon.png");
                        }

                        image_profile_6.UserInteractionEnabled = true;
                    }
                    else if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].id) && a.Equals(6))
                    {
                        if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].image_url))
                        {
                            image_profile_7.Image = FromUrl(ViewModel.allprofiles[a].image_url);
                        }

                        else
                        {
                            image_profile_7.Image = FromUrl("https://srendip-dev.s3.amazonaws.com/no-image-icon.png");
                        }

                        image_profile_7.UserInteractionEnabled = true;
                    }
                    else if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].id) && a.Equals(7))
                    {
                        if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].image_url))
                        {
                            image_profile_8.Image = FromUrl(ViewModel.allprofiles[a].image_url);
                        }

                        else
                        {
                            image_profile_8.Image = FromUrl("https://srendip-dev.s3.amazonaws.com/no-image-icon.png");
                        }

                        image_profile_8.UserInteractionEnabled = true;
                    }
                    else if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].id) && a.Equals(8))
                    {
                        if (!string.IsNullOrEmpty(ViewModel.allprofiles[a].image_url))
                        {
                            image_profile_9.Image = FromUrl(ViewModel.allprofiles[a].image_url);
                        }
                        else
                        {
                            image_profile_9.Image = FromUrl("https://srendip-dev.s3.amazonaws.com/no-image-icon.png");
                        }
                        image_profile_9.UserInteractionEnabled = true;
                    }
                }

                loading_View.Hide();
            });

            this.View.BackgroundColor = UIColor.FromRGB(246, 194, 96);

            NavigationBarSetUp();
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();



            navBar = new UINavigationBar(new RectangleF(0, 0, 320, 44));
            var bbi = new UIBarButtonItem(UIImage.FromBundle("Images/slideout"), UIBarButtonItemStyle.Plain, (sender, e) => {
                AppDelegate.Current.FlyoutNavigation.ToggleMenu();
            });
            var rbi = new UIBarButtonItem(UIImage.FromBundle("Images/113-navigation"), UIBarButtonItemStyle.Plain, (sender, e) => {
                mapFlipViewController.Flip();
            });

            var item = new UINavigationItem("Location Map");

            item.LeftBarButtonItem  = bbi;
            item.RightBarButtonItem = rbi;
            var items = new UINavigationItem[] {
                item
            };

            navBar.SetItems(items, false);



            mapView = new MKMapView()
            {
                ShowsUserLocation = true
            };

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

            var segmentedControl = new UISegmentedControl();
            var topOfSegement    = View.Frame.Height - 60;

            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;

            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, 44 + 50, View.Frame.Width, View.Frame.Height - 93);

            MKCoordinateSpan   span   = new MKCoordinateSpan(0.01, 0.01);
            MKCoordinateRegion region = new MKCoordinateRegion(ConferenceLocation.Location.To2D(), span);

            mapView.SetRegion(region, true);

            ConferenceAnnotation a = new ConferenceAnnotation(ConferenceLocation.Location.To2D()
                                                              , ConferenceLocation.Title
                                                              , ConferenceLocation.Subtitle
                                                              );

            mapView.AddAnnotationObject(a);


            locationManager          = new CLLocationManager();
            locationManager.Delegate = new LocationManagerDelegate(mapView, this);
            locationManager.Purpose  = "Show distance on map";            // also Info.plist
            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 {
                mapFlipViewController.Flip();
            };
            View.AddSubview(flipButton);


            View.Add(navBar);
        }
        public override void ViewDidLoad()
        {
            // all your base
            base.ViewDidLoad();

            // load the appropriate view, based on the device type
            this.LoadViewForDevice();

            // initialize our location manager and callback handler
            iPhoneLocationManager = new CLLocationManager();

            // uncomment this if you want to use the delegate pattern:
            //locationDelegate = new LocationDelegate (mainScreen);
            //iPhoneLocationManager.Delegate = locationDelegate;

            // you can set the update threshold and accuracy if you want:
            //iPhoneLocationManager.DistanceFilter = 10; // move ten meters before updating
            //iPhoneLocationManager.HeadingFilter = 3; // move 3 degrees before updating

            // you can also set the desired accuracy:
            iPhoneLocationManager.DesiredAccuracy = 1000;             // 1000 meters/1 kilometer
            // you can also use presets, which simply evalute to a double value:
            //iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;

            // handle the updated location method and update the UI
            if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
            {
                iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                    UpdateLocation(mainScreen, e.Locations [e.Locations.Length - 1]);
                };
            }
            else
            {
                                #pragma warning disable 618
                // this won't be called on iOS 6 (deprecated)
                iPhoneLocationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => {
                    UpdateLocation(mainScreen, e.NewLocation);
                };
                                #pragma warning restore 618
            }

            //iOS 8 requires you to manually request authorization now - Note the Info.plist file has a new key called requestWhenInUseAuthorization added to.
            if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
                iPhoneLocationManager.RequestWhenInUseAuthorization();
            }

            // handle the updated heading method and update the UI
            iPhoneLocationManager.UpdatedHeading += (object sender, CLHeadingUpdatedEventArgs e) => {
                mainScreen.LblMagneticHeading.Text = e.NewHeading.MagneticHeading.ToString() + "º";
                mainScreen.LblTrueHeading.Text     = e.NewHeading.TrueHeading.ToString() + "º";
            };

            // start updating our location, et. al.
            if (CLLocationManager.LocationServicesEnabled)
            {
                iPhoneLocationManager.StartUpdatingLocation();
            }
            if (CLLocationManager.HeadingAvailable)
            {
                iPhoneLocationManager.StartUpdatingHeading();
            }
        }
Beispiel #44
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            this.Add(faceBookView);
            this.Add(facebookView2);

            iPhoneLocationManager = new CLLocationManager();
            iPhoneLocationManager.DesiredAccuracy   = CLLocation.AccuracyNearestTenMeters;
            iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
            };

            iPhoneLocationManager.RequestAlwaysAuthorization();
            if (CLLocationManager.LocationServicesEnabled)
            {
                iPhoneLocationManager.StartUpdatingLocation();
            }
            #region observadores del teclado
            // Keyboard popup
            NSNotificationCenter.DefaultCenter.AddObserver
                (UIKeyboard.DidShowNotification, KeyBoardUpNotification);

            // Keyboard Down
            NSNotificationCenter.DefaultCenter.AddObserver
                (UIKeyboard.WillHideNotification, KeyBoardDownNotification);
            #endregion

            #region declaracion de vista de Facebook
            // Create the Facebook LogIn View with the needed Permissions
            // https://developers.facebook.com/ios/login-ui-control/
            loginView = new FBLoginView(ExtendedPermissions)
            {
                Frame = new CGRect(0, 0, 45, 45)
            };

            // Create view that will display user's profile picture
            // https://developers.facebook.com/ios/profilepicture-ui-control/

            pictureView = new FBProfilePictureView()
            {
                Frame = new CGRect(0, 0, 45, 45)
            };
            pictureView.UserInteractionEnabled = true;
            // Hook up to FetchedUserInfo event, so you know when
            // you have the user information available
            loginView.FetchedUserInfo += (sender, e) => {
                user = e.User;
                pictureView.ProfileID   = user.GetId();
                MainView.isWithFacebook = true;
                loginView.Alpha         = 0.1f;
                pictureView.Hidden      = false;
            };

            // Clean user Picture and label when Logged Out
            loginView.ShowingLoggedOutUser += (sender, e) => {
                pictureView.ProfileID   = null;
                pictureView.Hidden      = true;
                lblUserName.Text        = string.Empty;
                loginView.Alpha         = 1f;
                MainView.isWithFacebook = false;
            };

            this.faceBookView.Add(pictureView);
            this.faceBookView.Add(loginView);
            #endregion

            var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            _pathToDatabase = Path.Combine(documents, "db_sqlite-net.db");

            //Creamos la base de datos y la tabla de persona
            using (var conn = new SQLite.SQLiteConnection(_pathToDatabase))
            {
                conn.CreateTable <Person>();
                conn.CreateTable <State> ();
                conn.CreateTable <Terms> ();
                conn.CreateTable <PrivacyNotice> ();
            }

            using (var db = new SQLite.SQLiteConnection(_pathToDatabase))
            {
                people         = new List <Person> (from p in db.Table <Person> () select p);
                states         = new List <State> (from s in db.Table <State> () select s);
                terms          = new List <Terms> (from t in db.Table <Terms> () select t);
                privacyNotices = new List <PrivacyNotice> (from pr in db.Table <PrivacyNotice> () select pr);
            }

            if (people.Count > 0)
            {
                Person user = people.ElementAt(0);
                MainView.userId = user.ID;
                Console.WriteLine("El Id de usuario es: " + user.ID);
            }

            if (states.Count > 0)
            {
                State estado = states.ElementAt(0);
                MainView.localityId = estado.localityId;
                Console.WriteLine("El Id de localidad es: " + estado.stateId);
            }

            //Boton para entrar al menu de la aplicacion.
            this.btnEntrar.TouchUpInside += (sender, e) => {
                scanView = new ScanView();
                this.NavigationController.PushViewController(scanView, true);
            };

            this.btnListas.TouchUpInside += (sender, e) => {
                using (var db = new SQLite.SQLiteConnection(_pathToDatabase))
                {
                    people = new List <Person> (from p in db.Table <Person> () select p);
                }
                if (people.Count > 0)
                {
                    MyListsView mylists = new MyListsView();
                    this.NavigationController.PushViewController(mylists, true);
                }
                else
                {
                    UIAlertView alert = new UIAlertView()
                    {
                        Title = "Espera!", Message = "Debes iniciar sesion para acceder a tus listas"
                    };
                    alert.AddButton("Aceptar");
                    alert.Show();
                }
            };

            //Boton para hacer busqueda por nombre de producto
            this.btnBuscar.TouchUpInside += (sender, e) => {
                if (this.cmpNombre.Text == "")
                {
                    UIAlertView alert = new UIAlertView()
                    {
                        Title = "Espera!", Message = "Debes ingresar el nombre del producto a buscar"
                    };
                    alert.AddButton("Aceptar");
                    alert.Show();
                }
                else if (states.Count < 1)
                {
                    UIAlertView alert = new UIAlertView()
                    {
                        Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " +
                                                     "Al menu de opciones para establecerla"
                    };
                    alert.AddButton("Aceptar");
                    alert.Clicked += (s, o) => {
                        StatesView statesView = new StatesView();
                        this.NavigationController.PushViewController(statesView, true);
                    };
                    alert.Show();
                }
                else
                {
                    this._loadPop = new LoadingOverlay(UIScreen.MainScreen.Bounds);
                    this.View.Add(this._loadPop);
                    this.cmpNombre.ResignFirstResponder();
                    Task.Factory.StartNew(
                        () => {
                        System.Threading.Thread.Sleep(1 * 1000);
                    }
                        ).ContinueWith(
                        t => {
                        nsr = new NameSearchResultView();
                        nsr.setProductName(this.cmpNombre.Text.Trim());
                        this.NavigationController.PushViewController(nsr, true);
                        this._loadPop.Hide();
                    }, TaskScheduler.FromCurrentSynchronizationContext()
                        );
                }
            };

            this.cmpNombre.ShouldReturn += (textField) => {
                if (this.cmpNombre.Text == "")
                {
                    UIAlertView alert = new UIAlertView()
                    {
                        Title = "Espera!", Message = "Debes ingresar el nombre del producto a buscar"
                    };
                    alert.AddButton("Aceptar");
                    alert.Show();
                }
                else if (states.Count < 1)
                {
                    UIAlertView alert = new UIAlertView()
                    {
                        Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " +
                                                     "Al menu de opciones para establecerla"
                    };
                    alert.AddButton("Aceptar");
                    alert.Clicked += (s, o) => {
                        StatesView statesView = new StatesView();
                        this.NavigationController.PushViewController(statesView, true);
                    };
                    alert.Show();
                }
                else
                {
                    this._loadPop = new LoadingOverlay(UIScreen.MainScreen.Bounds);
                    this.View.Add(this._loadPop);
                    this.cmpNombre.ResignFirstResponder();
                    Task.Factory.StartNew(
                        () => {
                        System.Threading.Thread.Sleep(1 * 1000);
                    }
                        ).ContinueWith(
                        t => {
                        nsr = new NameSearchResultView();
                        nsr.setProductName(this.cmpNombre.Text.Trim());
                        this.NavigationController.PushViewController(nsr, true);
                        this._loadPop.Hide();
                    }, TaskScheduler.FromCurrentSynchronizationContext()
                        );
                }
                return(true);
            };

            //Boton para iniciar el escaner de codigo de barras
            this.btnCodigo.TouchUpInside += (sender, e) => {
                if (states.Count > 0)
                {
                    // Configurar el escaner de codigo de barras.
                    picker = new ScanditSDKRotatingBarcodePicker(appKey);
                    picker.OverlayController.Delegate = new overlayControllerDelegate(picker, this);
                    picker.OverlayController.ShowToolBar(true);
                    picker.OverlayController.ShowSearchBar(true);
                    picker.OverlayController.SetToolBarButtonCaption("Cancelar");
                    picker.OverlayController.SetSearchBarKeyboardType(UIKeyboardType.Default);
                    picker.OverlayController.SetSearchBarPlaceholderText("Búsqueda por nombre de producto");
                    picker.OverlayController.SetCameraSwitchVisibility(SICameraSwitchVisibility.OnTablet);
                    picker.OverlayController.SetTextForInitializingCamera("Iniciando la camara");
                    this.PresentViewController(picker, true, null);
                    picker.StartScanning();
                }
                else
                {
                    UIAlertView alert = new UIAlertView()
                    {
                        Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " +
                                                     "Al menu de opciones para establecerla"
                    };
                    alert.AddButton("Aceptar");
                    alert.Clicked += (s, o) => {
                        StatesView statesView = new StatesView();
                        this.NavigationController.PushViewController(statesView, true);
                    };
                    alert.Show();
                }
            };
        }
 public void Start()
 {
     _locationManager.StartUpdatingLocation();
     IsRunning = true;
     IsRunningChanged?.Invoke(this, IsRunning);
 }
Beispiel #46
0
        /// <summary>
        /// Start listening for changes
        /// </summary>
        /// <param name="minimumTime">Time</param>
        /// <param name="minimumDistance">Distance</param>
        /// <param name="includeHeading">Include heading or not</param>
        /// <param name="listenerSettings">Optional settings (iOS only)</param>
        public Task <bool> StartListeningAsync(TimeSpan minTime, double minDistance, bool includeHeading = false, ListenerSettings settings = null)
        {
            if (minDistance < 0)
            {
                throw new ArgumentOutOfRangeException("minDistance");
            }
            if (isListening)
            {
                throw new InvalidOperationException("Already listening");
            }

            // if no settings were passed in, instantiate the default settings. need to check this and create default settings since
            // previous calls to StartListeningAsync might have already configured the location manager in a non-default way that the
            // caller of this method might not be expecting. the caller should expect the defaults if they pass no settings.
            if (settings == null)
            {
                settings = new ListenerSettings();
            }

            // keep reference to settings so that we can stop the listener appropriately later
            listenerSettings = settings;

            var desiredAccuracy = DesiredAccuracy;

            #region apply settings to location manager
            // set background flag
            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                manager.AllowsBackgroundLocationUpdates = settings.AllowBackgroundUpdates;
            }

            // configure location update pausing
            if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
            {
                manager.PausesLocationUpdatesAutomatically = settings.PauseLocationUpdatesAutomatically;

                if (settings.ActivityType == ActivityType.AutomotiveNavigation)
                {
                    manager.ActivityType = CLActivityType.AutomotiveNavigation;
                }
                else if (settings.ActivityType == ActivityType.Fitness)
                {
                    manager.ActivityType = CLActivityType.Fitness;
                }
                else if (settings.ActivityType == ActivityType.Other)
                {
                    manager.ActivityType = CLActivityType.Other;
                }
                else if (settings.ActivityType == ActivityType.OtherNavigation)
                {
                    manager.ActivityType = CLActivityType.OtherNavigation;
                }
            }

            // to use deferral, CLLocationManager.DistanceFilter must be set to CLLocationDistance.None, and CLLocationManager.DesiredAccuracy must be
            // either CLLocation.AccuracyBest or CLLocation.AccuracyBestForNavigation. deferral only available on iOS 6.0 and above.
            if (CanDeferLocationUpdate && settings.DeferLocationUpdates)
            {
                minDistance     = CLLocationDistance.FilterNone;
                desiredAccuracy = CLLocation.AccuracyBest;
            }
            #endregion

            isListening             = true;
            manager.DesiredAccuracy = desiredAccuracy;
            manager.DistanceFilter  = minDistance;

            if (settings.ListenForSignificantChanges)
            {
                manager.StartMonitoringSignificantLocationChanges();
            }
            else
            {
                manager.StartUpdatingLocation();
            }

            if (includeHeading && CLLocationManager.HeadingAvailable)
            {
                manager.StartUpdatingHeading();
            }

            return(Task.FromResult(true));
        }
Beispiel #47
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			this.Add (faceBookView);
			this.Add (facebookView2);

			iPhoneLocationManager = new CLLocationManager ();
			iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;
			iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {

			};
				
			iPhoneLocationManager.RequestAlwaysAuthorization ();
			if (CLLocationManager.LocationServicesEnabled) {
				iPhoneLocationManager.StartUpdatingLocation ();
			}
			#region observadores del teclado
			// Keyboard popup
			NSNotificationCenter.DefaultCenter.AddObserver
			(UIKeyboard.DidShowNotification,KeyBoardUpNotification);

			// Keyboard Down
			NSNotificationCenter.DefaultCenter.AddObserver
			(UIKeyboard.WillHideNotification,KeyBoardDownNotification);
			#endregion

			#region declaracion de vista de Facebook
			// Create the Facebook LogIn View with the needed Permissions
			// https://developers.facebook.com/ios/login-ui-control/
			loginView = new FBLoginView (ExtendedPermissions) {
				Frame = new CGRect (0,0,45, 45)
			};

			// Create view that will display user's profile picture
			// https://developers.facebook.com/ios/profilepicture-ui-control/

			pictureView = new FBProfilePictureView () {
				Frame = new CGRect (0, 0, 45, 45)
			};
			pictureView.UserInteractionEnabled = true;
			// Hook up to FetchedUserInfo event, so you know when
			// you have the user information available
			loginView.FetchedUserInfo += (sender, e) => {
				user = e.User;
				pictureView.ProfileID = user.GetId ();
				MainView.isWithFacebook = true;
				loginView.Alpha = 0.1f;
				pictureView.Hidden = false;
			};

			// Clean user Picture and label when Logged Out
			loginView.ShowingLoggedOutUser += (sender, e) => {
				pictureView.ProfileID = null;
				pictureView.Hidden = true;
				lblUserName.Text = string.Empty;
				loginView.Alpha = 1f;
				MainView.isWithFacebook = false;
			};
		
			this.faceBookView.Add(pictureView);
			this.faceBookView.Add(loginView);
			#endregion

			var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
			_pathToDatabase = Path.Combine(documents, "db_sqlite-net.db");

			//Creamos la base de datos y la tabla de persona
			using (var conn= new SQLite.SQLiteConnection(_pathToDatabase))
			{
				conn.CreateTable<Person>();
				conn.CreateTable<State> ();
				conn.CreateTable<Terms> ();
				conn.CreateTable<PrivacyNotice> ();
			}

			using (var db = new SQLite.SQLiteConnection(_pathToDatabase ))
			{
				people = new List<Person> (from p in db.Table<Person> () select p);
				states = new List<State> (from s in db.Table<State> () select s);
				terms = new List<Terms> (from t in db.Table<Terms> ()select t);
				privacyNotices = new List<PrivacyNotice> (from pr in db.Table<PrivacyNotice> () select pr);
			}

			if(people.Count > 0){
				Person user = people.ElementAt(0);
				MainView.userId = user.ID;
				Console.WriteLine ("El Id de usuario es: "+ user.ID);
			}

			if(states.Count > 0){
				State estado = states.ElementAt(0);
				MainView.localityId = estado.localityId;
				Console.WriteLine ("El Id de localidad es: "+ estado.stateId);
			}
				
			//Boton para entrar al menu de la aplicacion.
			this.btnEntrar.TouchUpInside += (sender, e) => {
				scanView = new ScanView();
				this.NavigationController.PushViewController(scanView, true);
			};

			this.btnListas.TouchUpInside += (sender, e) => {
				using (var db = new SQLite.SQLiteConnection(_pathToDatabase ))
				{
					people = new List<Person> (from p in db.Table<Person> () select p);
				}
				if(people.Count > 0){
					MyListsView mylists = new MyListsView();
					this.NavigationController.PushViewController(mylists,true);
				}else{
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes iniciar sesion para acceder a tus listas"
					};
					alert.AddButton ("Aceptar");
					alert.Show ();
				}
			};

			//Boton para hacer busqueda por nombre de producto
			this.btnBuscar.TouchUpInside += (sender, e) => {
				if(this.cmpNombre.Text == ""){
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes ingresar el nombre del producto a buscar"
					};
					alert.AddButton ("Aceptar");
					alert.Show ();
				}
				else if (states.Count < 1){
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " +
							"Al menu de opciones para establecerla"
					};
					alert.AddButton ("Aceptar");
					alert.Clicked += (s, o) => {
						StatesView statesView = new StatesView();
						this.NavigationController.PushViewController(statesView, true);
					};
					alert.Show ();
				}
				else{
					this._loadPop = new LoadingOverlay (UIScreen.MainScreen.Bounds);
					this.View.Add ( this._loadPop );
					this.cmpNombre.ResignFirstResponder();
					Task.Factory.StartNew (
						() => {
							System.Threading.Thread.Sleep ( 1 * 1000 );
						}
					).ContinueWith ( 
						t => {
							nsr = new NameSearchResultView();
							nsr.setProductName(this.cmpNombre.Text.Trim());
							this.NavigationController.PushViewController(nsr,true);
							this._loadPop.Hide ();
						}, TaskScheduler.FromCurrentSynchronizationContext()
					);
				}
			};

			this.cmpNombre.ShouldReturn += (textField) => {
				if(this.cmpNombre.Text == ""){
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes ingresar el nombre del producto a buscar"
					};
					alert.AddButton ("Aceptar");
					alert.Show ();
				}
				else if (states.Count < 1){
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " +
							"Al menu de opciones para establecerla"
					};
					alert.AddButton ("Aceptar");
					alert.Clicked += (s, o) => {
						StatesView statesView = new StatesView();
						this.NavigationController.PushViewController(statesView, true);
					};
					alert.Show ();
				}
				else{
					this._loadPop = new LoadingOverlay (UIScreen.MainScreen.Bounds);
					this.View.Add ( this._loadPop );
					this.cmpNombre.ResignFirstResponder();
					Task.Factory.StartNew (
						() => {
							System.Threading.Thread.Sleep ( 1 * 1000 );
						}
					).ContinueWith ( 
						t => {
							nsr = new NameSearchResultView();
							nsr.setProductName(this.cmpNombre.Text.Trim());
							this.NavigationController.PushViewController(nsr,true);
							this._loadPop.Hide ();
						}, TaskScheduler.FromCurrentSynchronizationContext()
					);
				} 
				return true; 
			};

			//Boton para iniciar el escaner de codigo de barras
			this.btnCodigo.TouchUpInside += (sender, e) => {
				if(states.Count > 0){
					// Configurar el escaner de codigo de barras.
					picker = new ScanditSDKRotatingBarcodePicker (appKey);
					picker.OverlayController.Delegate = new overlayControllerDelegate(picker, this);
					picker.OverlayController.ShowToolBar(true);
					picker.OverlayController.ShowSearchBar(true);
					picker.OverlayController.SetToolBarButtonCaption("Cancelar");
					picker.OverlayController.SetSearchBarKeyboardType(UIKeyboardType.Default);
					picker.OverlayController.SetSearchBarPlaceholderText("Búsqueda por nombre de producto");
					picker.OverlayController.SetCameraSwitchVisibility(SICameraSwitchVisibility.OnTablet);
					picker.OverlayController.SetTextForInitializingCamera("Iniciando la camara");
					this.PresentViewController (picker, true, null);
					picker.StartScanning ();
				}else{
					UIAlertView alert = new UIAlertView () { 
						Title = "Espera!", Message = "Debes seleccionar tu ubicacion antes de comenzar a usar FixBuy, por favor ingresa " +
							"Al menu de opciones para establecerla"
					};
					alert.AddButton ("Aceptar");
					alert.Clicked += (s, o) => {
						StatesView statesView = new StatesView();
						this.NavigationController.PushViewController(statesView, true);
					};
					alert.Show ();
				}
			};
		}
 /*
  * Start receiving location updates
  */
 public void StartLocationUpdates()
 {
     manager.DesiredAccuracy   = CLLocation.AccuracyBest;
     manager.LocationsUpdated += LocationHandler;
     manager.StartUpdatingLocation();
 }
Beispiel #49
0
        public async Task <bool> StartListeningAsync(TimeSpan minimumTime, double minimumDistance, bool includeHeading = false, ListenerSettings listenerSettings = null)
        {
            if (minimumDistance < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(minimumDistance));
            }

            if (isListening)
            {
                throw new InvalidOperationException("Already listening");
            }

            // if no settings were passed in, instantiate the default settings. need to check this and create default settings since
            // previous calls to StartListeningAsync might have already configured the location manager in a non-default way that the
            // caller of this method might not be expecting. the caller should expect the defaults if they pass no settings.
            if (listenerSettings == null)
            {
                listenerSettings = new ListenerSettings();
            }

#if __IOS__
            var permission = Permission.Location;
            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                if (listenerSettings.AllowBackgroundUpdates)
                {
                    permission = Permission.LocationAlways;
                }
                else
                {
                    permission = Permission.LocationWhenInUse;
                }
            }

            var hasPermission = await CheckPermissions(permission);


            if (!hasPermission)
            {
                throw new GeolocationException(GeolocationError.Unauthorized);
            }
#endif

            // keep reference to settings so that we can stop the listener appropriately later
            this.listenerSettings = listenerSettings;

            var desiredAccuracy = DesiredAccuracy;

            // set background flag
#if __IOS__
            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                manager.AllowsBackgroundLocationUpdates = listenerSettings.AllowBackgroundUpdates;
            }

            // configure location update pausing
            if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
            {
                manager.PausesLocationUpdatesAutomatically = listenerSettings.PauseLocationUpdatesAutomatically;

                switch (listenerSettings.ActivityType)
                {
                case ActivityType.AutomotiveNavigation:
                    manager.ActivityType = CLActivityType.AutomotiveNavigation;
                    break;

                case ActivityType.Fitness:
                    manager.ActivityType = CLActivityType.Fitness;
                    break;

                case ActivityType.OtherNavigation:
                    manager.ActivityType = CLActivityType.OtherNavigation;
                    break;

                default:
                    manager.ActivityType = CLActivityType.Other;
                    break;
                }
            }
#endif

            // to use deferral, CLLocationManager.DistanceFilter must be set to CLLocationDistance.None, and CLLocationManager.DesiredAccuracy must be
            // either CLLocation.AccuracyBest or CLLocation.AccuracyBestForNavigation. deferral only available on iOS 6.0 and above.
            if (CanDeferLocationUpdate && listenerSettings.DeferLocationUpdates)
            {
                minimumDistance = CLLocationDistance.FilterNone;
                desiredAccuracy = CLLocation.AccuracyBest;
            }

            isListening             = true;
            manager.DesiredAccuracy = desiredAccuracy;
            manager.DistanceFilter  = minimumDistance;

#if __IOS__ || __MACOS__
            if (listenerSettings.ListenForSignificantChanges)
            {
                manager.StartMonitoringSignificantLocationChanges();
            }
            else
            {
                manager.StartUpdatingLocation();
            }
#elif __TVOS__
            //not supported
#endif

#if __IOS__
            if (includeHeading && CLLocationManager.HeadingAvailable)
            {
                manager.StartUpdatingHeading();
            }
#endif

            return(true);
        }
 public void CurrentLocation(CLLocationManager locationManager)
 {
     locationManager.StartUpdatingLocation();
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            try{
                mapView = new MKMapView(View.Bounds);
                mapView.AutoresizingMask = UIViewAutoresizing.FlexibleDimensions;
                View.AddSubview(mapView);

                //Verificar si el dispositivo es un ipad o un iphone para cargar la tabla correspondiente a cada dispositivo
                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                {
                    Title                = "Tiendas";
                    tiendaCercana        = new UIBarButtonItem(UIBarButtonSystemItem.Search);
                    tiendaCercana.Target = this;
                    this.NavigationItem.RightBarButtonItem = tiendaCercana;
                }
                else
                {
                    Title = "Tiendas registradas";
                    //Creamos el boton para buscar la tienda mas cercana.
                    tiendaCercana        = new UIBarButtonItem();
                    tiendaCercana.Style  = UIBarButtonItemStyle.Plain;
                    tiendaCercana.Target = this;
                    tiendaCercana.Title  = "Buscar tienda cercana";
                    this.NavigationItem.RightBarButtonItem = tiendaCercana;
                }

                //inicializacion del manejador de localizacion.
                iPhoneLocationManager = new CLLocationManager();
                //Establecer la precision del manejador de localizacion.
                iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters;

                iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                    newLocation = e.Locations [e.Locations.Length - 1];
                };

                List <StoresService> tiendas = storesService.All();

                //mostramos los puntos rojos sobre cada una de las tiendas registradas.
                foreach (StoresService tienda in tiendas)
                {
                    Console.WriteLine(tienda.nombre + " " + tienda.latitud + " " + tienda.longitud);
                    double distancia1 = iPhoneLocationManager.Location.DistanceFrom(new CLLocation(Double.Parse(tienda.latitud), Double.Parse(tienda.longitud))) / 1000;
                    var    annotation = new BasicMapAnnotation(new CLLocationCoordinate2D(Double.Parse(tienda.latitud), Double.Parse(tienda.longitud)), "" + tienda.nombre + " (" + Math.Round(distancia1, 2) + "km)", "" + tienda.direccion);
                    mapView.AddAnnotation(annotation);
                }

                //Mostramos la ubicacion del usuario.
                mapView.ShowsUserLocation = true;
                MKUserLocation usr = mapView.UserLocation;
                usr.Title = "Tú estas aqui";

                // establecemos la region a mostrar, poniendo a Chihuahua como region
                var coords = new CLLocationCoordinate2D(28.6352778, -106.08888890000003);         // Chihuahua
                var span   = new MKCoordinateSpan(MilesToLatitudeDegrees(10), MilesToLongitudeDegrees(10, coords.Latitude));

                // se establece la region.
                mapView.Region = new MKCoordinateRegion(coords, span);

                //Mostrar los diferentes tipos de mapas
                int typesWidth = 260, typesHeight = 30, distanceFromBottom = 60;
                mapTypes = new UISegmentedControl(new CGRect((View.Bounds.Width - typesWidth) / 2, View.Bounds.Height - distanceFromBottom, typesWidth, typesHeight));
                mapTypes.InsertSegment("Mapa", 0, false);
                mapTypes.InsertSegment("Satelite", 1, false);
                mapTypes.InsertSegment("Ambos", 2, false);
                mapTypes.SelectedSegment  = 0;        // Road is the default
                mapTypes.AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin;
                mapTypes.ValueChanged    += (s, e) => {
                    switch (mapTypes.SelectedSegment)
                    {
                    case 0:
                        mapView.MapType = MKMapType.Standard;
                        break;

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

                    case 2:
                        mapView.MapType = MKMapType.Hybrid;
                        break;
                    }
                };
                View.AddSubview(mapTypes);


                //Añadimos el evento para buscar tienda mas cercana.
                tiendaCercana.Clicked += (sender, e) => {
                    try{
                        StoresService tiendac   = nearestStore(newLocation, tiendas);
                        double        distancia = newLocation.DistanceFrom(new CLLocation(Double.Parse(tiendac.latitud), Double.Parse(tiendac.longitud))) / 1000;
                        UIAlertView   alert     = new UIAlertView()
                        {
                            Title = "Tu tienda mas cercana es:", Message = "" + tiendac.nombre + "\n " + tiendac.direccion + "\n" + "Distancia: " + Math.Round(distancia, 2) + "km"
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();

                        var coords1 = new CLLocationCoordinate2D(Double.Parse(tiendac.latitud), Double.Parse(tiendac.longitud));
                        var span1   = new MKCoordinateSpan(MilesToLatitudeDegrees(0.2), MilesToLongitudeDegrees(0.2, coords.Latitude));

                        // set the coords and zoom on the map
                        mapView.Region = new MKCoordinateRegion(coords1, span1);
                    }catch (Exception) {
                        UIAlertView alert = new UIAlertView()
                        {
                            Title = "Ups =(", Message = "Algo salio mal, por favor intentalo de nuevo."
                        };
                        alert.AddButton("Aceptar");
                        alert.Show();
                    }
                };

                // Manejamos la actualizacion de la localizacion del dispositivo.
                iPhoneLocationManager.RequestAlwaysAuthorization();
                if (CLLocationManager.LocationServicesEnabled)
                {
                    iPhoneLocationManager.StartUpdatingLocation();
                }
            } catch (System.Net.WebException) {
                UIAlertView alert = new UIAlertView()
                {
                    Title = "Ups =(", Message = "Algo salio mal, verifica tu conexión a internet e intentalo de nuevo."
                };
                alert.AddButton("Aceptar");
                alert.Show();
            } catch (Exception) {
                UIAlertView alert = new UIAlertView()
                {
                    Title = "Ups =(", Message = "Algo salio mal, por favor intentalo de nuevo."
                };
                alert.AddButton("Aceptar");
                alert.Show();
            }
        }
Beispiel #52
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // no XIB !
            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();

            segmentedControl.Frame = new RectangleF(20, 320, 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;

            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, this.View.Frame.Width, this.View.Frame.Height - 100);

            MKCoordinateSpan   span   = new MKCoordinateSpan(0.2, 0.2);
            MKCoordinateRegion region = new MKCoordinateRegion(ConferenceLocation, span);

            mapView.SetRegion(region, true);

            ConferenceAnnotation a = new ConferenceAnnotation(ConferenceLocation
                                                              , conf.Location.Title
                                                              , conf.Location.Subtitle
                                                              );

            mapView.AddAnnotationObject(a);


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

            // Add the table view as a subview
            this.View.AddSubview(mapView);
            this.View.AddSubview(labelDistance);
            this.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();
            };
            this.View.AddSubview(flipButton);
        }
Beispiel #53
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            MapDelegate mapDelegate = new MapDelegate();

            mapView.Delegate = mapDelegate;


            MKCoordinateRegion region = new MKCoordinateRegion();

            #region Location ausgeben (Text)
            locationManager = new CLLocationManager();

            locationManager.RequestAlwaysAuthorization();

            locationManager.LocationsUpdated += (sender, args) =>
            {
                location = args.Locations[0];
                double latitude  = Math.Round(location.Coordinate.Latitude, 4);
                double longitude = Math.Round(location.Coordinate.Longitude, 4);
                double accuracy  = Math.Round(location.HorizontalAccuracy, 0);


                lblOutput.Text = string.Format("Latitude: {0}\nLongitude: {1}\nAccuracy: {2}m", latitude, longitude, accuracy);
                Console.WriteLine("Zeitstempel Standort {0}", location.Timestamp);

                //region = new MKCoordinateRegion();
                //CLLocation secondlocation = new CLLocation(48.88370, 2.294481);
                region.Center = location.Coordinate;

                mapView.SetRegion(region, true);
            };

            locationManager.Failed += (sender, args) =>
            {
                lblOutput.Text = string.Format("Standortbestimmung fehlgeschlagen! \nFehlermeldung: {0}", args.Error.LocalizedDescription);
            };

            btnlocalize.TouchUpInside += (sender, args) =>
            {
                lblOutput.Text = "Bestimme Standort...";
                locationManager.StartUpdatingLocation();
            };

            btnStop.TouchUpInside += (sender, args) =>
            {
                locationManager.StopUpdatingLocation();
                lblOutput.Text = "Standortbestimmung beendet...";
            };
            #endregion

            #region Location in Map ausgeben

            //Aktuelle Position anzeigen
            mapView.ShowsUserLocation = true;
            mapView.ZoomEnabled       = true;

            mapView.MapType = MKMapType.Standard;

            //Karte auf der Position zentrieren
            //MKCoordinateRegion region = new MKCoordinateRegion();
            CLLocation secondlocation = new CLLocation(37.687834, -122.406417);
            region.Center = secondlocation.Coordinate;

            //Zoom-Level setzen
            MKCoordinateSpan span = new MKCoordinateSpan();
            span.LatitudeDelta  = 0.5;
            span.LongitudeDelta = 0.5;
            region.Span         = span;

            mapView.SetRegion(region, true);

            //Pin auf Karte setzen
            mapView.AddAnnotation(new MKPointAnnotation()
            {
                Title      = "Sehenswürdigkeit",
                Coordinate = new CLLocationCoordinate2D(37.687834, -122.406417)
            });

            MKPointAnnotation myAnnotation = new MKPointAnnotation();
            myAnnotation.Coordinate = new CLLocationCoordinate2D(37.687834, -122.406417);
            myAnnotation.Title      = "Unsere Position";

            MKPointAnnotation mysecondAnnotation = new MKPointAnnotation();
            mysecondAnnotation.Coordinate = new CLLocationCoordinate2D(37.787834, -122.406417);
            mysecondAnnotation.Title      = "Unsere Position";
            mapView.AddAnnotations(new IMKAnnotation[] { myAnnotation, mysecondAnnotation });

            //mapView.GetViewForAnnotation += (mapView, annotation) =>
            //{
            //    string pID = "PinAnnotation";
            //    if (annotation is MKPointAnnotation)
            //    {
            //        MKPinAnnotationView pinView = (MKPinAnnotationView)mapView.DequeueReusableAnnotation(pID);
            //        if (pinView == null)
            //            pinView = new MKPinAnnotationView(annotation, pID);

            //        pinView.PinColor = MKPinAnnotationColor.Green;
            //        pinView.CanShowCallout = true;
            //        pinView.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure);
            //        pinView.LeftCalloutAccessoryView = new UIImageView(UIImage.FromBundle("Default.png"));
            //        return pinView;
            //    }
            //    else
            //    {
            //        return null;
            //    }
            //};

            //var circleOverlay = MKCircle.Circle(secondlocation.Coordinate, 1000);
            //mapView.AddOverlay(circleOverlay);

            //var circleView = new MKCircleView(circleOverlay);
            //circleView.FillColor = UIColor.Blue;
            //mapView.AddOverlay(mapView,  circleView);

            MKPolygon hotelOverlay = MKPolygon.FromCoordinates(
                new CLLocationCoordinate2D[]
            {
                new CLLocationCoordinate2D(37.787834, -122.406417),
                new CLLocationCoordinate2D(37.797834, -122.406417),
                new CLLocationCoordinate2D(37.797834, -122.416417),
                new CLLocationCoordinate2D(37.787834, -122.416417),
                new CLLocationCoordinate2D(37.787834, -122.406417),
            });
            mapView.AddOverlay(hotelOverlay);
            #endregion

            #region Suchleiste in der Map
            //var searchResultContainer = new SearchResultsViewController(mapView);
            //var searchUpdater = new UISearchResultsUpdating();

            //UISearchController searchController = new UISearchController(searchResultsController: null);

            #endregion
        }
Beispiel #54
0
 private void initLocation()
 {
     //location stuff
     locationManger = new CLLocationManager ();
     locationManger.DistanceFilter = 15;//must move 10 meters between updates (seems reasonable)
     locationManger.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters * 3;//30 meter accuracy
     locationManger.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => {
         locationChanged (e.NewLocation);
     };
     if (CLLocationManager.LocationServicesEnabled && UserPreferences.PreferCurrentLocation)
         locationManger.StartUpdatingLocation ();
 }
Beispiel #55
0
 public override void WillEnterForeground(UIApplication application)
 {
     locationManager.StartUpdatingLocation();
 }
        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();

            InitElements();

            if (!databaseMethods.GetShowMapHint())
            {
                hintView.Hidden = true;
            }
            okBn.TouchUpInside += (s, e) =>
            {
                hintView.Hidden = true;
            };
            neverShowBn.TouchUpInside += (s, e) =>
            {
                hintView.Hidden = true;
                databaseMethods.InsertMapHint(false);
            };

            backBn.TouchUpInside += (s, e) =>
            {
                this.NavigationController.PopViewController(true);
            };
            camera = CameraPosition.FromCamera(latitude: Convert.ToDouble(lat, CultureInfo.InvariantCulture),
                                               longitude: Convert.ToDouble(lng, CultureInfo.InvariantCulture),
                                               zoom: zoom);
            mapView                        = MapView.FromCamera(CGRect.Empty, camera);
            mapView.Frame                  = new Rectangle(0, Convert.ToInt32(headerView.Frame.Height), Convert.ToInt32(View.Frame.Width), Convert.ToInt32(View.Frame.Height));
            mapView.MyLocationEnabled      = true;
            mapView.CoordinateLongPressed += HandleLongPress;
            mapView.UserInteractionEnabled = true;
            setMoscowCameraView();
            applyAddressBn.BackgroundColor = UIColor.FromRGB(255, 99, 62);
            applyAddressBn.Frame           = new Rectangle(Convert.ToInt32(View.Frame.Width) / 15,
                                                           (Convert.ToInt32(View.Frame.Height - View.Frame.Height / 10)),
                                                           Convert.ToInt32(View.Frame.Width) - ((Convert.ToInt32(View.Frame.Width) / 15) * 2),
                                                           Convert.ToInt32(View.Frame.Height) / 12);

            if (!methods.IsConnected())
            {
                NoConnectionViewController.view_controller_name = GetType().Name;
                this.NavigationController.PushViewController(sb.InstantiateViewController(nameof(NoConnectionViewController)), false);
                return;
            }
            address_textView.Hidden = true;
            View.AddSubviews(mapView, centerPositionBn, applyAddressBn, /*address_textView,*/ hintView);

            var mgr = new CLLocationManager();

            try
            {
                var lati = mgr.Location.Coordinate.Latitude.ToString().Replace(',', '.');
                var lngi = mgr.Location.Coordinate.Longitude.ToString().Replace(',', '.');

                camera = CameraPosition.FromCamera(latitude: Convert.ToDouble(lati, CultureInfo.InvariantCulture),
                                                   longitude: Convert.ToDouble(lngi, CultureInfo.InvariantCulture),
                                                   zoom: zoom);
                mapView.Camera = camera;
            }
            catch { }
            bool updated = false;

            mgr.LocationsUpdated += (sender, e) =>
            {
                if (!updated)
                {
                    foreach (var locss in e.Locations)
                    {
                        var lati = e.Locations[0].Coordinate.Latitude.ToString().Replace(',', '.');
                        var lngi = e.Locations[0].Coordinate.Longitude.ToString().Replace(',', '.');
                        camera = CameraPosition.FromCamera(latitude: Convert.ToDouble(lati, CultureInfo.InvariantCulture),
                                                           longitude: Convert.ToDouble(lngi, CultureInfo.InvariantCulture),
                                                           zoom: zoom);

                        try
                        {
                            if (!String.IsNullOrEmpty(lat) && !String.IsNullOrEmpty(lng))
                            {
                                camera = CameraPosition.FromCamera(latitude: Convert.ToDouble(lat, CultureInfo.InvariantCulture),
                                                                   longitude: Convert.ToDouble(lng, CultureInfo.InvariantCulture),
                                                                   zoom: zoom);
                            }
                        }
                        catch { }
                        if (String.IsNullOrEmpty(lat_temporary) && String.IsNullOrEmpty(lng_temporary))
                        {
                            mapView.Camera = camera;
                        }
                    }
                }
                updated = true;
            };
            mgr.StartUpdatingLocation();
            centerPositionBn.TouchUpInside += (s, e) =>
            {
                mgr = new CLLocationManager();
                try
                {
                    var latitude  = mgr.Location.Coordinate.Latitude.ToString().Replace(',', '.');
                    var longitude = mgr.Location.Coordinate.Longitude.ToString().Replace(',', '.');

                    camera = CameraPosition.FromCamera(latitude: Convert.ToDouble(latitude, CultureInfo.InvariantCulture),
                                                       longitude: Convert.ToDouble(longitude, CultureInfo.InvariantCulture),
                                                       zoom: zoom);
                    mapView.Camera = camera;
                }
                catch { }
            };

            try
            {
                if (lat == null && lng == null)
                {
                    try
                    {
                        var sd = await GeocodeToConsoleAsync(HomeAddressViewController.FullAddressTemp);
                    }
                    catch
                    {
                        if (!methods.IsConnected())
                        {
                            InvokeOnMainThread(() =>
                            {
                                NoConnectionViewController.view_controller_name = GetType().Name;
                                this.NavigationController.PushViewController(sb.InstantiateViewController(nameof(NoConnectionViewController)), false);
                                return;
                            });
                        }
                        return;
                    }
                }
                else
                {
                    CLLocationCoordinate2D coord = new CLLocationCoordinate2D(Convert.ToDouble(lat, CultureInfo.InvariantCulture), Convert.ToDouble(lng, CultureInfo.InvariantCulture));
                    var marker = Marker.FromPosition(coord);
                    //marker.Title = string.Format("Marker 1");
                    marker.Icon = UIImage.FromBundle("add_loc_marker.png");
                    marker.Map  = mapView;
                    camera      = CameraPosition.FromCamera(latitude: Convert.ToDouble(lat, CultureInfo.InvariantCulture),
                                                            longitude: Convert.ToDouble(lng, CultureInfo.InvariantCulture),
                                                            zoom: zoom);
                    mapView.Camera = camera;
                }
            }
            catch { }
            applyAddressBn.TouchUpInside += (s, e) =>
            {
                HomeAddressViewController.changedSomething = true;
                if (!String.IsNullOrEmpty(lat_temporary) && !String.IsNullOrEmpty(lng_temporary))
                {
                    lat = lat_temporary;
                    lng = lng_temporary;
                }
                else
                {
                    try
                    {
                        lat = mgr.Location.Coordinate.Latitude.ToString().Replace(',', '.');
                        lng = mgr.Location.Coordinate.Longitude.ToString().Replace(',', '.');
                    }
                    catch { }
                }
                HomeAddressViewController.came_from_map = true;
                this.NavigationController.PopViewController(true);
            };
        }
Beispiel #57
0
 public void StartTracking()
 {
     locationManager.StartUpdatingLocation();
 }
Beispiel #58
0
        private async Task <NSDictionary> BuildGPSDataAsync()
        {
            // setup the location manager
            if (_locationManager == null)
            {
                _locationManager = new CLLocationManager();
                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    _locationManager.RequestWhenInUseAuthorization();
                }
                _locationManager.DesiredAccuracy = 1; // in meters
            }

            // setup a task for getting the current location and a callback for receiving the location
            _locationTCS = new TaskCompletionSource <CLLocation>();
            _locationManager.LocationsUpdated += (sender, locationArgs) =>
            {
                if (locationArgs.Locations.Length > 0)
                {
                    _locationManager.StopUpdatingLocation();
                    _locationTCS.TrySetResult(locationArgs.Locations[locationArgs.Locations.Length - 1]);
                }
            };
            // start location monitoring
            _locationManager.StartUpdatingLocation();

            // create a timeout and location task to ensure we don't wait forever
            var timeoutTask  = System.Threading.Tasks.Task.Delay(5000); // 5 second wait
            var locationTask = _locationTCS.Task;

            // try and set a location based on whatever task ends first
            CLLocation location;
            var        completeTask = await System.Threading.Tasks.Task.WhenAny(locationTask, timeoutTask);

            if (completeTask == locationTask && completeTask.Status == TaskStatus.RanToCompletion)
            {
                // use the location result
                location = locationTask.Result;
            }
            else
            {
                // timeout - stop the location manager and try and use the last location
                _locationManager.StopUpdatingLocation();
                location = _locationManager.Location;
            }

            if (location == null)
            {
                return(null);
            }

            var gpsData = new NSDictionary(
                ImageIO.CGImageProperties.GPSLatitude, Math.Abs(location.Coordinate.Latitude),
                ImageIO.CGImageProperties.GPSLatitudeRef, (location.Coordinate.Latitude >= 0) ? "N" : "S",
                ImageIO.CGImageProperties.GPSLongitude, Math.Abs(location.Coordinate.Longitude),
                ImageIO.CGImageProperties.GPSLongitudeRef, (location.Coordinate.Longitude >= 0) ? "E" : "W",
                ImageIO.CGImageProperties.GPSAltitude, Math.Abs(location.Altitude),
                ImageIO.CGImageProperties.GPSDateStamp, DateTime.UtcNow.ToString("yyyy:MM:dd"),
                ImageIO.CGImageProperties.GPSTimeStamp, DateTime.UtcNow.ToString("HH:mm:ss.ff")
                );

            return(gpsData);
        }
Beispiel #59
0
        private void MonitorLocation(UIApplicationState appState)
        {
            if (CLLocationManager.LocationServicesEnabled)
            {
                LastSentLocationTime  = new DateTime(0);
                FirstSentLocationTime = new DateTime(0);
                Console.WriteLine("MONITOR LOCATION");

                GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "location", "monitor location", null).Build());

                LocationManager = new CLLocationManager();
                LocationManager.DesiredAccuracy = 10;
                LocationManager.PausesLocationUpdatesAutomatically = false;

                LocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
                    CLLocation currentLocation  = e.Locations[e.Locations.Length - 1];
                    DateTime   locationDateTime = DateTime.SpecifyKind(currentLocation.Timestamp, DateTimeKind.Utc);

                    double timeremaining = UIApplication.SharedApplication.BackgroundTimeRemaining;

                    Console.WriteLine("LOCATION UPDATE - Time Remaining: " + timeremaining.ToString());

                    if (LastSentLocationTime.Ticks == 0)
                    {
                        Console.WriteLine("FIRST LOCATION SENT");
                        sendLocation(currentLocation);
                        FirstSentLocationTime = locationDateTime;
                        LastSentLocationTime  = locationDateTime;
                    }
                    else
                    {
                        var diffInSeconds = (locationDateTime - LastSentLocationTime).TotalSeconds;
                        if (diffInSeconds >= 10.0)
                        {
                            Console.WriteLine("LOCATION SENT");
                            GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "location", "location sent", null).Build());
                            sendLocation(currentLocation);
                            LastSentLocationTime = locationDateTime;
                        }

                        var diffInSecondsFromFirst = (locationDateTime - FirstSentLocationTime).TotalSeconds;
                        if (diffInSecondsFromFirst >= 120)
                        {
                            Console.WriteLine("STOP MONITOR LOCATION");
                            GAI.SharedInstance.DefaultTracker.Send(GAIDictionaryBuilder.CreateEvent("app_action", "location", "stop monitor location", null).Build());
                            if (LocationManager != null)
                            {
                                LocationManager.StopUpdatingLocation();
                                LocationManager.StopMonitoringSignificantLocationChanges();
                            }

                            LocationManager = null;
                        }
                    }
                };


                if (appState == UIApplicationState.Active)
                {
                    LocationManager.StartUpdatingLocation();
                }
                else
                {
                    LocationManager.StartMonitoringSignificantLocationChanges();
                }
            }
            else
            {
                Console.WriteLine("Location services not enabled");
            }
        }
 public void StartLocationRequest()
 {
     manager.StartUpdatingLocation();
 }