public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); locationManager.RequestWhenInUseAuthorization(); locationManager.RequestLocation(); var region = TargetRegion; if (region != null) { AnnotateAndZoomToRegion(region); } }
/// <summary> /// 領域に侵入した際にステータスを更新します。 /// </summary> /// <param name="manager"></param> /// <param name="region"></param> public override void RegionEntered(CLLocationManager manager, CLRegion region) { var adapter = new DbAdapter_iOS(); if (region.Identifier.Equals(RegionList.研究室.Identifier)) { //研究室領域に侵入 UpdateStatus(Status.在室.GetStatusId()); adapter.AddDeviceLog("在室状況を「在室」に更新", $"領域[{RegionList.研究室.Name}]に侵入"); } else { //学内領域に侵入 var gregion = RegionList.CampusAllRegions .Where(r => r.Identifier.Equals(region.Identifier)) .First(); adapter.UpdateGeofenceStatus(UserDataModel.Instance.DeviceId, gregion.DbIdentifierName, true); adapter.AddDeviceLog("ジオフェンス状態を更新", $"領域[{gregion.Name}]に侵入"); if (manager.Location != null) { AddLocationLog(manager.Location, "LastUpdate", true); } else { manager.RequestLocation(); } } }
/// <summary> /// Starts an asynchronous operation to retrieve the current location of the device. /// </summary> /// <returns></returns> public async Task <Geoposition> GetGeopositionAsync() { #if WINDOWS_UWP || WINDOWS_APP || WINDOWS_PHONE_APP || WINDOWS_PHONE var g = await _locator.GetGeopositionAsync(); return(g == null ? null : g); #elif __UNIFIED__ #if __IOS__ || __TVOS__ _manager.RequestLocation(); #endif CLLocation current = _manager.Location; Geoposition pos = new Geoposition(current); return(pos); #elif TIZEN var loc = await _locator.GetLocationAsync(-1); return(new Geoposition(loc)); #elif WIN32 if (_watcher == null) { _watcher = new GeoCoordinateWatcher(DesiredAccuracy == PositionAccuracy.High ? GeoPositionAccuracy.High : GeoPositionAccuracy.Default); } var pos = _watcher.Position; return(new Geoposition(pos)); #else throw new PlatformNotSupportedException(); #endif }
/// <summary> /// 領域から出た際にステータスを更新します。 /// </summary> /// <param name="manager"></param> /// <param name="region"></param> public override void RegionLeft(CLLocationManager manager, CLRegion region) { Console.WriteLine("Exit [{0}] Region", region.Identifier); var adapter = new DbAdapter_iOS(); if (region.Identifier.Equals(RegionList.研究室.Identifier)) { //研究室領域から退出 UpdateStatus(Status.学内.GetStatusId()); adapter.AddDeviceLog("在室状況を「学内」に更新", $"領域[{RegionList.研究室.Name}]から退出"); } else { //学内領域から退出 var gregion = RegionList.CampusAllRegions .Where(r => r.Identifier.Equals(region.Identifier)) .First(); adapter.UpdateGeofenceStatus(UserDataModel.Instance.DeviceId, gregion.DbIdentifierName, false); adapter.AddDeviceLog($"領域[{gregion.Name}]から退出"); if (manager.Location != null) { AddLocationLog(manager.Location, "LastUpdate", false); } else { manager.RequestLocation(); } } }
/// <summary> /// Gets the location. /// </summary> /// <returns>The location.</returns> public Location GetLocation() { if (CheckPermission()) { if (LastLocation != null) { return(LastLocation); } else if (locationManager.Location != null) { if (locationManager.Location.HorizontalAccuracy <= ApplicationConst.MaxLocationAccuracy) { return(new Location() { Altitude = locationManager.Location.Altitude, Latitude = locationManager.Location.Coordinate.Latitude, Longitude = locationManager.Location.Coordinate.Longitude, Orientation = locationManager.Location.Course, Speed = locationManager.Location.Speed, Accuracy = locationManager.Location.HorizontalAccuracy, Utc = DateTime.UtcNow }); } } else { locationManager.RequestLocation(); } } return(null); }
static void Main() { NSApplication.Init(); var locationManager = new CLLocationManager(); locationManager.Delegate = new LocationDelegate(); locationManager.DesiredAccuracy = CLLocation.AccuracyBest; locationManager.RequestAlwaysAuthorization(); locationManager.RequestLocation(); NSRunLoop.Current.RunUntil(NSDate.DistantFuture); }
public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. LocationManager = new CLLocationManager(); LocationManager.DesiredAccuracy = 1000; LocationManager.RequestAlwaysAuthorization(); LocationManager.RequestWhenInUseAuthorization(); LocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => { if (e.Locations.Length > 0) { var location = e.Locations [0]; WriteLine($"LocationsUpdated :緯度:{ location.Coordinate.Latitude };經度:{location.Coordinate.Longitude}"); InvokeOnMainThread(() => { lbMessage.Text = $"緯度:{ location.Coordinate.Latitude.ToString("F4") };經度:{location.Coordinate.Longitude.ToString ("F4") }"; }); } }; if (CLLocationManager.LocationServicesEnabled) { // 單次要求 LocationManager.RequestLocation(); // 持續更新 LocationManager.StartUpdatingLocation(); } btnLocation.TouchUpInside += async(sender, e) => { LocationManager.StopUpdatingLocation(); var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 50; var position = await locator.GetPositionAsync(timeoutMilliseconds : 10000); InvokeOnMainThread(() => { lbMessage.Text = $"Position 緯度:{ position.Latitude.ToString ("F4") };經度:{position.Longitude.ToString ("F4") }"; }); Console.WriteLine("Position Status: {0}", position.Timestamp); Console.WriteLine("Position Latitude: {0}", position.Latitude); Console.WriteLine("Position Longitude: {0}", position.Longitude); }; }
public async Task <Location?> GetCurrentLocation() { if (!HasLocationPermissions()) { return(null); } _requestLocationTaskCompletionSource = new TaskCompletionSource <CLLocation>(); _locationManager.UpdatedLocation += _LocationManagerOnUpdatedLocation; _locationManager.RequestLocation(); var clLocation = await _requestLocationTaskCompletionSource.Task; return(new Location(clLocation.Coordinate.Longitude, clLocation.Coordinate.Latitude)); }
public static Task <CLLocation> GetCurrentLocationAsync() { var tcs = new TaskCompletionSource <CLLocation>(); EventHandler <CLLocationsUpdatedEventArgs> handler = null; EventHandler <NSErrorEventArgs> failedHandler = null; handler = (object sender, CLLocationsUpdatedEventArgs e) => { Debug.WriteLine("UpdatedLocations: " + e.Locations.FirstOrDefault()); _locationManager.LocationsUpdated -= handler; _locationManager.Failed -= failedHandler; LastKnownLocation = e.Locations.FirstOrDefault() ?? new CLLocation(); tcs.TrySetResult(LastKnownLocation); }; failedHandler = (object sender, NSErrorEventArgs e) => { //если доступ к локации запрещен, попадем сюда Debug.WriteLine("Failed to get location: " + e.Error); _locationManager.LocationsUpdated -= handler; _locationManager.Failed -= failedHandler; tcs.TrySetResult(new CLLocation()); }; UIApplication.SharedApplication.InvokeOnMainThread(() => { _locationManager.DistanceFilter = 0; _locationManager.DesiredAccuracy = CLLocation.AccuracyBest; _locationManager.LocationsUpdated += handler; _locationManager.Failed += failedHandler; _locationManager.RequestLocation(); }); if (_locationManager.Location != null) { tcs.TrySetResult(_locationManager.Location); } return(tcs.Task); }
public Task <CoordinateModel> GetCurrentPositionAsync() { tcs = new TaskCompletionSource <CoordinateModel>(); locationManager = new CLLocationManager(); locationManager.Delegate = this; locationManager.RequestWhenInUseAuthorization(); if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse) { locationManager.RequestLocation(); } else { tcs.TrySetResult(default(CoordinateModel)); } return(tcs.Task); }
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.RequestLocation(); }
public async Task <Gps> GetLocation() { if (locationManager.Location == null) { var source = new TaskCompletionSource <CLLocation>(); EventHandler <CLLocationsUpdatedEventArgs> handler = (sender, e) => { source.TrySetResult(locationManager.Location); }; locationManager.LocationsUpdated += handler; locationManager.RequestLocation(); await source.Task; locationManager.LocationsUpdated -= handler; } return(new Gps() { Latitude = locationManager.Location.Coordinate.Latitude, Longitude = locationManager.Location.Coordinate.Longitude, }); }
public static Task <CLLocation> GetCurrentLocationAsync() { var tcs = new TaskCompletionSource <CLLocation>(); EventHandler <CLLocationsUpdatedEventArgs> handler = null; EventHandler <NSErrorEventArgs> failedHandler = null; handler = (object sender, CLLocationsUpdatedEventArgs e) => { MvxTrace.Trace("UpdatedLocations: " + e.Locations.FirstOrDefault()); _locationManager.LocationsUpdated -= handler; _locationManager.Failed -= failedHandler; LastKnownLocation = e.Locations.FirstOrDefault() ?? new CLLocation(); tcs.TrySetResult(LastKnownLocation); }; failedHandler = (object sender, NSErrorEventArgs e) => { MvxTrace.Trace("Failed to get location: " + e.Error); _locationManager.LocationsUpdated -= handler; _locationManager.Failed -= failedHandler; tcs.TrySetResult(new CLLocation()); }; _locationManager.DesiredAccuracy = CLLocation.AccuracyHundredMeters; _locationManager.LocationsUpdated += handler; _locationManager.Failed += failedHandler; _locationManager.RequestLocation(); return(tcs.Task); }
public void AuthorizationChanged(CLLocationManager manager, CLAuthorizationStatus status) { manager.RequestLocation(); }
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)); }
private async void UploadJacketButton_TouchUpInside(object sender, EventArgs e) { if (string.IsNullOrEmpty(jacketOwnerTextField.Text) || string.IsNullOrEmpty(jacketIdTextField.Text) || string.IsNullOrEmpty(secretKeyTextField.Text)) { uploadStatusLabel.TextColor = UIColor.FromRGB(143, 0, 0).ColorWithAlpha((nfloat)0.5); uploadStatusLabel.Text = "All fields are required"; uploadStatusLabel.Hidden = false; return; } if (jacketIdTextField.Text.Length != 4) { uploadStatusLabel.TextColor = UIColor.FromRGB(143, 0, 0).ColorWithAlpha((nfloat)0.5); uploadStatusLabel.Text = "Jacket ID is 4 characters"; uploadStatusLabel.Hidden = false; return; } var charMatch = Regex.Matches(jacketIdTextField.Text, @"[a-zA-Z]").Count; if (charMatch != 4) { uploadStatusLabel.TextColor = UIColor.FromRGB(143, 0, 0).ColorWithAlpha((nfloat)0.5); uploadStatusLabel.Text = "Jacket ID is from letters A to Z"; uploadStatusLabel.Hidden = false; return; } locationManager = new CLLocationManager(); locationManager.RequestAlwaysAuthorization(); locationManager.RequestWhenInUseAuthorization(); if (CLLocationManager.LocationServicesEnabled) { if (CLLocationManager.Status == CLAuthorizationStatus.Denied || CLLocationManager.Status == CLAuthorizationStatus.NotDetermined || CLLocationManager.Status == CLAuthorizationStatus.Restricted) { var alert = UIAlertController.Create("Location Access Denied", "Please open settings and grant Console Jacket location permission", UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("No", UIAlertActionStyle.Cancel, (alertAction) => { DismissViewController(true, () => { LaunchViewController.ReloadDetails(); }); })); alert.AddAction(UIAlertAction.Create("Open Settings", UIAlertActionStyle.Default, async(alertAction) => { var settingsUrl = new NSUrl(UIApplication.OpenSettingsUrlString); if (UIApplication.SharedApplication.CanOpenUrl(settingsUrl)) { UIApplication.SharedApplication.OpenUrl(settingsUrl); } else { uploadStatusLabel.TextColor = UIColor.FromRGB(143, 0, 0).ColorWithAlpha((nfloat)0.5); uploadStatusLabel.Text = "Something went wrong"; } })); PresentViewController(alert, true, null); } else { locationManager.Delegate = this; locationManager.DesiredAccuracy = CLLocation.AccuracyBest; locationManager.RequestLocation(); } } else { var alert = UIAlertController.Create("Location Error", "Location services not enabled on your device. Would you like to use 'Earth' as your location", UIAlertControllerStyle.Alert); alert.AddAction(UIAlertAction.Create("No", UIAlertActionStyle.Cancel, (alertAction) => { DismissViewController(true, () => { LaunchViewController.ReloadDetails(); }); })); alert.AddAction(UIAlertAction.Create("Yes", UIAlertActionStyle.Default, async(alertAction) => { country = "Earth"; await PerformPost(); })); PresentViewController(alert, true, null); } }
public GeoLocation GetCurrentLocation() { _Manager.RequestLocation(); return((CurrentLocation != null) ? CurrentLocation : null); }
private void RequestLocation() { ShowLoading(); locationManager.RequestWhenInUseAuthorization(); locationManager.RequestLocation(); }