Ejemplo n.º 1
0
        public async Task <XLocation> GetQuickLocation()
        {
            Setup();

            var loc = new XLocation();

            _cancelSource = new CancellationTokenSource();

            await _geolocator.GetPositionAsync(5000, _cancelSource.Token, false)
            .ContinueWith(t =>
            {
                if (t.IsFaulted)
                {
                    CurrentLocation.IsResolved = false;
                    CurrentLocation.IsEnabled  = false;
                    CurrentLocation.Status     = XPositionStatus.Disabled;
                    _fire();
                    return(loc);
                }
                if (t.IsCanceled)
                {
                    return(new XLocation());
                }
                loc.Latitude   = t.Result.Latitude;
                loc.Longitude  = t.Result.Longitude;
                loc.Accuracy   = t.Result.Accuracy;
                loc.Heading    = t.Result.Heading;
                loc.IsEnabled  = true;
                loc.IsResolved = true;
                loc.Status     = XPositionStatus.Ready;
                return(loc);
            }, _scheduler);

            return(loc);
        }
Ejemplo n.º 2
0
        public async void getLocate()
        {
            while (true)
            {
                if (_coordinates.Text.StartsWith("Cannot", StringComparison.Ordinal))
                {
                    _coordinates.Text   = "Calculating Location...";
                    _progressbar.Hidden = false;
                }

                locating = true;

                try
                {
                    var position = await locator.GetPositionAsync(29000);

                    string latitude  = Convert.ToDouble(position.Latitude).ToString("#.###");
                    string longitude = Convert.ToDouble(-position.Longitude).ToString("#.###");
                    string altitude  = (Convert.ToInt32((position.Altitude) * 3.28084)).ToString();

                    _coordinates.Text = latitude + "º N,  " + longitude + "º W" + Environment.NewLine + altitude + " ft Elevation";
                }
                catch
                {
                    _coordinates.Text = "Cannot Determine Location";
                }

                _progressbar.Hidden = true;
                locator.StopListening();
                locating = false;

                await Task.Delay(9000);
            }
        }
Ejemplo n.º 3
0
        public async Task GetPositionAsync(Func <string, Task> alertOnViewModel)
        {
            try
            {
                var hasPermission = await checkPermissionsAsync(alertOnViewModel);

                if (hasPermission)
                {
                    Position results = null;
                    if (Device.RuntimePlatform == Device.Android)
                    {
                        //On Android, Fused Location Service has better performance
                        results = await FusedGeolocator.GetPositionAsync(10000);
                    }
                    else
                    {
                        results = await Geolocator.GetPositionAsync(TimeSpan.FromSeconds(10));
                    }
                    if (results != null)
                    {
                        GlobalAttributes.CurrentPosition.Latitude  = results.Latitude;
                        GlobalAttributes.CurrentPosition.Longitude = results.Longitude;
                        GeoEvent.DefaultInstance.Publish(GlobalAttributes.CurrentPosition);
                    }
                }
            }
            catch (Exception ex)
            {
                DebugUtil.WriteLine("GeoService > " + ex.Message);
                await alertOnViewModel("Cannot acquire location information." +
                                       "\nPlease enable location service and try again.");
            }
        }
        public async Task <Location> GetCurrentLocation()
        {
            try
            {
                //NOTE: wait until here to create Gelocator, so that the iOS prompt appears on GPS request
                if (_geolocator == null)
                {
                    _geolocator = new Geolocator();
                }

                var location = await _geolocator.GetPositionAsync(Timeout);

                Console.WriteLine("GPS location: {0},{1}", location.Latitude, location.Longitude);

                return(new Location
                {
                    Latitude = location.Latitude,
                    Longitude = location.Longitude,
                });
            }
            catch (Exception exc)
            {
                Console.WriteLine("Error finding GPS location: " + exc);

                //If anything goes wrong, just return null as if it was not found
                return(null);
            }
        }
