Ejemplo n.º 1
0
        private async Task <GeolocationAccessStatus> GetAccessStatus(CancellationToken timeoutToken)
        {
            GeolocationAccessStatus     accessStatus    = GeolocationAccessStatus.Unspecified;
            TaskCompletionSource <bool> resultRetrieved = new TaskCompletionSource <bool>();

            DispatcherHelper.CheckBeginInvokeOnUI(
                async() =>
            {
                try
                {
                    accessStatus = await Geolocator.RequestAccessAsync().AsTask(timeoutToken);
                }
                catch (OperationCanceledException ex)
                {
                    System.Diagnostics.Debug.WriteLine("Request access call timed out. Seems to be a CU only bug?");
                    accessStatus = GeolocationAccessStatus.Denied;
                }
                finally
                {
                    resultRetrieved.SetResult(true);
                }
            });

            await resultRetrieved.Task;

            return(accessStatus);
        }
Ejemplo n.º 2
0
        public async Task <bool> AskForPermissions(string[] permissionTab, Action <int> solicitMethod)
        {
            if (CheckPermissions(permissionTab) == true)
            {
                solicitMethod(2000);
                return(await Task.FromResult(true));
            }


            foreach (string permissionUWP in permissionTab)
            {
                switch (permissionUWP)
                {
                case "UWP.permission.LOCATION":

                    accessStatus = await Geolocator.RequestAccessAsync();

                    solicitMethod((int)accessStatus);
                    break;

                default:
                    throw new NotImplementedException();
                }
            }

            return(await Task.FromResult(false));
        }
Ejemplo n.º 3
0
        //private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        //{
        //    var b = (StackPanel) sender;
        //    var selected = (Sight) b.DataContext;
        //    MyMap.Center = selected.Position;

        //    Popup popup = new Popup();
        //    popup.DataContext = selected;
        //}

        private async void PageLoaded(Object sender, RoutedEventArgs e)
        {
            GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:
                _geolocator = new Geolocator {
                    DesiredAccuracy = PositionAccuracy.Default, MovementThreshold = 2
                };
                // geolocator = new Geolocator {ReportInterval = 1000};
                _geolocator.PositionChanged += Geolocator_PositionChanged;

                Geoposition pos = await _geolocator.GetGeopositionAsync();

                await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    Model.DrawPlayer(pos);
                });

                break;

            case GeolocationAccessStatus.Denied:
                break;

            case GeolocationAccessStatus.Unspecified:
                break;
            }
        }
        public async void ShowNoAccessDialog() {
            AccessStatus = await RequestAccess();
            if (AccessStatus == GeolocationAccessStatus.Allowed) {
                return;
            }

            TextBlock content = new TextBlock {
                Text = "ERROR_NO_LOCTION_ACCESS_DisplayMessage".t(R.File.CORTANA),
                TextAlignment = Windows.UI.Xaml.TextAlignment.Center,
                Margin = new Windows.UI.Xaml.Thickness { Bottom = 10, Left = 10, Top = 10, Right = 10},
                TextWrapping = Windows.UI.Xaml.TextWrapping.WrapWholeWords,
                HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center,
                VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center,
            };
            ContentDialog dialog = new ContentDialog() {
                Content = content
            };
            dialog.SecondaryButtonText = "DIALOG_NO_LOCATION_ACCESS_CANCEL".t();
            dialog.PrimaryButtonText = "DIALOG_NO_LOCATION_ACCESS_SETTINGS_BUTTON_TEXT".t();
            dialog.PrimaryButtonClick += (d, _) => {
                ShowLocationSettingsPage().Forget();
            };
            
            await dialog.ShowAsync();
        }
