/// <summary> /// Returns an IObservable that continuously updates as the user's /// physical location changes. It is super important to make sure to /// dispose all subscriptions to this IObservable. /// </summary> /// <param name="minUpdateTime">Minimum update time.</param> /// <param name="minUpdateDist">Minimum update dist.</param> /// <param name="includeHeading">If set to <c>true</c> include heading.</param> public static IObservable<Position> Listen(int minUpdateTime, double minUpdateDist, bool includeHeading = false) { if (Implementation != null) { return Implementation.Listen(minUpdateTime, minUpdateDist, includeHeading); } var ret = Observable.Create<Position>(subj => { #if ANDROID var geo = new Geolocator(AndroidApp.Context); #else var geo = new Geolocator(); #endif var disp = new CompositeDisposable(); bool isDead = false; if (!geo.IsGeolocationAvailable || !geo.IsGeolocationEnabled) { return Observable.Throw<Position>(new Exception("Geolocation isn't available")).Subscribe(subj); } // NB: This isn't very Functional, but I'm lazy. disp.Add(Observable.FromEventPattern<PositionEventArgs>(x => geo.PositionChanged += x, x => geo.PositionChanged -= x).Subscribe(x => { if (isDead) return; subj.OnNext(x.EventArgs.Position); })); disp.Add(Observable.FromEventPattern<PositionErrorEventArgs>(x => geo.PositionError += x, x => geo.PositionError -= x).Subscribe(ex => { isDead = true; var toDisp = Interlocked.Exchange(ref disp, null); if (toDisp != null) toDisp.Dispose(); subj.OnError(new GeolocationException(ex.EventArgs.Error)); })); return disp; }); return ret.Multicast(new Subject<Position>()).RefCount(); }
public override void ViewDidLoad() { base.ViewDidLoad (); buttonLocation.TouchUpInside += (sender, e) => { var locator = new Geolocator { DesiredAccuracy = 50 }; locator.GetPositionAsync (timeout: 10000).ContinueWith (t => { var text = String.Format("Lat: {0}, Long: {0}", t.Result.Latitude, t.Result.Longitude); InvokeOnMainThread(() => LabelLocation.Text = text); }); }; buttonPicture.TouchUpInside += (sender, e) => { var camera = new MediaPicker (); if (!camera.IsCameraAvailable) { Console.WriteLine("Camera unavailable!"); return; } var opts = new StoreCameraMediaOptions { Name = "test.jpg", Directory = "MiniHackDemo" }; camera.TakePhotoAsync (opts).ContinueWith (t => { if (t.IsCanceled) return; InvokeOnMainThread(() => imagePhoto.Image = UIImage.FromFile(t.Result.Path)); }); }; }
private async Task GetLocation() { var locator = new Geolocator(this) { DesiredAccuracy = 50 }; var location = await locator.GetPositionAsync(10000); MineAppServices.Current.CurrentPosition = location; }
public GeoLocator() { #if __ANDROID__ this.locator = new Geolocator(Android.App.Application.Context); #else this.locator = new Geolocator(); #endif this.locator.PositionChanged += this.OnPositionChanged; this.locator.PositionError += this.OnPositionError; }
public LocationService() { #if __ANDROID__ this.locator = new Geolocator(Xamarin.Forms.Forms.Context); #else this.locator = new Geolocator(); #endif this.locator.PositionChanged += this.OnPositionChanged; this.locator.PositionError += this.OnPositionError; }
private void Setup() { if (this.geolocator != null) return; this.geolocator = new Geolocator { DesiredAccuracy = 50 }; this.geolocator.PositionError += OnListeningError; this.geolocator.PositionChanged += OnPositionChanged; }
public async Task<TripLog.Models.GeoCoords> GetGeoCoordinatesAsync () { var locator = new Geolocator{ DesiredAccuracy = 30 }; var position = await locator.GetPositionAsync (30000); var result = new GeoCoords{ Latitude = position.Latitude, Longitude = position.Longitude }; return result; }
public System.Threading.Tasks.Task<GeoTwitter.Tools.TwitterPosition> GetCurrentPosition() { return Task.Run( async () => { var geo = new Geolocator(Android.App.Application.Context); var result = await geo.GetPositionAsync(1000); return new TwitterPosition { Latitude = result.Latitude, Longitude = result.Longitude }; }); }
public GeolocatorApplicationObject() { #if MONOANDROID var androidGlobal = this.GetService<Cirrious.MvvmCross.Droid.Interfaces.IMvxAndroidGlobals>(); geo = new Geolocator(androidGlobal.ApplicationContext); #else geo = new Geolocator(); #endif geo.DesiredAccuracy = 250; geo.PositionChanged += geo_PositionChanged; geo.PositionError += geo_PositionError; }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button>(Resource.Id.buttonLocation); LabelLocation = FindViewById<TextView>(Resource.Id.locationLabel); image = FindViewById<ImageView>(Resource.Id.imagePhoto); button.Click += delegate { var locator = new Geolocator(this) { DesiredAccuracy = 50 }; locator.GetPositionAsync(timeout: 10000).ContinueWith(t => { var text = String.Format("Location : Lat: {0}, Long: {0}", t.Result.Latitude, t.Result.Longitude); this.RunOnUiThread(() => LabelLocation.Text = text); }); }; Button getimge = FindViewById<Button>(Resource.Id.buttonCamera); getimge.Click += delegate { var camera = new MediaPicker(this); if (!camera.IsCameraAvailable) { Console.WriteLine("Camera unavailable!"); return; } var opts = new StoreCameraMediaOptions { Name = "test.jpg", Directory = "MiniHackDemo" }; camera.TakePhotoAsync(opts).ContinueWith(t => { if (t.IsCanceled) return; using (var bmp = Android.Graphics.BitmapFactory.DecodeFile(t.Result.Path)) { this.RunOnUiThread(() => image.SetImageBitmap(bmp)); } }); }; }
public async Task<Coordinates> GetCoordinatesAsync() { var locator = new Geolocator() {DesiredAccuracy = 50}; var position = await locator.GetPositionAsync(30000); var coords = new Coordinates { Latitude = position.Latitude, Longitude = position.Longitude }; return coords; }
public async Task<Coordinates> GetCoordinatesAsync() { var locator = new Geolocator(Forms.Context) { DesiredAccuracy = 30 }; var position = await locator.GetPositionAsync(30000); var result = new Coordinates { Latitude = position.Latitude, Longitude = position.Longitude }; return result; }
public async Task<GPSCoordinates> GetCurrentCoordinates() { var locator = new Geolocator() { DesiredAccuracy = 50 }; var coordinates = new GPSCoordinates(); if (locator.IsGeolocationEnabled && locator.IsGeolocationEnabled) { var pos = await locator.GetPositionAsync(timeout: 10000); coordinates.Latitude = pos.Latitude; coordinates.Longitude = pos.Longitude; } return coordinates; }
public async Task<GeoCoords> GetLocationAsync() { var locator = new Geolocator(this._appContext) { DesiredAccuracy = 30 }; var position = await locator.GetPositionAsync(30000); var result = new GeoCoords { Latitude = position.Latitude, Longitude = position.Longitude }; return result; }
private async void LoadViewControllers() { Forms.Init(); window = new UIWindow(UIScreen.MainScreen.Bounds); var locator = new Geolocator() { DesiredAccuracy = 20 }; var location = await locator.GetPositionAsync(10000); window.RootViewController = App.GetMainPage().CreateViewController(); window.MakeKeyAndVisible(); }
async void GetPosition() { try { locator = new Geolocator{DesiredAccuracy =50}; if ( locator.IsListening != true ) locator.StartListening(minTime: 1000, minDistance: 0); position = await locator.GetPositionAsync (timeout: 20000); } catch ( Exception e) { } }
public static void CurrentClosestStation(IQueryable<Station> stations, IStationHolder holder, TaskScheduler scheduler, Geolocator geolocator) { geolocator.DesiredAccuracy = 50; var locator = geolocator; locator.GetPositionAsync (10000).ContinueWith (t => { if(t.Status == TaskStatus.RanToCompletion){ var currentStation = new Station{Latitude = t.Result.Latitude, Longitude = t.Result.Longitude}; holder.Station = currentStation.GetClosestStation(stations); }else{ var currentStation = Station.NotFoundStation(); holder.Station = currentStation; } }, scheduler); }
public MainPageViewModel (Geolocator geolocator, SynchronizationContext syncContext) { if (geolocator == null) throw new ArgumentNullException ("geolocator"); if (syncContext == null) throw new ArgumentNullException ("syncContext"); this.sync = syncContext; this.geolocator = geolocator; this.geolocator.DesiredAccuracy = 50; this.geolocator.PositionError += GeolocatorOnPositionError; this.geolocator.PositionChanged += GeolocatorOnPositionChanged; this.getPosition = new DelegatedCommand (GetPositionHandler, s => true); this.toggleListening = new DelegatedCommand (ToggleListeningHandler, s => true); }
protected override void OnResume () { base.OnResume (); // Get a handle on the map element _mapFragment = FragmentManager.FindFragmentById(Resource.Id.map) as MapFragment; _map = _mapFragment.Map; _map.UiSettings.MyLocationButtonEnabled = true; _map.MyLocationEnabled = true; _locator = new Geolocator(this) { DesiredAccuracy = 1000 }; _locator.PositionChanged += OnLocationChanged; _locator.StartListening(2000, 1); }
public async Task<LocationCoordinates> GetCurrentLocation() { EventHandler<PositionEventArgs> handler = null; var result = new LocationCoordinates(); TaskCompletionSource<LocationCoordinates> tcs = new TaskCompletionSource<LocationCoordinates>(); Geolocator locator = new Geolocator { DesiredAccuracy = 50 }; try { if (!locator.IsListening) { locator.StartListening(10, 100); } handler = (object sender, PositionEventArgs e) => { result.Status = e.Position.Timestamp; result.Latitude = e.Position.Latitude; result.Longitude = e.Position.Longitude; locator.PositionChanged -= handler; tcs.SetResult(result); }; locator.PositionChanged += handler; await locator.GetPositionAsync(timeout: 10000).ContinueWith( t => { }); } catch (System.Exception ex) { if (ex.InnerException.GetType().ToString() == "Xamarin.Geolocation.GeolocationException") { tcs.SetException(ex); } } return tcs.Task.Result; }
public async Task<CoffeeRadar.Core.Models.GeoCoords> GetGeoCoordinatesAsync () { try { var locator = new Geolocator() {DesiredAccuracy = 30}; var position = await locator.GetPositionAsync(30000); var result = new GeoCoords { Latitude = position.Latitude, Longitude = position.Longitude }; return result; } catch (Exception e) { } return null; }
public static IObservable<Position> GetPosition(bool includeHeading = false) { if (Implementation != null) { return Implementation.GetPosition(includeHeading); } #if !WP7 && !WP8 var ret = Observable.Create<Position>(subj => { var geo = new Geolocator(); var cts = new CancellationTokenSource(); var disp = new CompositeDisposable(); if (!geo.IsGeolocationAvailable || !geo.IsGeolocationEnabled) { return Observable.Throw<Position>(new Exception("Geolocation isn't available")).Subscribe(subj); } disp.Add(new CancellationDisposable(cts)); disp.Add(geo.GetPositionAsync(cts.Token, includeHeading).ToObservable().Subscribe(subj)); return disp; }).Multicast(new AsyncSubject<Position>()); #else // NB: Xamarin.Mobile.dll references CancellationTokenSource, but // the one we have comes from the BCL Async library - if we try to // pass in our type into the Xamarin library, it gets confused. var ret = Observable.Create<Position>(subj => { var geo = new Geolocator(); var disp = new CompositeDisposable(); if (!geo.IsGeolocationAvailable || !geo.IsGeolocationEnabled) { return Observable.Throw<Position>(new Exception("Geolocation isn't available")).Subscribe(subj); } disp.Add(geo.GetPositionAsync(Int32.MaxValue, includeHeading).ToObservable().Subscribe(subj)); return disp; }).Multicast(new AsyncSubject<Position>()); #endif return ret.RefCount(); }
internal SinglePositionListener(double accuracy, int timeout, CancellationToken cancelToken) { cancelToken.Register(HandleTimeout, true); this.desiredAccuracy = accuracy; this.start = DateTime.Now; this.timeout = timeout; System.Threading.Tasks.Task.Factory.StartNew(() => { this.watcher = new GeoCoordinateWatcher(Geolocator.GetAccuracy(accuracy)); this.watcher.PositionChanged += WatcherOnPositionChanged; this.watcher.StatusChanged += WatcherOnStatusChanged; this.watcher.Start(); }); if (timeout != Timeout.Infinite) { this.timer = new Timer(HandleTimeout, null, timeout, Timeout.Infinite); } Task.ContinueWith(Cleanup); }
public void Initialize(Geolocator locator) { _locator = locator; _locator.DesiredAccuracy = _desiredAccuracyMeters; _locator.PositionChanged += (o, e) => { SensusServiceHelper.Get().Logger.Log("GPS position has changed.", LoggingLevel.Verbose, GetType()); if (PositionChanged != null) PositionChanged(o, e); }; }
public override async void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); if (fileName == "") { fileName = "in-progress"; var picker = new MediaPicker (); // new MediaPicker (this); on Android if (!picker.IsCameraAvailable || !picker.PhotosSupported) Console.WriteLine ("No camera!"); else { var options = new StoreCameraMediaOptions { Name = DateTime.Now.ToString("yyyyMMddHHmmss"), Directory = "MediaPickerSample" }; #if !VISUALSTUDIO #region new style pickerController = picker.GetTakePhotoUI (options); PresentViewController (pickerController, true, null); var pickerTask = pickerController.GetResultAsync (); await pickerTask; // We need to dismiss the controller ourselves await DismissViewControllerAsync (true); // woot! async-ified iOS method // User canceled or something went wrong if (pickerTask.IsCanceled || pickerTask.IsFaulted) return; // We get back a MediaFile MediaFile media = pickerTask.Result; fileName = media.Path; PhotoImageView.Image = new UIImage (fileName); SavePicture(fileName); #endregion #else #region old style (deprecated) var t = picker.TakePhotoAsync (options); //.ContinueWith (t => { await t; if (t.IsCanceled) { Console.WriteLine ("User canceled"); fileName = "cancelled"; //InvokeOnMainThread(() =>{ NavigationController.PopToRootViewController(false); //}); return; } Console.WriteLine (t.Result.Path); fileName = t.Result.Path; //InvokeOnMainThread(() =>{ PhotoImageView.Image = new UIImage (fileName); //}); SavePicture(fileName); //}); #endregion #endif } } else if (fileName == "cancelled") { NavigationController.PopToRootViewController (true); } else { // populate screen with existing item PhotoImageView.Image = new UIImage (fileName); LocationText.Text = location; } var locator = new Geolocator { DesiredAccuracy = 50 }; // new Geolocator (this) { ... }; on Android var position = await locator.GetPositionAsync (timeout: 10000); //.ContinueWith (p => { Console.WriteLine ("Position Latitude: {0}", position.Latitude); Console.WriteLine ("Position Longitude: {0}", position.Longitude); location = string.Format("{0},{1}", position.Latitude, position.Longitude); LocationText.Text = location; }
///Returns double array of user location, {latitude,longitude}; returns {0,0} if location not found public async Task<double[]> GetLocation() { double[] location={0,0}; System.Diagnostics.Debug.WriteLine("mydebug--started getting position"); var locator = new Geolocator(MainActivity.Instance) { DesiredAccuracy = 50 }; await locator.GetPositionAsync(timeout: 10000).ContinueWith(t => { System.Diagnostics.Debug.WriteLine("mydebug--Position Status: {0}", t.Result.Timestamp); System.Diagnostics.Debug.WriteLine("mydebug--Position Latitude: {0}", t.Result.Latitude); System.Diagnostics.Debug.WriteLine("mydebug--Position Longitude: {0}", t.Result.Longitude); //save the location for return location[0] = t.Result.Latitude; location[1] = t.Result.Longitude; }, TaskScheduler.FromCurrentSynchronizationContext()); return location; }
public GPSCoordinates_iOS() { _locator = new Geolocator (); }
public override async void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); if (fileName == "") { fileName = "in-progress"; var picker = new MediaPicker (); // new MediaPicker (this); on Android if (!picker.IsCameraAvailable || !picker.PhotosSupported) Console.WriteLine ("No camera!"); else { var options = new StoreCameraMediaOptions { Name = DateTime.Now.ToString("yyyyMMddHHmmss"), Directory = "MediaPickerSample" }; pickerController = picker.GetTakePhotoUI (options); PresentViewController (pickerController, true, null); MediaFile media; try { var pickerTask = pickerController.GetResultAsync (); await pickerTask; // User canceled or something went wrong if (pickerTask.IsCanceled || pickerTask.IsFaulted) { fileName = ""; return; } media = pickerTask.Result; fileName = media.Path; // We need to dismiss the controller ourselves await DismissViewControllerAsync (true); // woot! async-ified iOS method } catch(AggregateException ae) { fileName = ""; Console.WriteLine("Error while huh", ae.Message); } catch(Exception e) { fileName = ""; Console.WriteLine("Error while cancelling", e.Message); } if (String.IsNullOrEmpty (fileName)) { await DismissViewControllerAsync (true); } else { PhotoImageView.Image = new UIImage (fileName); SavePicture(fileName); } } } else if (fileName == "cancelled") { NavigationController.PopToRootViewController (true); } else { // populate screen with existing item PhotoImageView.Image = FileExists(fileName) ? new UIImage (fileName) : null; LocationText.Text = location; } var locator = new Geolocator { DesiredAccuracy = 50 }; var position = await locator.GetPositionAsync ( new CancellationToken(), false); Console.WriteLine ("Position Latitude: {0}", position.Latitude); Console.WriteLine ("Position Longitude: {0}", position.Longitude); location = string.Format("{0},{1}", position.Latitude, position.Longitude); LocationText.Text = location; }
public GPSCoordinates_Droid () { _locator = new Geolocator (AndroidApp.GetAppContext ()); }
public override void ViewDidLoad() { base.ViewDidLoad(); var documentDirectories = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true); string documentDirectory = documentDirectories[0]; string path = Path.Combine(documentDirectory, "annotations.archive"); Console.WriteLine("Path: {0}", path); var annotations = (NSMutableArray)NSKeyedUnarchiver.UnarchiveFile(path); if (annotations != null) { for (int i = 0; i < annotations.Count; i++) { mapView.AddAnnotation(annotations.GetItem<BNRMapPoint>(i)); } } // Perform any additional setup after loading the view, typically from a nib. // locator = new Geolocator{ DesiredAccuracy = 50 }; // // locator.StartListening(5000, 1, false); // locator.PositionChanged += (object sender, PositionEventArgs e) => { // Console.WriteLine ("Position Status: {0}", e.Position.Accuracy); // Console.WriteLine ("Position Latitude: {0}", e.Position.Latitude); // Console.WriteLine ("Position Longitude: {0}", e.Position.Longitude); // }; // locator.PositionError += (object sender, PositionErrorEventArgs e) => { // Console.WriteLine("Could not find position: {0}, {1}", e.Error, e.ToString() ); // }; var clm = new CLLocationManager(); clm.RequestAlwaysAuthorization(); actIndicator.StartAnimating(); gettingLocLabel.Hidden = false; textField.Enabled = false; int mapTypeValue = NSUserDefaults.StandardUserDefaults.IntForKey(WhereamiMapTypePrefKey); segControl.SelectedSegment = mapTypeValue; mapView.MapType = (MKMapType)mapTypeValue; mapView.ShowsUserLocation = true; mapView.ZoomEnabled = true; CLLocationCoordinate2D lastLoc = new CLLocationCoordinate2D(NSUserDefaults.StandardUserDefaults.DoubleForKey(WhereamiLastLocLatPrefKey),NSUserDefaults.StandardUserDefaults.DoubleForKey(WhereamiLastLocLongPrefKey)); MKCoordinateRegion lastRegion = new MKCoordinateRegion(lastLoc, new MKCoordinateSpan(0.0025, 0.0025)); mapView.SetRegion(lastRegion, true); //currLocation = new CLLocationCoordinate2D(20.7592, -156.4572); // C# style event handler - can access class instance variables mapView.DidUpdateUserLocation += (object sender, MKUserLocationEventArgs e) => { actIndicator.StopAnimating(); gettingLocLabel.Hidden = true; textField.Enabled = true; Console.WriteLine(".NET Lat: {0}, Long: {1}, Alt: {2}", e.UserLocation.Coordinate.Latitude, e.UserLocation.Coordinate.Longitude, e.UserLocation.Location.Altitude); currLocation = e.UserLocation.Coordinate; if (firstLaunch) { mapView.SetRegion(MKCoordinateRegion.FromDistance(currLocation, 250, 250), true); firstLaunch = false; } else mapView.SetCenterCoordinate(currLocation, true); }; mapView.DidFailToLocateUser += (object sender, NSErrorEventArgs e) => { Console.WriteLine("Could not find location: {0}", e.ToString()); actIndicator.StartAnimating(); gettingLocLabel.Hidden = false; textField.Enabled = false; }; mapView.DidSelectAnnotationView += (object sender, MKAnnotationViewEventArgs e) => { var annotation = e.View.Annotation as BNRMapPoint; if (annotation != null) { Console.WriteLine(".NET DidSelectAnnotationView: {0}", annotation.Title); } }; // Strong Delegate method. Create delegate class as nested class of ViewCOntroller // Override need methods in that nested delegate class // mapDelegate = new WhereAmIMapDelegate(); // mapView.Delegate = mapDelegate; // Weak delegate method. use Export attribute with selector to override then implement method. // Whichever is assigned last wins and kills the other. // mapView.WeakDelegate = this; // textField.Delegate = new TextFieldDelegate(); textField.EditingDidEndOnExit += (object sender, EventArgs e) => { actIndicator.Hidden = false; if (!firstLaunch) { BNRMapPoint mp = new BNRMapPoint(textField.Text, currLocation); NSUserDefaults.StandardUserDefaults.SetDouble(currLocation.Latitude, WhereamiLastLocLatPrefKey); NSUserDefaults.StandardUserDefaults.SetDouble(currLocation.Longitude, WhereamiLastLocLongPrefKey); mapView.AddAnnotation(mp); textField.ResignFirstResponder(); textField.Text = ""; actIndicator.Hidden = true; } else { var locator = new Geolocator{ DesiredAccuracy = 50 }; locator.GetPositionAsync (timeout: 10000).ContinueWith (t => { CLLocationCoordinate2D coord = new CLLocationCoordinate2D(t.Result.Latitude, t.Result.Longitude); currLocation = coord; MKCoordinateRegion region = MKCoordinateRegion.FromDistance(currLocation, 250, 250); mapView.SetRegion(region, true); BNRMapPoint mp = new BNRMapPoint(textField.Text, currLocation); NSUserDefaults.StandardUserDefaults.SetDouble(currLocation.Latitude, WhereamiLastLocLatPrefKey); NSUserDefaults.StandardUserDefaults.SetDouble(currLocation.Longitude, WhereamiLastLocLongPrefKey); mapView.AddAnnotation(mp); textField.ResignFirstResponder(); textField.Text = ""; actIndicator.Hidden = true; }, TaskScheduler.FromCurrentSynchronizationContext()); } }; segControl.BackgroundColor = UIColor.White; segControl.ValueChanged += (object sender, EventArgs e) => { NSUserDefaults.StandardUserDefaults.SetInt(segControl.SelectedSegment, WhereamiMapTypePrefKey); switch (segControl.SelectedSegment) { case 0: mapView.MapType = MKMapType.Standard; break; case 1: mapView.MapType = MKMapType.Satellite; break; case 2: mapView.MapType = MKMapType.Hybrid; break; default: break; } }; }
private void UpdateLocation() { locationManager = new Geolocator (this); locationManager.PositionChanged += (sender, e) => { location = e.Position; locationManager.StopListening (); }; locationManager.StartListening (0, 0); }