Ejemplo n.º 5
0
        public async Task GetPosition()
        {
            _cancelSource = new CancellationTokenSource();

            PositionStatus    = string.Empty;
            PositionLatitude  = string.Empty;
            PositionLongitude = string.Empty;
            IsBusy            = true;
            await
            Geolocator.GetPositionAsync(10000, _cancelSource.Token, true)
            .ContinueWith(t =>
            {
                IsBusy = false;
                if (t.IsFaulted)
                {
                    PositionStatus = ((GeolocationException)t.Exception.InnerException).Error.ToString();
                }
                else if (t.IsCanceled)
                {
                    PositionStatus = "Canceled";
                }
                else
                {
                    PositionStatus    = t.Result.Timestamp.ToString("G");
                    PositionLatitude  = "La: " + t.Result.Latitude.ToString("N4");
                    PositionLongitude = "Lo: " + t.Result.Longitude.ToString("N4");
                }
            }, _scheduler);
        }
Ejemplo n.º 6
0
        public async Task <bool> AbrirLocalizacao()
        {
            var context = MainApplication.CurrentContext as Activity;

            if (context == null)
            {
                return(false);
            }

            var locationPermission = Manifest.Permission.ReadContacts;

            if (context.CheckSelfPermission(locationPermission) == (int)Permission.Granted)
            {
                var locator = new Geolocator(context)
                {
                    DesiredAccuracy = 50
                };

                var position = await locator.GetPositionAsync(timeout : 10000);

                var geoString = $"geo:{position.Latitude},{position.Longitude}?q={position.Latitude},{position.Longitude}(Label+Name)";

                var geoUri = Android.Net.Uri.Parse(geoString);

                var mapIntent = new Intent(Intent.ActionView, geoUri);

                context.StartActivity(mapIntent);
                return(true);
            }

            return(false);
        }
Ejemplo n.º 7
0
        public async void NavigateUsingNativeMap(double destinationLat, double destinationLng, int zoomLevel = 1, DirectionsMode directionsMode = DirectionsMode.Driving)
        {
            if (CLLocationManager.Status == CLAuthorizationStatus.NotDetermined || CLLocationManager.Status == CLAuthorizationStatus.Denied)
            {
                return;
            }

            //get current location
            Geolocator locator = new Geolocator()
            {
                DesiredAccuracy = 100
            };
            var location = await locator.GetPositionAsync(50000);

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

            var sourceLat = location.Latitude;
            var sourceLng = location.Longitude;

            var urlString = string.Format("http://maps.apple.com/?saddr={0},{1}&daddr={2},{3}", sourceLat.ParseToCultureInfo(new CultureInfo("en-US")), sourceLng.ParseToCultureInfo(new CultureInfo("en-US")), destinationLat.ParseToCultureInfo(new CultureInfo("en-US")), destinationLng.ParseToCultureInfo(new CultureInfo("en-US")));

            UIApplication.SharedApplication.OpenUrl(new NSUrl(urlString));
        }
Ejemplo n.º 8
0
        async Task ExecuteTakePhotoCommandAsync()
        {
            try
            {
                await Media.Initialize();

                if (!Media.IsCameraAvailable || !Media.IsTakePhotoSupported)
                {
                    Acr.UserDialogs.UserDialogs.Instance.Alert(
                        "Please ensure that camera is enabled and permissions are allowed for MyDriving to take photos.",
                        "Camera Disabled", "OK");

                    return;
                }

                var locationTask = Geolocator.GetPositionAsync(2500);
                var photo        = await Media.TakePhotoAsync(new StoreCameraMediaOptions
                {
                    DefaultCamera = CameraDevice.Rear,
                    Directory     = "MyDriving",
                    Name          = "MyDriving_",
                    SaveToAlbum   = true,
                    PhotoSize     = PhotoSize.Small
                });

                if (photo == null)
                {
                    return;
                }

                if (CrossDeviceInfo.Current.Platform == Plugin.DeviceInfo.Abstractions.Platform.Android ||
                    CrossDeviceInfo.Current.Platform == Plugin.DeviceInfo.Abstractions.Platform.iOS)
                {
                    Acr.UserDialogs.UserDialogs.Instance.Toast(
                        new Acr.UserDialogs.ToastConfig(Acr.UserDialogs.ToastEvent.Success, "Photo taken!")
                    {
                        Duration        = TimeSpan.FromSeconds(3),
                        TextColor       = System.Drawing.Color.White,
                        BackgroundColor = System.Drawing.Color.FromArgb(96, 125, 139)
                    });
                }

                var local   = await locationTask;
                var photoDb = new Photo
                {
                    PhotoUrl  = photo.Path,
                    Latitude  = local.Latitude,
                    Longitude = local.Longitude,
                    TimeStamp = DateTime.UtcNow
                };

                photos.Add(photoDb);
                photo.Dispose();
            }
            catch (Exception ex)
            {
                Logger.Instance.Report(ex);
            }
        }