Ejemplo n.º 5
0
        private async void MyMap_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                AccessStatus = await Geolocator.RequestAccessAsync();

                if (AccessStatus == GeolocationAccessStatus.Allowed)//Get the user location
                {
                    Geolocator  geoLocator = new Geolocator();
                    Geoposition pos        = await geoLocator.GetGeopositionAsync();

                    Geopoint userLocation = pos.Coordinate.Point;
                    await myMap.TrySetViewAsync(userLocation, 16);//assign the map center to user's location
                }
                else
                {   //Default map center is Puyallup, Wa Municipal Court
                    var defaultCenter = new Geopoint(new BasicGeoposition()
                    {
                        Latitude  = 47.192298,
                        Longitude = -122.281621
                    });
                    await myMap.TrySetViewAsync(defaultCenter, 16);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message, "Maploaded");
            }
        }
        private async void SetGeotagFromGeolocatorButton_Click()
        {
            // Call RequestAccessAsync from the UI thread to get user permission on location usage.
            // Otherwise SetGeotagFromGeolocator will fail.
            GeolocationAccessStatus status = await Geolocator.RequestAccessAsync();

            if (status != GeolocationAccessStatus.Allowed)
            {
                rootPage.NotifyUser("Location access is not allowed", NotifyType.ErrorMessage);
                return;
            }

            Geolocator geolocator = new Geolocator();

            geolocator.DesiredAccuracy = PositionAccuracy.High;

            try
            {
                await GeotagHelper.SetGeotagFromGeolocatorAsync(file, geolocator);

                rootPage.NotifyUser("Geolocation set to current location", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                // File I/O errors are reported as exceptions.
                // AccessDeniedExcetion can be raised if the user revoked location access
                // after RequestAccessAsync completed.
                rootPage.NotifyUser("Exception: " + ex.Message, NotifyType.ErrorMessage);
            }
        }
Ejemplo n.º 7
0
        public async Task InitializeLocationServiceAsync()
        {
            _accessStatus = await Geolocator.RequestAccessAsync();

            await Task.Factory.StartNew(() =>
            {
                switch (_accessStatus)
                {
                    case GeolocationAccessStatus.Allowed:

                        _geolocator.StatusChanged += OnStatusChanged;
                        _geolocator.PositionChanged += OnGeolocatorPositionChanged;
                        break;

                    case GeolocationAccessStatus.Denied:
                        // TODO: Do something meaningfull here
                        break;

                    case GeolocationAccessStatus.Unspecified:
                        // TODO: Do something meaningfull here
                        break;
                }

            });
        }
        public async Task<Geoposition> HandeleAccessStatus(GeolocationAccessStatus accessStatus)
        {
            Geoposition geoposition = null;

            var message = "";

            switch (accessStatus)
            {
                case GeolocationAccessStatus.Allowed:
                    Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 1000 };
                    geoposition = await geolocator.GetGeopositionAsync();
                    break;

                case GeolocationAccessStatus.Denied:
                    message = "Access to location is denied!";
                    break;

                case GeolocationAccessStatus.Unspecified:
                    message = "Unspecified error!";
                    break;
            }

            if (message != "")
            {
                this.notificator.ShowErrorToastWithDismissButton(message);
            }

            return geoposition;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Initializes the location service with the specified accuracy and movement threshold.
        /// </summary>
        /// <param name="desiredAccuracyInMeters">The desired accuracy at which the service provides location updates.</param>
        /// <param name="movementThreshold">The distance of movement, in meters, that is required for the service to raise the PositionChanged event.</param>
        /// <returns>True if the initialization was successful and the service can be used.</returns>
        public async Task <bool> InitializeAsync(uint desiredAccuracyInMeters, double movementThreshold)
        {
            if (geolocator != null)
            {
                geolocator.PositionChanged -= GeolocatorOnPositionChanged;
                geolocator = null;
            }

            GeolocationAccessStatus accessStatus = GeolocationAccessStatus.Unspecified;
            bool result;

            try
            {
                // Dispatch back to the main thread
                accessStatus = await Geolocator.RequestAccessAsync();

                switch (accessStatus)
                {
                case GeolocationAccessStatus.Allowed:
                    geolocator = new Geolocator
                    {
                        DesiredAccuracyInMeters = desiredAccuracyInMeters,
                        MovementThreshold       = movementThreshold
                    };
                    result = true;
                    break;

                case GeolocationAccessStatus.Denied:
                    result = false;
                    break;

                case GeolocationAccessStatus.Unspecified:
                default:
                    await DispatcherHelper.RunAsync(async() =>
                    {
                        var dlg = new MessageDialog("Whoops! You haven't granted permission for " + Package.Current.DisplayName + " to access your location. Would you like to go to Settings and do that now?");
                        dlg.Commands.Add(new UICommand("Yes", async(command) =>
                        {
                            var uri = new Uri("ms-settings:privacy-location");
                            await Launcher.LaunchUriAsync(uri);
                        }));
                        dlg.Commands.Add(new UICommand("No"));
                        dlg.DefaultCommandIndex = 0;
                        dlg.CancelCommandIndex  = 1;
                        var dlgResult           = await dlg.ShowAsync();
                    });

                    result = false;
                    break;
                }
            }
            catch (UnauthorizedAccessException)
            {
                accessStatus = GeolocationAccessStatus.Denied;
                result       = false;
            }

            return(result);
        }
        // Apps need to call RequestAccessAsync to get user permission on location usage,
        // otherwise SetGeotagFromGeolocator will fail. Also RequestAccessAsync needs
        // to be called from a UI thread.
        private async Task RequestLocationAccessAsync()
        {
            GeolocationAccessStatus status = await Geolocator.RequestAccessAsync();

            if (status != GeolocationAccessStatus.Allowed)
            {
                LogError("Location access is NOT allowed");
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// request access if user has not yet given permission to use location
 /// </summary>
 private async void Initialize()
 {
     try
     {
         accessStatus = await Geolocator.RequestAccessAsync();
     } catch (Exception)
     {
         accessStatus = GeolocationAccessStatus.Denied;
     }
 }
Ejemplo n.º 12
0
        public async Task <bool> RequestUserAccesAsync()
        {
            GeolocationAccessStatus LocationEnabled = await Geolocator.RequestAccessAsync();

            if (LocationEnabled == GeolocationAccessStatus.Allowed)
            {
                return(true);
            }
            return(false);
        }
Ejemplo n.º 13
0
        public MainPage()
        {
            this.InitializeComponent();

            // Initialize ConnectTheDots Helper
            CTD = new ConnectTheDots();

            // Restore local settings
            if (localSettings.Values.ContainsKey("DisplayName"))
            {
                CTD.DisplayName        = (string)localSettings.Values["DisplayName"];
                this.TBDeviceName.Text = CTD.DisplayName;
            }
            if (localSettings.Values.ContainsKey("ConnectionString"))
            {
                CTD.ConnectionString         = (string)localSettings.Values["ConnectionString"];
                this.TBConnectionString.Text = CTD.ConnectionString;
            }

            // Check configuration settings
            ConnectToggle.IsEnabled = checkConfig();
            CTD.DisplayName         = this.TBDeviceName.Text;
            CTD.ConnectionString    = this.TBConnectionString.Text;
            CTD.Organization        = "My Company";
            CTD.Location            = "Unknown";

            // Get user consent for accessing location
            Task.Run(async() =>
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                              async() =>
                {
                    this.LocationAccess = await Geolocator.RequestAccessAsync();
                });
            });

            // Connect to MS Band
            connectToBand();

            // Start task that will send telemetry data to Azure
            // Hook up a callback to display message received from Azure
            CTD.ReceivedMessage += (object sender, EventArgs e) => {
                // Received a new message, display it
                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                        async() =>
                {
                    var dialogbox = new MessageDialog("Received message from Azure IoT Hub: \nName: " +
                                                      ((ConnectTheDots.ReceivedMessageEventArgs)e).Message.name +
                                                      "\nMessage: " +
                                                      ((ConnectTheDots.ReceivedMessageEventArgs)e).Message.message);
                    await dialogbox.ShowAsync();
                });
            };
        }
