internal override void CheckAndEnableSensors() { base.CheckAndEnableSensors(); if (Accelerometer.ShouldBeEnabled) { motionManager.StartAccelerometerUpdates(); } if ((Compass.ShouldBeEnabled || Orientation.ShouldBeEnabled) && !locationManagerActivated) { locationManagerActivated = true; locationManager.StartUpdatingHeading(); } if (Gyroscope.ShouldBeEnabled) { motionManager.StartGyroUpdates(); } if ((UserAcceleration.ShouldBeEnabled || Gravity.ShouldBeEnabled || Orientation.ShouldBeEnabled) && !motionManager.DeviceMotionActive) { motionManager.StartDeviceMotionUpdates(); } }
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(); } }
/// <summary> /// Start listening to location changes /// </summary> /// <param name="minTime">Minimum interval in milliseconds</param> /// <param name="minDistance">Minimum distance in meters</param> /// <param name="includeHeading">Include heading information</param> /// <exception cref="ArgumentOutOfRangeException"> /// minTime /// or /// minDistance /// </exception> /// <exception cref="InvalidOperationException">Already listening</exception> public void StartListening(uint minTime, double minDistance, bool includeHeading) { if (minTime < 0) { throw new ArgumentOutOfRangeException("minTime"); } if (minDistance < 0) { throw new ArgumentOutOfRangeException("minDistance"); } if (IsListening) { throw new InvalidOperationException("Already listening"); } IsListening = true; _manager.DesiredAccuracy = DesiredAccuracy; _manager.DistanceFilter = minDistance; _manager.StartUpdatingLocation(); if (includeHeading && CLLocationManager.HeadingAvailable) { _manager.StartUpdatingHeading(); } }
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 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 void ViewDidLoad() { base.ViewDidLoad(); // load the appropriate view, based on the device type // initialize our location manager and callback handler iPhoneLocationManager = new CLLocationManager(); double longdute; double latidute; // 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(this, e.Locations [e.Locations.Length - 1]); iPhoneLocationManager.StopUpdatingLocation(); }; } else { // this won't be called on iOS 6 (deprecated) iPhoneLocationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => { UpdateLocation(this, e.NewLocation); iPhoneLocationManager.StopUpdatingLocation(); }; } // handle the updated heading method and update the UI iPhoneLocationManager.UpdatedHeading += (object sender, CLHeadingUpdatedEventArgs e) => { // GPSLocate.LblMagneticHeading.Text = e.NewHeading.MagneticHeading.ToString () + "º"; // GPSLocate.LblTrueHeading.Text = e.NewHeading.TrueHeading.ToString () + "º"; }; // start updating our location, et. al. if (CLLocationManager.LocationServicesEnabled) { iPhoneLocationManager.StartUpdatingLocation(); } if (CLLocationManager.HeadingAvailable) { iPhoneLocationManager.StartUpdatingHeading(); } }
/// <summary> /// Start listening to location changes /// </summary> /// <param name="minTime">Minimum interval in milliseconds</param> /// <param name="minDistance">Minimum distance in meters</param> /// <param name="includeHeading">Include heading information</param> /// <exception cref="ArgumentOutOfRangeException"> /// minTime /// or /// minDistance /// </exception> /// <exception cref="InvalidOperationException">Already listening</exception> public void StartListening(uint minTime, double minDistance, bool includeHeading) { if (minTime < 0) { throw new ArgumentOutOfRangeException("minTime"); } if (minDistance < 0) { throw new ArgumentOutOfRangeException("minDistance"); } if (IsListening) { throw new InvalidOperationException("Already listening"); } // 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 IsListening = true; _manager.DesiredAccuracy = DesiredAccuracy; _manager.DistanceFilter = minDistance; _manager.StartUpdatingLocation(); if (includeHeading && CLLocationManager.HeadingAvailable) { _manager.StartUpdatingHeading(); } }
internal static void PlatformStart(SensorSpeed sensorSpeed) { locationManager = new CLLocationManager(); switch (sensorSpeed) { case SensorSpeed.Fastest: locationManager.HeadingFilter = FastestFilter; locationManager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation; break; case SensorSpeed.Game: locationManager.HeadingFilter = GameFilter; locationManager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation; break; case SensorSpeed.Normal: locationManager.HeadingFilter = NormalFilter; locationManager.DesiredAccuracy = CLLocation.AccuracyBest; break; case SensorSpeed.Ui: locationManager.HeadingFilter = UiFilter; locationManager.DesiredAccuracy = CLLocation.AccuracyBest; break; } locationManager.UpdatedHeading += LocationManagerUpdatedHeading; locationManager.StartUpdatingHeading(); }
public void SetUpLocationManger() { beaconUUID = new NSUuid(BeaconCreds.UUID); LocationManager = new CLLocationManager(); LocationManager.RequestAlwaysAuthorization(); LocationManager.StartUpdatingHeading(); if (BeaconCreds.BeaconMonitoring == BeaconMonitoring.Proximity) { BeaconsRegion = new CLBeaconRegion(beaconUUID, BeaconCreds.BeaconsRegion); LocationManager.StartRangingBeacons(BeaconsRegion); } else { BeaconsRegionsList = new List <CLBeaconRegion>(); foreach (Beacon beacon in Beacons.BeaconList) { CLBeaconRegion tempRegion = new CLBeaconRegion(beaconUUID, (ushort)beacon.Major, (ushort)beacon.Minor, beacon.RegionId); tempRegion.NotifyEntryStateOnDisplay = true; tempRegion.NotifyOnEntry = true; tempRegion.NotifyOnExit = true; BeaconsRegionsList.Add(tempRegion); LocationManager.StartMonitoring(tempRegion); } } }
public void GetLocation(GetLocationActions locActions, UITextField textField) { if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0)) { iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => { UpdateLocation(e.Locations [e.Locations.Length - 1], iPhoneLocationManager, locActions, textField); }; } else { // this won't be called on iOS 6 (deprecated) iPhoneLocationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => { UpdateLocation(e.NewLocation, iPhoneLocationManager, locActions, textField); }; } // handle the updated heading method and update the UI iPhoneLocationManager.UpdatedHeading += (object sender, CLHeadingUpdatedEventArgs e) => { Console.WriteLine(e.NewHeading.MagneticHeading.ToString() + "º"); Console.WriteLine(e.NewHeading.TrueHeading.ToString() + "º"); }; // start updating our location, et. al. if (CLLocationManager.LocationServicesEnabled) { iPhoneLocationManager.StartUpdatingLocation(); } if (CLLocationManager.HeadingAvailable) { iPhoneLocationManager.StartUpdatingHeading(); } }
public IObservable <double> WhenReadingTaken() { this.readOb = this.readOb ?? Observable.Create <double>(ob => { var handler = new EventHandler <CLHeadingUpdatedEventArgs>((sender, args) => { // TODO: TrueHeading, MagneticHeading, Accuracy ob.OnNext(args.NewHeading.TrueHeading); }); var lm = new CLLocationManager { DesiredAccuracy = CLLocation.AccuracyBest, HeadingFilter = 1 }; lm.UpdatedHeading += handler; lm.StartUpdatingHeading(); return(() => { lm.StopUpdatingHeading(); lm.UpdatedHeading -= handler; }); }); return(this.readOb); }
public IObservable <CompassReading> WhenReadingTaken() => this.readOb ??= Observable.Create <CompassReading>(ob => { var handler = new EventHandler <CLHeadingUpdatedEventArgs>((sender, args) => { var accuracy = this.FromNative(args.NewHeading.HeadingAccuracy); var read = new CompassReading(accuracy, args.NewHeading.MagneticHeading, args.NewHeading.TrueHeading); ob.OnNext(read); }); var lm = new CLLocationManager { DesiredAccuracy = CLLocation.AccuracyBest, HeadingFilter = 1 }; lm.UpdatedHeading += handler; lm.StartUpdatingHeading(); return(() => { lm.StopUpdatingHeading(); lm.UpdatedHeading -= handler; }); }) .Publish() .RefCount();
internal static void PlatformStart(SensorSpeed sensorSpeed, bool applyLowPassFilter) { locationManager = new CLLocationManager(); locationManager.ShouldDisplayHeadingCalibration += LocationManagerShouldDisplayHeadingCalibration; switch (sensorSpeed) { case SensorSpeed.Fastest: locationManager.HeadingFilter = FastestFilter; locationManager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation; break; case SensorSpeed.Game: locationManager.HeadingFilter = GameFilter; locationManager.DesiredAccuracy = CLLocation.AccurracyBestForNavigation; break; case SensorSpeed.Default: locationManager.HeadingFilter = NormalFilter; locationManager.DesiredAccuracy = CLLocation.AccuracyBest; break; case SensorSpeed.UI: locationManager.HeadingFilter = UIFilter; locationManager.DesiredAccuracy = CLLocation.AccuracyBest; break; } locationManager.UpdatedHeading += LocationManagerUpdatedHeading; locationManager.StartUpdatingHeading(); }
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(); } }
/// <summary> /// Start tracking changes /// </summary> public override void Start() { if (locationManager == null) { locationManager = new CLLocationManager(); locationManager.DesiredAccuracy = CLLocation.AccuracyBest; locationManager.HeadingFilter = 1; locationManager.UpdatedHeading += LocationManager_UpdatedHeading; } locationManager.StartUpdatingHeading(); }
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(); }
/// <summary> /// Start the specified sensorType and interval. /// </summary> /// <param name="sensorType">Sensor type.</param> /// <param name="interval">Interval.</param> public void Start(MotionSensorType sensorType, MotionSensorDelay interval) { switch (sensorType) { case MotionSensorType.Accelerometer: if (motionManager.AccelerometerAvailable) { motionManager.AccelerometerUpdateInterval = (double)interval / ms; motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, OnAccelerometerChanged); } else { Debug.WriteLine("Accelerometer not available"); } break; case MotionSensorType.Gyroscope: if (motionManager.GyroAvailable) { motionManager.GyroUpdateInterval = (double)interval / ms; motionManager.StartGyroUpdates(NSOperationQueue.CurrentQueue, OnGyroscopeChanged); } else { Debug.WriteLine("Gyroscope not available"); } break; case MotionSensorType.Magnetometer: if (motionManager.MagnetometerAvailable) { motionManager.MagnetometerUpdateInterval = (double)interval / ms; motionManager.StartMagnetometerUpdates(NSOperationQueue.CurrentQueue, OnMagnometerChanged); } else { Debug.WriteLine("Magnetometer not available"); } break; case MotionSensorType.Compass: if (CLLocationManager.HeadingAvailable) { locationManager.StartUpdatingHeading(); locationManager.UpdatedHeading += OnHeadingChanged; } else { Debug.WriteLine("Compass not available"); } break; } sensorStatus[sensorType] = true; }
public GeoLocationModel GetGeoLocation(bool IncludeHeading = false) { GeoLocationModel geoLocation = new GeoLocationModel(); locationManager = new CLLocationManager(); // 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; // handle the updated location method and update the UI if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0)) { locationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => { CLLocation newLocation = e.Locations[e.Locations.Length - 1]; geoLocation.Latitude = newLocation.Coordinate.Latitude; geoLocation.Longitude = newLocation.Coordinate.Longitude; }; } else { #pragma warning disable 618 // this won't be called on iOS 6 (deprecated) locationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => { CLLocation newLocation = e.NewLocation; geoLocation.Latitude = newLocation.Coordinate.Latitude; geoLocation.Longitude = newLocation.Coordinate.Longitude; }; #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)) { locationManager.RequestWhenInUseAuthorization(); } // start updating our location, et. al. if (CLLocationManager.LocationServicesEnabled) { locationManager.StartUpdatingLocation(); } if (IncludeHeading && CLLocationManager.HeadingAvailable) { locationManager.StartUpdatingHeading(); } return(geoLocation); }
public override void ViewDidLoad() { base.ViewDidLoad(); // initialize our location manager and callback handler _iPhoneLocationManager = new CLLocationManager(); _iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyBest; _iPhoneLocationManager.HeadingFilter = 1; _iPhoneLocationManager.UpdatedHeading += HandleUpdatedHeading; _iPhoneLocationManager.StartUpdatingHeading(); }
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 iPhoneLocationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => { mainScreen.LblAltitude.Text = e.NewLocation.Altitude.ToString() + "meters"; mainScreen.LblLongitude.Text = e.NewLocation.Coordinate.Longitude.ToString() + "º"; mainScreen.LblLatitude.Text = e.NewLocation.Coordinate.Latitude.ToString() + "º"; mainScreen.LblCourse.Text = e.NewLocation.Course.ToString() + "º"; mainScreen.LblSpeed.Text = e.NewLocation.Speed.ToString() + "meters/s"; // get the distance from here to paris mainScreen.LblDistanceToParis.Text = (e.NewLocation.DistanceFrom(new CLLocation(48.857, 2.351)) / 1000).ToString() + "km"; }; // 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(); } }
void CompassStart() { if (_locationManager != null) { _locationManager = new CLLocationManager(); //_locationManager.Delegate = new CLLocationManagerDelegate(); _locationManager.UpdatedHeading += delegate(object sender, CLHeadingUpdatedEventArgs e) { string javascript = string.Format("compass.onCompassSuccess({0:0.00})", _locationManager.Heading.MagneticHeading); _webView.EvaluateJavascript(javascript); }; _locationManager.StartUpdatingHeading(); } }
/// <summary> /// Comprueba los permisos de localizacion en el dispositivo. /// </summary> private void CompruebaPermisos() { // Comprueba si tiene permiso de localizacion if (CLLocationManager.LocationServicesEnabled) { Localizacion.StartUpdatingLocation(); } // Comprueba si tiene permiso para mostrar la localización if (CLLocationManager.HeadingAvailable) { Localizacion.StartUpdatingHeading(); } }
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(); } }
public void StartLocationUpdates() { if (CLLocationManager.LocationServicesEnabled) { //set the desired accuracy, in meters locationManager.DesiredAccuracy = 1; locationManager.DistanceFilter = 10; locationManager.UpdatedHeading += (object sender, CLHeadingUpdatedEventArgs e) => { // fire our custom Location Updated event HeadingUpdated(this, new HeadingUpdatedEventArgs(e.NewHeading)); }; locationManager.StartUpdatingHeading(); } }
//locatie opvragen private void GetLocation() { CLLocationManager locationManager = new CLLocationManager(); locationManager.StartUpdatingLocation(); locationManager.StartUpdatingHeading(); locationManager.LocationsUpdated += delegate(object sender, CLLocationsUpdatedEventArgs e) { foreach (CLLocation loc in e.Locations) { GetWeatherData(loc.Coordinate.Latitude, loc.Coordinate.Longitude); } }; }
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 (); }
/// <summary> /// Start the specified sensor type reading. /// </summary> /// <param name="sensorType">Sensor type</param> public override void Start(SensorType sensorType) { switch (sensorType) { case SensorType.Accelerometer: AccelerometerActive = true; motionManager.AccelerometerUpdateInterval = 0.05; motionManager.StartAccelerometerUpdates(NSOperationQueue.MainQueue, (data, error) => { EmitAccelerometer(new MotionVector(data.Acceleration.X, data.Acceleration.Y, data.Acceleration.Z)); }); break; case SensorType.Gyroscope: GyroActive = true; motionManager.GyroUpdateInterval = 0.05; motionManager.StartGyroUpdates(NSOperationQueue.MainQueue, (data, error) => { EmitGyroscope(new MotionVector(data.RotationRate.x, data.RotationRate.y, data.RotationRate.z)); }); break; case SensorType.DeviceMotion: DeviceMotionActive = true; motionManager.DeviceMotionUpdateInterval = 0.05d; motionManager.StartDeviceMotionUpdates(NSOperationQueue.MainQueue, (motion, error) => { EmitDeviceMotion(new MotionVector(motion.Attitude.Roll, motion.Attitude.Pitch, motion.Attitude.Yaw)); }); break; case SensorType.Compass: CompassActive = true; locationManager.UpdatedHeading += (sender, eventArgs) => { // TODO: Fix. EmitCompass(eventArgs.NewHeading.TrueHeading); }; locationManager.StartUpdatingHeading(); break; case SensorType.LightLevel: LightLevelActive = false; break; } }
public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. try { //Pass Static Variables Handler._imgBG = imgBG; Handler._imgBase = imgBase; Handler._progressbar = progressLocation; Handler._lblGreeting = lblGreeting; Handler._coordinates = lblCoordinates; //Create Handler Instance Handler eventsHandler = new Handler(); eventsHandler._lblClock = lblTime; eventsHandler.runHandler(); //Setup Defaults btnToggle.SetTitle("", UIControlState.Normal); lblTime.Text = DateTime.Now.ToString("hh:mm:ss t z"); //Setup Locator _iPhoneLocationManager = new CLLocationManager(); _iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyBest; _iPhoneLocationManager.HeadingFilter = 1; _iPhoneLocationManager.UpdatedHeading += HandleDirection; _iPhoneLocationManager.StartUpdatingHeading(); //Admob admob(); } catch { } }
public BeaconLocateriOS() { SetupBeaconRanging(); locationManager.StartMonitoring(rBeaconRegion); locationManager.RequestState(rBeaconRegion); if (locationManager == null) { locationManager = new CLLocationManager(); locationManager.DesiredAccuracy = CLLocation.AccuracyBest; locationManager.HeadingFilter = 1; locationManager.UpdatedHeading += LocationManager_UpdatedHeading;; } else { locationManager.DesiredAccuracy = CLLocation.AccuracyBest; locationManager.HeadingFilter = 1; locationManager.UpdatedHeading += LocationManager_UpdatedHeading;; } locationManager.StartUpdatingHeading(); }
public override void ViewDidLoad() { base.ViewDidLoad(); locationManager = new CLLocationManager(); StartButton.TouchUpInside += (sender, e) => { locationManager.StartUpdatingHeading(); locationManager.UpdatedHeading += (object s, CLHeadingUpdatedEventArgs a) => { AngleLabel.Text = string.Format($"{locationManager.Heading.MagneticHeading:N0}°"); }; }; StopButton.TouchUpInside += (sender, e) => { locationManager.StopUpdatingHeading(); }; }
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 void StartSensorUpdates() { // Raw accelerometer if (_motionManager.AccelerometerAvailable) { _motionManager.StartAccelerometerUpdates(_queue, HandleCMAccelerometerHandler); } if (_motionManager.GyroAvailable) { _motionManager.StartGyroUpdates(_queue, HandleCMGyroHandler); } if (_motionManager.MagnetometerAvailable) { _motionManager.StartMagnetometerUpdates(_queue, HandleCMMagnetometerHandler); } if (_motionManager.DeviceMotionAvailable) { _motionManager.StartDeviceMotionUpdates(_queue, HandleCMDeviceMotionHandler); _pedometer.StartPedometerUpdates(NSDate.Now, HandleCMPedometer); } //start updating headings _locationManager.StartUpdatingHeading(); //// service for measurements once per minute UIDevice.CurrentDevice.BatteryMonitoringEnabled = true; Timer timer = new Timer(60000); timer.AutoReset = true; timer.Elapsed += SensorMeasurementSessionTimerElapsed; timer.Start(); IsListening = true; }
public string ReturnHeading() { if (_lm != null) { _lm = new CLLocationManager(); _lm.UpdatedHeading += HeadingUpdateDelegate; _lm.StartUpdatingHeading(); } // block on the search until the async result return string result; lock (_locker) { while (location == null) { Monitor.Pulse(_locker); } result = location; location = null; } return result; }
/// <summary> /// Start listening for location changes /// </summary> /// <param name="minTime">Minimum interval in milliseconds</param> /// <param name="minDistance">Minimum distance in meters</param> /// <param name="includeHeading">Include heading information</param> /// <exception cref="ArgumentOutOfRangeException"> /// minTime /// or /// minDistance /// </exception> /// <exception cref="InvalidOperationException">Already listening</exception> public OperationResult StartListening(uint minTime, double minDistance, double desiredAccurancy = 0, bool includeHeading = false) { if (IsListening) { return(OperationResult.AsFailure("Already listening")); } if (minTime < 0) { return(OperationResult.AsFailure(new ArgumentOutOfRangeException(nameof(minTime)))); } if (minDistance < 0) { return(OperationResult.AsFailure(new ArgumentOutOfRangeException(nameof(minDistance)))); } _desiredAccuracy = desiredAccurancy; _manager.LocationsUpdated -= OnLocationsUpdated; _manager.UpdatedHeading -= OnHeadingUpdated; _manager.LocationsUpdated += OnLocationsUpdated; _manager.UpdatedHeading += OnHeadingUpdated; IsListening = true; _manager.DesiredAccuracy = _desiredAccuracy; _manager.DistanceFilter = minDistance; _manager.StartUpdatingLocation(); if (includeHeading && CLLocationManager.HeadingAvailable) { _manager.StartUpdatingHeading(); } return(OperationResult.AsSuccess()); }
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 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 (); }
public string ReturnHeading() { if (_lm != null) { _lm = new CLLocationManager(); _lm.UpdatedHeading += HeadingUpdateDelegate; _lm.StartUpdatingHeading(); } // block on the search until the async result return string result; lock (_locker) { while (location == null) { Monitor.Pulse(_locker); } result = location; location = null; } return(result); }
public override void ViewDidLoad() { base.ViewDidLoad (); var locSvc = new ROMPLocation (); myFacilities = locSvc.GetLocations (sessionKey, groupID); locMan = new CLLocationManager (); if (myFacilities.Count () > 0) { if (!CLLocationManager.LocationServicesEnabled) { UIAlertView _error = new UIAlertView ("Error", "Location services not enabled, please enable this in your Settings.", null, "Ok", null); _error.Show (); } else if (CLLocationManager.Status == CLAuthorizationStatus.Denied) { UIAlertView _error = new UIAlertView ("Error", "App is not authorized to use location data.", null, "Ok", null); _error.Show (); } else { //locMan.LocationUpdated += LocationChanged; locMan.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters; if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) { locMan.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => { UpdateLocation (e.Locations [e.Locations.Length - 1]); }; } else { #pragma warning disable 618 // this won't be called on iOS 6 (deprecated) locMan.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => { UpdateLocation (e.NewLocation); }; #pragma warning restore 618 } if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) { locMan.RequestAlwaysAuthorization (); } if (CLLocationManager.LocationServicesEnabled) locMan.StartUpdatingLocation (); if (CLLocationManager.HeadingAvailable) locMan.StartUpdatingHeading (); } btnCheckIn.BackgroundColor = new UIColor(new CoreGraphics.CGColor(0.9f,0.9f,0.9f)); btnCheckIn.Layer.CornerRadius = 1; btnCheckIn.TouchUpInside += (object sender, EventArgs e) => { if (currentLocation != null) { if (groupID <= 2) { string absResult = "You Are Not Within A Specified Zone."; string absTitle = "Error"; if (btnCheckIn.Title (UIControlState.Normal) == "Check In") { foreach (FacilityCoordinates fc in myFacilities) { var fenceLat = fc.Latitude; var fenceLon = fc.Longitude; var R = 6371; // Radius of the earth in km var dLat = deg2rad (currentLocation.Coordinate.Latitude - fenceLat); // deg2rad below var dLon = deg2rad (currentLocation.Coordinate.Longitude - fenceLon); var a = Math.Sin (dLat / 2) * Math.Sin (dLat / 2) + Math.Cos (deg2rad (fenceLat)) * Math.Cos (deg2rad (currentLocation.Coordinate.Latitude)) * Math.Sin (dLon / 2) * Math.Sin (dLon / 2); var c = 2 * Math.Atan2 (Math.Sqrt (a), Math.Sqrt (1 - a)); var d = R * c; if (d <= 0.25) { string result = locSvc.CheckIn (sessionKey, fc.LocationID); if (result == "Success") { absTitle = "Success"; absResult = "Check In Successful"; btnCheckIn.SetTitle ("CHECK OUT", UIControlState.Normal); break; } else { absTitle = "Error"; absResult = "An Unexpected Error Occurred. Try Again"; } } } } else if (btnCheckIn.Title (UIControlState.Normal) == "Check Out") { string result = locSvc.CheckOutWithoutLocation (sessionKey); if (result == "Success") { absTitle = "Success"; absResult = "Check Out Successful"; btnCheckIn.SetTitle ("CHECK IN", UIControlState.Normal); } else { absTitle = "Error"; absResult = "An Unexpected Error Occurred. Try Again"; } } UIAlertView _error = new UIAlertView (absTitle, absResult, null, "Ok", null); _error.Show (); } else if (groupID > 2 && groupID <= 7) { string absResult = ""; string absTitle = ""; if (btnCheckIn.Title (UIControlState.Normal) == "Check In") { string result = locSvc.CheckInWithLocation (sessionKey, -1, currentLocation.Coordinate.Latitude, currentLocation.Coordinate.Longitude); if (result == "Success") { absTitle = "Success"; absResult = "Check In Successful"; btnCheckIn.SetTitle ("CHECK OUT", UIControlState.Normal); } else { absTitle = "Error"; absResult = "An Unexpected Error Occurred. Try Again"; } } else if (btnCheckIn.Title (UIControlState.Normal) == "Check Out") { string result = locSvc.CheckOutWithoutLocation (sessionKey); if (result == "Success") { absTitle = "Success"; absResult = "Check In Successful"; btnCheckIn.SetTitle ("CHECK IN", UIControlState.Normal); } else { absTitle = "Error"; absResult = "An Unexpected Error Occurred. Try Again"; } } UIAlertView _error = new UIAlertView (absTitle, absResult, null, "Ok", null); _error.Show (); } else if (groupID == 8) { var fenceLat = 48.46003187; var fenceLon = -89.18908003; var R = 6371; // Radius of the earth in km var dLat = deg2rad (currentLocation.Coordinate.Latitude - fenceLat); // deg2rad below var dLon = deg2rad (currentLocation.Coordinate.Longitude - fenceLon); var a = Math.Sin (dLat / 2) * Math.Sin (dLat / 2) + Math.Cos (deg2rad (fenceLat)) * Math.Cos (deg2rad (currentLocation.Coordinate.Latitude)) * Math.Sin (dLon / 2) * Math.Sin (dLon / 2); var c = 2 * Math.Atan2 (Math.Sqrt (a), Math.Sqrt (1 - a)); var d = R * c; string absResult = d.ToString (); UIAlertView _error = new UIAlertView ("Check In", absResult, null, "Ok", null); _error.Show (); } } }; } else { btnCheckIn.Hidden = true; lblText.Text = "You have no locations to check in to. Please start the application during a rotation to properly utilize the functionality. Thank you."; } btnExit.BackgroundColor = new UIColor(new CoreGraphics.CGColor(0.9f,0.9f,0.9f)); btnExit.Layer.CornerRadius = 1; btnExit.TouchUpInside += (object sender, EventArgs e) => { Environment.Exit(0); }; }
public override void ViewWillAppear(bool animated) { base.ViewWillAppear (animated); //Ocultamos el campo de observaciones, ya que por lo visto no se almacena en ningun lado, esperamos respuesta this.cmpObservaciones.Hidden = true; this.lblObservaciones.Hidden = true; //Ocultamos los labels donde se muestran las coordenadas del dispositivo this.lblLatitud.Hidden = true; this.lblLongitud.Hidden = true; //Declarar el Location Manager iPhoneLocationManager = new CLLocationManager (); iPhoneLocationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters; //Obtener la posicion del dispositivo //El metodo es diferente en iOS 6 se verifica la version del S.O. if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) { iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => { UpdateLocation (e.Locations [e.Locations.Length - 1]); }; }else{ iPhoneLocationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => { UpdateLocation (e.NewLocation); }; } iPhoneLocationManager.UpdatedHeading += (object sender, CLHeadingUpdatedEventArgs e) => { }; //Actualizar la ubicacion if (CLLocationManager.LocationServicesEnabled) iPhoneLocationManager.StartUpdatingLocation (); if (CLLocationManager.HeadingAvailable) iPhoneLocationManager.StartUpdatingHeading (); //Se esconde el booton para ir a la vista anterior this.NavigationItem.HidesBackButton = true; //se crea el boton para regresar a la vista anterior, verificando que la tarea haya sido dada de alta UIBarButtonItem regresar = new UIBarButtonItem(); regresar.Style = UIBarButtonItemStyle.Plain; regresar.Target = this; regresar.Title = "Lista de tareas"; regresar.Clicked += (sender, e) => { if(this.listo == false){ UIAlertView alert = new UIAlertView(){ Title = "¿Salir?" , Message = "Si sales se perderá el registro de la tarea" }; alert.AddButton("Aceptar"); alert.AddButton("Cancelar"); alert.Clicked += (s, o) => { if(o.ButtonIndex==0){ NavigationController.PopViewControllerAnimated(true); } }; alert.Show(); }else{ NavigationController.PopViewControllerAnimated(true); } }; //posionamiento del boton this.NavigationItem.LeftBarButtonItem = regresar; //Se establece un borde para el textarea de la descripcion this.cmpDescripcion.Layer.BorderWidth = 1.0f; this.cmpDescripcion.Layer.BorderColor = UIColor.Gray.CGColor; this.cmpDescripcion.Layer.ShadowColor = UIColor.Black.CGColor; this.cmpDescripcion.Layer.CornerRadius = 8; //Declaramos el datamodel para los responsables pickerDataModelResponsibles = new PickerDataModelResponsibles (); //Declaramos el datamodel para las categorias pickerDataModelCategories = new PickerDataModelCategories (); //Declaramos el datamodel para el picker de prioridades pickerDataModel = new PickerDataModel (); //Declaramos el datamodel para el picker de buisqueda de personas pickerDataModelPeople = new PickerDataModelPeople (); //Declaramos el actionsheet donde se mostrara el picker actionSheetPicker = new ActionSheetPicker(this.View); this.btnResponsable.TouchUpInside += (sender, e) => { try{ responsibleService = new ResponsibleService(); pickerDataModelResponsibles.Items = responsibleService.All(); actionSheetPicker.Picker.Source = pickerDataModelResponsibles; actionSheetPicker.Show(); }catch(System.Net.WebException){ UIAlertView alert = new UIAlertView(){ Title = "ERROR", Message = "No se pueden cargar los datos, verifique su conexión a internet" }; alert.AddButton("Aceptar"); alert.Show(); } catch(System.Exception){ UIAlertView alert = new UIAlertView(){ Title = "Lo sentimos", Message = "Ocurrio un problema de ejecucion, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); } }; this.btnCategoria.TouchUpInside += (sender, e) => { try{ categoryService = new CategoryService(); pickerDataModelCategories.Items = categoryService.All();//llenamos el picker view con la respuesta del servicio de categorias actionSheetPicker.Picker.Source = pickerDataModelCategories; actionSheetPicker.Show(); }catch(System.Net.WebException){ UIAlertView alert = new UIAlertView(){ Title = "ERROR", Message = "No se pueden cargar los datos, verifique su conexión a internet" }; alert.AddButton("Aceptar"); alert.Show(); } catch(System.Exception){ UIAlertView alert = new UIAlertView(){ Title = "Lo sentimos", Message = "Ocurrio un problema de ejecucion, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); } }; this.btnPrioridad.TouchUpInside += (sender, e) => { try{ prioritiesService = new PrioritiesService(); pickerDataModel.Items = prioritiesService.All();//llenamos el pickerview con la lista de prioridades actionSheetPicker.Picker.Source = pickerDataModel; actionSheetPicker.Show(); } catch(System.Net.WebException){ UIAlertView alert = new UIAlertView(){ Title = "ERROR", Message = "No se pueden cargar los datos, verifique su conexión a internet" }; alert.AddButton("Aceptar"); alert.Show(); } catch(System.Exception){ UIAlertView alert = new UIAlertView(){ Title = "Lo sentimos", Message = "Ocurrio un problema de ejecucion, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); } }; this.btnFechaCont.TouchUpInside += (sender, e) => { actionSheetDatePicker.Show(); }; this.btnFechaCompr.TouchUpInside += (sender, e) => { actionSheetDatePicker1.Show(); }; //Establecemos las propiedades del primer datepicker actionSheetDatePicker = new ActionSheetDatePicker (this.View); actionSheetDatePicker.Picker.Mode = UIDatePickerMode.Date; actionSheetDatePicker.Picker.TimeZone = NSTimeZone.LocalTimeZone; //actionSheetDatePicker.Picker.MinimumDate = DateTime.Today.AddDays (-7); //actionSheetDatePicker.Picker.MaximumDate = DateTime.Today.AddDays (7); //Establecemos las propiedades del segundo datepicker actionSheetDatePicker1 = new ActionSheetDatePicker (this.View); actionSheetDatePicker1.Picker.Mode = UIDatePickerMode.Date; actionSheetDatePicker1.Picker.TimeZone = NSTimeZone.LocalTimeZone; //actionSheetDatePicker1.Picker.MinimumDate = DateTime.Today.AddDays (-7); //actionSheetDatePicker1.Picker.MaximumDate = DateTime.Today.AddDays (7); actionSheetDatePicker.Picker.ValueChanged += (s, e) => { DateTime fecha1 = (s as UIDatePicker).Date; //DateTime fecha3 = fecha1.AddDays(-1); String fecha2 = String.Format("{0:yyyy-MM-dd}",fecha1); this.lblFechaCont.Text = fecha2; }; actionSheetDatePicker1.Picker.ValueChanged += (s, e) => { DateTime fecha1 = (s as UIDatePicker).Date; //DateTime fecha3 = fecha1.AddDays(-1); String fecha2 = String.Format("{0:yyyy-MM-dd}",fecha1); this.lblFechaCompr.Text = fecha2; }; String categoria=""; pickerDataModelCategories.ValueChanged += (sender, e) => { categoria = pickerDataModelCategories.SelectedItem.idCategoria; this.lblCategoria.Text = pickerDataModelCategories.SelectedItem.ToString(); }; String prioridad = ""; pickerDataModel.ValueChanged += (sender, e) => { prioridad = pickerDataModel.SelectedItem.idPrioridad; this.lblPrioridad.Text = pickerDataModel.SelectedItem.ToString(); }; String responsable = ""; pickerDataModelResponsibles.ValueChanged += (sender, e) => { responsable = pickerDataModelResponsibles.SelectedItem.UserID; this.lblResponsable.Text = pickerDataModelResponsibles.SelectedItem.ToString(); }; String idPadron =""; pickerDataModelPeople.ValueChanged += (sender, e) => { idPadron = pickerDataModelPeople.SelectedItem.idPadron; this.cmpSolicitante.Text = pickerDataModelPeople.SelectedItem.ToString(); }; this.btnBuscar.TouchUpInside += (sender, e) => { try{ peopleService = new PeopleService(); peopleService.FindPeople(this.cmpNombre.Text, this.cmpPaterno.Text, this.cmpMaterno.Text); pickerDataModelPeople.Items = peopleService.All(); if(pickerDataModelPeople.Items.Count == 0){ UIAlertView alert = new UIAlertView(){ Title = "Persona no encontrada", Message = "No se encontraron resultados, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); }else { actionSheetPicker = new ActionSheetPicker(this.View); actionSheetPicker.Picker.Source = pickerDataModelPeople; actionSheetPicker.Show(); } } catch(System.Net.WebException){ UIAlertView alert = new UIAlertView(){ Title = "ERROR", Message = "No se pueden cargar los datos, verifique su conexión a internet" }; alert.AddButton("Aceptar"); alert.Show(); } catch(System.Exception){ UIAlertView alert = new UIAlertView(){ Title = "Lo sentimos", Message = "Ocurrio un problema de ejecucion, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); } }; this.cmpSolicitante.Enabled = false; //Se crea el boton para enviar la informacion al servidor this.btnGuardar.TouchUpInside += (sender, e) => { try{ newTaskService = new NewTaskService(); String respuesta = newTaskService.SetData(cmpTitulo.Text, cmpDescripcion.Text,categoria,responsable,prioridad,lblFechaCont.Text,lblFechaCompr.Text,idPadron,MainView.user ,cmpTelCasa.Text,cmpTelCel.Text,cmpCorreo.Text,lblLatitud.Text,lblLongitud.Text); if (respuesta.Equals("0")){ UIAlertView alert = new UIAlertView(){ Title = "ERROR", Message = "Error del Servidor, intentelo de nuevo" }; alert.AddButton("Aceptar"); alert.Show(); }else if(respuesta.Equals("1")){ UIAlertView alert = new UIAlertView(){ Title = "Correcto", Message = "La tarea ha sido guardada correctamente" }; alert.AddButton("Aceptar"); alert.Clicked += (s, o) => { if(o.ButtonIndex==0){ NavigationController.PopViewControllerAnimated(true); } }; alert.Show(); } }catch(System.Net.WebException ex){ Console.WriteLine(ex.ToString()); UIAlertView alert = new UIAlertView(){ Title = "ERROR", Message = "Error del Servidor, intentelo de nuevo, o verifique su conexión a internet" }; alert.AddButton("Aceptar"); alert.Show(); } }; //Se establece un borde para el textarea de las observaciones this.cmpObservaciones.Layer.BorderWidth = 1.0f; this.cmpObservaciones.Layer.BorderColor = UIColor.Gray.CGColor; this.cmpObservaciones.Layer.ShadowColor = UIColor.Black.CGColor; this.cmpObservaciones.Layer.CornerRadius = 8; }
public override void ViewDidLoad() { base.ViewDidLoad(); // For accelerometer readings motionManager = new CMMotionManager(); motionManager.AccelerometerUpdateInterval = 0.01; // 100Hz //To handle long presses and bring up path start/end menu var longPressManager = new UILongPressGestureRecognizer(); //Graph loading code //Graph loading code var assembly = Assembly.GetExecutingAssembly(); var asset = assembly.GetManifestResourceStream("Navigator.iOS.Resources.dcsfloorWideDoors.xml"); pf = new Pathfinding.Pathfinding(new Dictionary<int, Stream>() { {0,assembly.GetManifestResourceStream("Navigator.iOS.Resources.dcsfloorWideDoors.xml")}, {1,assembly.GetManifestResourceStream("Navigator.iOS.Resources.dcsFloor1.xml")} },assembly.GetManifestResourceStream("Navigator.iOS.Resources.Rooms.xml") ); pf.CurrentFloor = 0; while (true) { if (pf.Ready) break; Thread.Sleep(500); } //set up the search bar and prediction box var searchController = new CustomSearchController(this, SearchBar, SearchPredictionTable, pf.Rooms); floorPlanGraph = Graph.Load(asset); wallCollImg = UIImage.FromBundle("Images/dcsfloorWideDoors.png"); col = new Collision(floorPlanGraph, new StepDetector()); ((Collision)col).WallCol = new WallCollision ((x,y) => GetPixelColor(new PointF(x, y), wallCollImg)); wallColTest = new WallCollision ((x,y) => GetPixelColor(new PointF(x, y), wallCollImg)); pathView = new PathView (wallColTest); col.SetLocation(707.0f, 677.0f); col.PassHeading(90); col.PositionChanged += HandleStepsTaken; //Container for floorplan and any overlaid images var container = new UIView(); //Will contain floorplan images floorplanImageView = new UIImageView(); //Load floorplan images floorplanImageNoGrid = UIImage.FromBundle("Images/FinalDcsFloor1.png"); floorplanImageWithGrid = UIImage.FromBundle("Images/dcsFloorWideDoorsGrid.png"); //Initiate the location arrow locationArrow = new LocationArrowImageView(); locationArrow.ScaleFactor = floorplanView.ZoomScale; pathView.ScaleFactor = floorplanView.ZoomScale; setStartPoint(690.0f, 840.0f); //Set sizes for floorplan view and path view floorplanView.ContentSize = floorplanImageNoGrid.Size; pathView.Frame = new CGRect(new CGPoint(0, 0), floorplanImageNoGrid.Size); //Add subviews to the container (including pathview and floorplanview) container.AddSubview(floorplanImageView); container.AddSubview(locationArrow); floorplanImageView.AddSubview(pathView); changeFloorPlanImage(floorplanImageView, floorplanImageNoGrid); container.SizeToFit(); //Adjust scrolling and zooming properties for the floorplanView floorplanView.MaximumZoomScale = 1f; floorplanView.MinimumZoomScale = .25f; floorplanView.AddSubview(container); floorplanView.ViewForZoomingInScrollView += (UIScrollView sv) => { return floorplanImageView; }; //Variables needed to convert device acceleration to world z direction acceleration double accelX = 0, accelY = 0, accelZ = 0; //Scale location arrow and paths when zooming the floorplan floorplanView.DidZoom += (sender, e) => { locationArrow.ScaleFactor = floorplanView.ZoomScale; pathView.ScaleFactor = floorplanView.ZoomScale; }; //Pass acceleremoter values to the collision class motionManager.StartAccelerometerUpdates(NSOperationQueue.CurrentQueue, (data, error) => { accelX = data.Acceleration.X*9.8; accelY = data.Acceleration.Y*9.8; accelZ = Math.Sqrt(Math.Pow(accelX, 2) + Math.Pow(accelY, 2) + Math.Pow(data.Acceleration.Z*9.8, 2)); col.PassSensorReadings(CollisionSensorType.Accelometer, accelX, accelY, accelZ); //displayAccelVal((float)accelZ); }); /* motionManager.StartDeviceMotionUpdates(NSOperationQueue.CurrentQueue, (data, error) => { //data.Attitude.MultiplyByInverseOfAttitude(data.Attitude); var test = data.UserAcceleration.X; var accelRelZ = data.Attitude.RotationMatrix.m31 * accelX + data.Attitude.RotationMatrix.m32 * accelY + data.Attitude.RotationMatrix.m33 * accelZ; debugLabel.Text = "" + Math.Round(test, 2);//Math.Round(accelRelZ, 2); } ); */ //LongPressManager will cause the path input menu to appear after a stationary long press longPressManager.AllowableMovement = 0; longPressManager.AddTarget(() => handleLongPress(longPressManager, floorPlanGraph)); floorplanView.AddGestureRecognizer(longPressManager); //the location manager handles the phone heading locationManager = new CLLocationManager(); locationManager.DesiredAccuracy = CLLocation.AccuracyBest; locationManager.HeadingFilter = 1; locationManager.UpdatedHeading += HandleUpdatedHeading; locationManager.StartUpdatingHeading(); //Button currently used for testing purposes only //Another testing button simulationButton.TouchUpInside += delegate { col.StepTaken(false); }; returnButton.TouchUpInside += delegate{ returnToMenu(); }; }