Ejemplo n.º 9
0
        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));
                    }
                });
            };
        }
Ejemplo n.º 10
0
        public async Task <Position> GetGeolocator(object context)
        {
            var locator = new Geolocator {
                DesiredAccuracy = 50
            };
            Position position = await locator.GetPositionAsync(timeout : 10000);

            return(position);
        }
Ejemplo n.º 11
0
        public void GetCoordenada()
        {
            var locator = new Geolocator {
                DesiredAccuracy = 50
            };

            locator.GetPositionAsync(timeout: 10000).ContinueWith(t => {
                SetCoordenada(t.Result.Latitude, t.Result.Longitude);
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Ejemplo n.º 12
0
        private async Task GetLocation()
        {
            var locator = new Geolocator(this)
            {
                DesiredAccuracy = 50
            };

            var location = await locator.GetPositionAsync(10000);

            MineAppServices.Current.CurrentPosition = location;
        }
        public TramstopsViewModel(ITramsService tramsService)
        {
            this.tramsService = tramsService;

            var locator = new Geolocator {
                DesiredAccuracy = 50
            };

            locator.GetPositionAsync(timeout: 10000).ContinueWith(t => {
                this.GetNearbyTramStops(t.Result.Latitude, t.Result.Longitude);
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Ejemplo n.º 14
0
        public override async Task InitializeAsync(object navigation_data)
        {
            LocationCoordinates initial_position = navigation_data as LocationCoordinates;

            if (initial_position != null)
            {
                InitialMapLocationCenter = initial_position;
            }
            else
            {
                InitialMapLocationCenter = await Geolocator.GetPositionAsync();
            }
        }
Ejemplo n.º 15
0
        public void GetCoordenada()
        {
            var context = Forms.Context as Activity;
            var locator = new Geolocator(context)
            {
                DesiredAccuracy = 50
            };

            locator.GetPositionAsync(timeout: 10000).ContinueWith(t => {
                SetCoordenada(t.Result.Latitude, t.Result.Longitude);
                System.Diagnostics.Debug.WriteLine(t.Result.Latitude);
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
        public void GetCoordenada()
        {
            //exemplo de intent
            var context = Forms.Context as Activity;
            var locator = new Geolocator(context)
            {
                DesiredAccuracy = 50
            };

            locator.GetPositionAsync(timeout: 10000).ContinueWith(t => {
                SetCoordenada(t.Result.Latitude, t.Result.Longitude);
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }
Ejemplo n.º 17
0
        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
                };
            }));
        }
Ejemplo n.º 18
0
        public async Task <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);
        }
Ejemplo n.º 19
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            string folder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var    conn   = new SQLiteConnection(System.IO.Path.Combine(folder, "Location.db"));

            conn.CreateTable <Location>();

            //fill collection with data from db
            var query = conn.Table <Location> ();

            foreach (var item in query)
            {
                MyLocations.Add("Latitude: " + item.Latitude);
                MyLocations.Add("Longitude: " + item.Longitude);
            }

            tvList.DataSource = new LocationDS(MyLocations);

            // Perform any additional setup after loading the view, typically from a nib.
            btnAdd.TouchUpInside += delegate {
                var locator = new Geolocator {
                    DesiredAccuracy = 50
                };


                locator.GetPositionAsync(timeout: 10000).ContinueWith(t => {
                    // insert to db
                    var CurrentLocation       = new Location();
                    CurrentLocation.Latitude  = t.Result.Latitude.ToString();
                    CurrentLocation.Longitude = t.Result.Longitude.ToString();
                    conn.Insert(CurrentLocation);

                    //update


                    MyLocations.Add("Latitude: " + t.Result.Latitude);
                    MyLocations.Add("Longitue: " + t.Result.Longitude);
                    tvList.ReloadData();
                }, TaskScheduler.FromCurrentSynchronizationContext());

                btnClear.TouchUpInside += delegate {
                    conn.Execute("delete frome Location");
                    MyLocations.Clear();
                    tvList.ReloadData();
                };
            };
        }
        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);
        }
Ejemplo n.º 21
0
        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();
        }