Ejemplo n.º 14
0
        public MainPage()
        {
            this.InitializeComponent();

            // Initialize ConnectTheDots Helper
            CTD = new ConnectTheDots();

            // Restore local settings
            if (localSettings.Values.ContainsKey("DisplayName"))
            {
                CTD.DisplayName = (string)localSettings.Values["DisplayName"];
                this.TBDeviceName.Text = CTD.DisplayName;
            }
            if (localSettings.Values.ContainsKey("ConnectionString"))
            {
                CTD.ConnectionString = (string)localSettings.Values["ConnectionString"];
                this.TBConnectionString.Text = CTD.ConnectionString;
            }

            // Check configuration settings
            ConnectToggle.IsEnabled = checkConfig();
            CTD.DisplayName = this.TBDeviceName.Text;
            CTD.ConnectionString = this.TBConnectionString.Text;
            CTD.Organization = "My Company";
            CTD.Location = "Unknown";

            // Get user consent for accessing location
            Task.Run(async () =>
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                async () =>
                {
                    this.LocationAccess = await Geolocator.RequestAccessAsync();
                });
            });

            // Add sensors to the ConnectTheDots object
            CTD.AddSensor("Temperature", "C");
            CTD.AddSensor("Humidity", "%");

            // Hook up a callback to display message received from Azure
            CTD.ReceivedMessage += (object sender, EventArgs e) => {
                // Received a new message, display it
                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                async () =>
                {
                    var dialogbox = new MessageDialog("Received message from Azure IoT Hub: \nName: " +
                                                      ((ConnectTheDots.ReceivedMessageEventArgs)e).Message.name +
                                                      "\nMessage: " +
                                                      ((ConnectTheDots.ReceivedMessageEventArgs)e).Message.message);
                    await dialogbox.ShowAsync();
                });
            };
        }
Ejemplo n.º 15
0
        private async Task InitializeAsync()
        {
            await BootstrapperService.Initialize(new IocWindowsModule());

            GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();

            //TODO: should store in settings
            var locationService = CC.IoC.Resolve <ILocationService>();

            locationService.HasGpsPermissions = accessStatus == GeolocationAccessStatus.Allowed;

            DismissExtendedSplash();
        }
        private async void autoLocate_Click(object sender, RoutedEventArgs e)
        {
            searchingWait.IsActive   = true;
            autoLocate.Background    = new SolidColorBrush(Color.FromArgb(255, 17, 191, 219));
            location.IsEnabled       = false;
            searchLocation.IsEnabled = false;

            GeolocationAccessStatus status = await App.searchParam.getGPSAccessStatus();

            switch (status)
            {
            case GeolocationAccessStatus.Allowed:

                MapLocationFinderResult result = await App.searchParam.getLocationData();

                if (result.Status == MapLocationFinderStatus.Success)
                {
                    if (!App.searchParam.getBasicSearchResults().Any())
                    {
                        errorSymbol.Text       = "\xE783";
                        errorMsg.Text          = "We did not find any listings.";
                        searchingWait.IsActive = false;
                    }
                    else
                    {
                        this.Frame.Navigate(typeof(intro));
                    }
                }
                else
                {
                    errorSymbol.Text = "\xE783";
                    errorMsg.Text    = "We couldn't find your location.";
                }
                break;

            case GeolocationAccessStatus.Denied:
                errorSymbol.Text = "\xE783";
                errorMsg.Text    = "Please enable location access";
                await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));

                break;

            case GeolocationAccessStatus.Unspecified:
                errorSymbol.Text = "\xE783";
                errorMsg.Text    = "An unknown error occured";
                break;
            }

            this.reset();
        }