Ejemplo n.º 22
0
        public async Task <GeoCoords> GetGeoCoordinatesAsync()
        {
            //the difference with iOS is that Android requires Geolocator to be instantiated with the current Android Activity (=Forms.Contex)
            var locator = new Geolocator(Forms.Context)
            {
                DesiredAccuracy = 30
            };

            var position = await locator.GetPositionAsync(30000);

            return(new GeoCoords
            {
                Latitude = position.Latitude,
                Longitude = position.Longitude
            });
        }
Ejemplo n.º 23
0
        public static IObservable <Position> GetPosition(bool includeHeading = false)
        {
            if (Implementation != null)
            {
                return(Implementation.GetPosition(includeHeading));
            }

#if !WP7 && !WP8
            var ret = Observable.Create <Position>(subj => {
#if ANDROID
                var geo = new Geolocator(Android.App.Application.Context);
#else
                var geo = new Geolocator();
#endif
                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());
        }
Ejemplo n.º 24
0
        public async Task <Dictionary <string, double> > GetCurrentLocation()
        {
            try {
                var locator = new Geolocator(MainActivity.AppContext)
                {
                    DesiredAccuracy = 1000
                };
                var position = await locator.GetPositionAsync(timeout : 100000);

                var dictionary = new Dictionary <string, double> ();
                dictionary.Add("Latitude", position.Latitude);
                dictionary.Add("Longitude", position.Longitude);
                return(dictionary);
            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
                return(new Dictionary <string, double> ());
            }
        }
Ejemplo n.º 25
0
        private async Task SetMapCenterToUserLocation()
        {
            var geoLocator = new Geolocator();

            try {
                BTProgressHUD.Show(maskType: ProgressHUD.MaskType.Black);                 //shows the spinner
                var position = await geoLocator.GetPositionAsync(10000);

                BTProgressHUD.Dismiss();                 //dismiss the spinner

                SetMapCenter(position.Latitude, position.Longitude, UserLocationZoom);
            }
            catch (GeolocationException)
            {
                // Do something useful here
                SetMapCenter(Location.DefaultPosition.Latitude, Location.DefaultPosition.Longitude, DefaultZoom);
            }
        }
        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);
        }
        // gets the location of the device
        public async void getLatLong()
        {
            var locator = new Geolocator(this.BaseContext)
            {
                DesiredAccuracy = 50
            };

            try
            {
                await locator.GetPositionAsync(timeout : 60000).ContinueWith(t => {
                    position.Latitude  = t.Result.Latitude;
                    position.Longitude = t.Result.Longitude;
                    Log.Debug("Test", "latitude: " + position.Latitude);
                    Log.Debug("Test", "logitude: " + position.Longitude);
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
            catch (System.Threading.Tasks.TaskCanceledException g)
            {
                Log.Debug("ProtectionService", "Coordinates not available!!" + g.Message);
            }
        }
Ejemplo n.º 28
0
 public static void GetLocation()
 {
     try
     {
         var locator = new Geolocator {
             DesiredAccuracy = 50
         };
         //            new Geolocator (this) { ... }; on Andro
         locator.GetPositionAsync(timeout: 10000).ContinueWith(t =>
         {
             StaticDataModel.Lattitude = t.Result.Latitude;
             StaticDataModel.Longitude = t.Result.Longitude;
             Console.WriteLine("Position Status: {0}", t.Result.Timestamp);
             Console.WriteLine("Position Latitude: {0}", t.Result.Latitude);
             Console.WriteLine("Position Longitude: {0}", t.Result.Longitude);
         }, TaskScheduler.FromCurrentSynchronizationContext());
     }
     catch (Exception ex)
     {
     }
 }
        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));
                });
            };
        }
        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);
        }