Ejemplo n.º 17
0
        private async Task <GeolocationAccessStatus> RequestAccessAsync()
        {
            GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Denied:
                throw new UnauthorizedAccessException("Location Service is not available at this time. Location service for this device may be disabled or denied");

            case GeolocationAccessStatus.Unspecified:
                throw new ArgumentException("Location Service is not available at this time. Unspecified error");
            }
            return(accessStatus);
        }
Ejemplo n.º 18
0
        public MainPage()
        {
            this.InitializeComponent();

            // Initialize QRCode Scanner
            Scanner            = new MobileBarcodeScanner(Dispatcher);
            Scanner.Dispatcher = Dispatcher;

            // Initialize ConnectTheDots Helper
            CTD = new ConnectTheDots();

            // Hook up a callback to display message received from Azure
            CTD.ReceivedMessage += CTD_ReceivedMessage;

            // Restore local settings
            if (localSettings.Values.ContainsKey("ConnectionString"))
            {
                CTD.ConnectionString         = (string)localSettings.Values["ConnectionString"];
                this.TBConnectionString.Text = CTD.ConnectionString;
            }

            if (localSettings.Values.ContainsKey("DisplayName"))
            {
                CTD.DisplayName        = (string)localSettings.Values["DisplayName"];
                this.TBDeviceName.Text = CTD.DisplayName;
            }

            // Check configuration settings
            ConnectToggle.IsEnabled = checkConfig();
            CTD.ConnectionString    = this.TBConnectionString.Text;
            CTD.DisplayName         = this.TBDeviceName.Text;
            CTD.Organization        = "My Company";
            CTD.Location            = "Unknown";

            // Get user consent for accessing location
            Task.Run(async() =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                          async() =>
                {
                    this.LocationAccess = await Geolocator.RequestAccessAsync();
                    // Get device location
                    await updateLocation();
                });
            });

            // Add sensors to the ConnectTheDots object
            CTD.AddSensor("Temperature", "C");
            CTD.AddSensor("Humidity", "%");
        }
        public static LocationServiceRequestResult ToLocationServiceRequestResult(this GeolocationAccessStatus status)
        {
            switch (status)
            {
            case GeolocationAccessStatus.Allowed:
                return(LocationServiceRequestResult.Allowed);

            case GeolocationAccessStatus.Denied:
            case GeolocationAccessStatus.Unspecified:
                return(LocationServiceRequestResult.Denied);

            default:
                throw new ArgumentOutOfRangeException(nameof(status), status, null);
            }
        }
        // Apps need to call RequestAccessAsync to get user permission on location usage,
        // otherwise SetGeotagFromGeolocator will fail. Also RequestAccessAsync needs
        // to be called from a UI thread.
        private async Task RequestLocationAccessAsync()
        {
            try
            {
                GeolocationAccessStatus status = await Geolocator.RequestAccessAsync();

                if (status != GeolocationAccessStatus.Allowed)
                {
                    LogError("Location access is NOT allowed");
                }
            }
            catch (Exception e)
            {
                LogError("Exception: " + e.Message);
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            Window.Current.VisibilityChanged += OnVisibilityChanged;

            DateTime oneHourLater = DateTime.Now.AddHours(1);

            //rjc/$$
            StartDate.Date = oneHourLater.Date;
            StartTime.Time = oneHourLater.TimeOfDay;

            // Get permission to use location
            GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:
                // Wrap in try/catch in case user revokes access suddenly.
                try
                {
                    geofenceMonitor = GeofenceMonitor.Current;
                }
                catch (UnauthorizedAccessException)
                {
                    _rootPage.NotifyUser("Access denied.", NotifyType.ErrorMessage);
                }
                if (geofenceMonitor != null)
                {
                    foreach (Geofence geofence in geofenceMonitor.Geofences)
                    {
                        AddGeofenceToRegisteredGeofenceListBox(geofence);
                    }

                    // register for state change events
                    geofenceMonitor.GeofenceStateChanged += OnGeofenceStateChanged;
                    geofenceMonitor.StatusChanged        += OnGeofenceStatusChanged;
                }
                break;

            case GeolocationAccessStatus.Denied:
                _rootPage.NotifyUser("Access denied.", NotifyType.ErrorMessage);
                break;

            case GeolocationAccessStatus.Unspecified:
                _rootPage.NotifyUser("Unspecified error.", NotifyType.ErrorMessage);
                break;
            }
        }
Ejemplo n.º 22
0
        public MainPage()
        {
            this.InitializeComponent();

            // Initialize ConnectTheDots Helper
            CTD = new ConnectTheDots();

            // Restore local settings
            if (localSettings.Values.ContainsKey("DisplayName"))
            {
                CTD.DisplayName        = (string)localSettings.Values["DisplayName"];
                this.TBDeviceName.Text = CTD.DisplayName;
            }
            if (localSettings.Values.ContainsKey("ConnectionString"))
            {
                CTD.ConnectionString         = (string)localSettings.Values["ConnectionString"];
                this.TBConnectionString.Text = CTD.ConnectionString;
            }

            // Check configuration settings
            ConnectToggle.IsEnabled = checkConfig();
            CTD.DisplayName         = this.TBDeviceName.Text;
            CTD.ConnectionString    = this.TBConnectionString.Text;
            CTD.Organization        = "My Company";
            CTD.Location            = "Unknown";

            // Hook up a callback to display message received from Azure
            CTD.ReceivedMessage += CTD_ReceivedMessage;

            // Get user consent for accessing location
            Task.Run(async() =>
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                              async() =>
                {
                    this.LocationAccess = await Geolocator.RequestAccessAsync();
                    // Get device location
                    await updateLocation();
                });
            });

            // Connect to MS Band
            Task.Run(async() =>
            {
                await connectToBand();
            });
        }
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            GeolocationAccessStatus status = await Geolocator.RequestAccessAsync();

            if (status == GeolocationAccessStatus.Denied)
            {
                BtnNoAccess.Visibility = Visibility.Visible;
            }

            _geolocator = new Geolocator
            {
                DesiredAccuracyInMeters = 100,
                ReportInterval          = 5000
            };
            _geolocator.PositionChanged += Geolocator_PositionChanged;
            _geolocator.StatusChanged   += Geolocator_StatusChanged;
        }
Ejemplo n.º 24
0
        private static async System.Threading.Tasks.Task GetGeoLocationAsync()
        {
            GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:
                Log.WriteLine("Getting Geolocation data");

                Geolocator _geolocator = new Geolocator {
                    DesiredAccuracyInMeters = (uint)desiredAccuracyInMeters
                };

                // Subscribe to the StatusChanged event to get updates of location status changes.
#if false
                // TODO: disable updating due to very frequenty updating (per second).
                _geolocator.PositionChanged += OnPositionChanged;
#endif
                _geolocator.StatusChanged += OnStatusChangedAsync;

                // Carry out the operation.
                Geoposition pos = await _geolocator.GetGeopositionAsync();

                longitude = pos.Coordinate.Longitude;
                latitude  = pos.Coordinate.Latitude;

                await UpdateLocationDataAsync(pos);

                break;

            case GeolocationAccessStatus.Denied:
                Log.WriteLine("Geolocation: Access to location is denied.");
                //LocationDisabledMessage.Visibility = Visibility.Visible;
                await UpdateLocationDataAsync(null);

                break;

            case GeolocationAccessStatus.Unspecified:
            default:
                Log.WriteLine("Unspecified error.");
                await UpdateLocationDataAsync(null);

                break;
            }
        }
Ejemplo n.º 25
0
        public void StartTracking()
        {
#if WINDOWS_UWP
            IAsyncOperation <GeolocationAccessStatus> task = Geolocator.RequestAccessAsync();

            task.Completed = (asyncop, status) =>
            {
                GeolocationAccessStatus accessStatus = asyncop.GetResults();
                if (accessStatus == GeolocationAccessStatus.Allowed)
                {
                    geolocator.PositionChanged += OnGeolocatorPositionChanged;
                    isTracking = true;
                }
            };
#else
            geolocator.PositionChanged += OnGeolocatorPositionChanged;
#endif
        }
Ejemplo n.º 26
0
        public static async Task <bool> IsLocationCanAccess()
        {
            try
            {
                //request the access of geolocation
                GeolocationAccessStatus status = await Geolocator.RequestAccessAsync();

                if (status == GeolocationAccessStatus.Allowed)
                {
                    return(true);
                }
                return(false);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// get geo position (lat/long as basic info) for current device
        /// </summary>
        /// <returns>null - GPS not active now</returns>
        public async static Task <BasicGeoposition> GetGeoPosition()
        {
            GeolocationAccessStatus result = await Geolocator.RequestAccessAsync();

            if (result == GeolocationAccessStatus.Allowed)
            {
                Geolocator  geo = new Geolocator();
                Geoposition pos = await geo.GetGeopositionAsync();

                return(pos.Coordinate.Point.Position);
            }
            else
            {
                return(new BasicGeoposition()
                {
                    Longitude = 0d, Latitude = 0d, Altitude = 0d
                });
            }
        }
Ejemplo n.º 28
0
        private async void InitializeData()
        {
            loadGoal();

            goaltextbox.Text = goal.ToString();

            accessStatus = await Geolocator.RequestAccessAsync();

            if (accessStatus == GeolocationAccessStatus.Allowed)
            {
                gl = new Geolocator()
                {
                    MovementThreshold = 5, DesiredAccuracyInMeters = 5, ReportInterval = 1000
                };
                pos = await gl.GetGeopositionAsync();

                curPoint = new MapIcon()
                {
                    NormalizedAnchorPoint = new Point(0.5, 0.5),
                    Image    = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/LocationLogo.png")),
                    ZIndex   = 2,
                    Location = pos.Coordinate.Point
                };
                gpList = new List <Geoposition>()
                {
                    pos
                };
                bgpList = new List <BasicGeoposition>()
                {
                    pos.Coordinate.Point.Position
                };
                line = new MapPolyline()
                {
                    StrokeThickness = 2,
                    StrokeColor     = ((SolidColorBrush)Resources["SystemControlHighlightAccentBrush"]).Color,
                    ZIndex          = 1,
                    Path            = new Geopath(bgpList)
                };
                map.MapElements.Add(curPoint);
                track = false;
                gl.PositionChanged += OnPositionChanged;
            }
        }
Ejemplo n.º 29
0
        public async void Geolocate()
        {
            GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:
                _locator = new Geolocator {
                    DesiredAccuracy = PositionAccuracy.Default, MovementThreshold = 2
                };
                // geolocator = new Geolocator {ReportInterval = 1000};
                Geoposition pos = await _locator.GetGeopositionAsync();

                Location = pos.Coordinate.Point;
                UpdateLocation();
                _locator.PositionChanged += LocatorOnPositionChanged;
                break;
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            GeolocationAccessStatus status = await Geolocator.RequestAccessAsync();

            if (status == GeolocationAccessStatus.Allowed)
            {
                Geolocator  geolocator = new Geolocator();
                Geoposition position   = await geolocator.GetGeopositionAsync();

                Map.Center    = position.Coordinate.Point;
                Map.ZoomLevel = 15;

                Image marker = new Image();
                marker.Source = new BitmapImage(new Uri("ms-appx:///Assets/Marker.png", UriKind.Absolute));
                marker.Height = 64;
                Map.Children.Add(marker);
                MapControl.SetLocation(marker, position.Coordinate.Point);
                MapControl.SetNormalizedAnchorPoint(marker, new Point(0.5, 1.0));
            }
        }
Ejemplo n.º 31
0
        private async void giveMeDirections_Click(object sender, RoutedEventArgs e)
        {
            GeolocationAccessStatus locationAccessStatus = await Geolocator.RequestAccessAsync();

            if (locationAccessStatus == GeolocationAccessStatus.Allowed)
            {
                Geolocator geolocator = new Geolocator();
                geolocator.DesiredAccuracy = PositionAccuracy.High;
                Geoposition userPosition = await geolocator.GetGeopositionAsync();

                string formattedString = String.Format("bingmaps:?rtp=pos.{0}_{1}~adr.555%20North%20Point%20St,%20San%20Francisco,%20CA%2094133;mode=d&amp;trfc=1",
                                                       userPosition.Coordinate.Point.Position.Latitude, userPosition.Coordinate.Point.Position.Longitude);

                await Launcher.LaunchUriAsync(new Uri(formattedString));
            }
            else
            {
                if (!LocationAccessDenied)
                {
                    ContentDialog cd = new ContentDialog
                    {
                        Title               = "Oops, looks like you forgot to give us permission to your location",
                        Content             = @"To help us service you better we would like to request your location access. We respect user's privacy and your data is safe with us
                    Could you revist settings page and grant us permissions please? 
                    ",
                        PrimaryButtonText   = "Take me to settings",
                        SecondaryButtonText = "No Access for you!"
                    };
                    cd.PrimaryButtonClick   += cd_PrimaryButtonClick;
                    cd.SecondaryButtonClick += cd_SecondaryButtonClick;

                    await cd.ShowAsync();
                }
                else
                {
                    return;
                }
            }
        }
Ejemplo n.º 32
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();

            await RunOnLaunchInternetTasks();

            await HueHelper.Setup();

            if (device == Device.Desktop)
            {
                BuildDialMenu();
            }
            Task refreshLightStatus        = HueHelper.RefreshStatus();
            Task updateClockTask           = UpdateClockUI();
            Task checkFrozenVideo          = CheckFrozenVideo();
            Task processRotationBufferTask = ProcessRotationBuffer();

            _ = AirQualityHelper.Run();
            _ = CalendarHelper.Run();

            base.OnNavigatedTo(e);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Gets a raw geoposition object and returns it
        /// </summary>
        /// <returns>a raw geoposition object with a bunch of information</returns>
        /// <exception cref="LocationProviderException">If there's an error getting location (such as if the user disabled location access)</exception>
        public static async Task <Geoposition> GetCurrentLocation()
        {
            GeolocationAccessStatus accessStatus = await RequestLocationAccess();

            switch (accessStatus)
            {
            case GeolocationAccessStatus.Allowed:
                var locator  = new Geolocator();
                var position = await locator.GetGeopositionAsync();

                return(position);

            case GeolocationAccessStatus.Unspecified:
                throw new LocationProviderException("Unspecified Geolocation status");

            case GeolocationAccessStatus.Denied:
                throw new LocationProviderException("Location access is denied by the user");

            default:
                throw new LocationProviderException("Unknown error (hit default branch in switch)");
            }
        }
        internal static async Task <string> GetZipForGeopositionAsync(AppLogger appLogger)
        {
            string zip = null;

            GeolocationAccessStatus locationAccess = await Geolocator.RequestAccessAsync();

            if (locationAccess == GeolocationAccessStatus.Allowed)
            {
                Geolocator geolocator = new Geolocator
                {
                    DesiredAccuracyInMeters = DESIRED_ACCURACY_IN_METERS
                };

                Geoposition geoposition = await geolocator.GetGeopositionAsync();

                if (geoposition != null && geoposition.Coordinate != null && geoposition.Coordinate.Point != null)
                {
                    zip = await BigDataCloudReverseGeocodingService.GetZipAsync(geoposition, appLogger);
                }
            }

            return(zip);
        }
 public async void RequestAccess()
 {
     AccessStatus = await Geolocator.RequestAccessAsync();
 }
Ejemplo n.º 36
0
 private async void InitializeGeolocation() {
     AccessStatus = await RequestAccess();
 }