Пример #1
0
        public async Task <bool> AttemptGPSAsync()
        {
            try
            {
                Debug.WriteLine("Getting device GPS capabilities.");

                GeolocationRequest request  = new GeolocationRequest(GeolocationAccuracy.Best);
                Location           location = await Geolocation.GetLocationAsync(request);

                if (location != null)
                {
                    Debug.WriteLine($"Got the device's current location: {location.Latitude}, {location.Longitude}.");
                }
                else
                {
                    Debug.WriteLine("Failed to get the device's current location.");
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
                Debug.WriteLine($"Failed to get the device's current location: {fnsEx}.");
                await App.Current.MainPage.DisplayAlert("GPS Not Supported", "Your device does not have gps capabilities.\n\nLocation tracking can't be enabled on this device possibly.", "OK");

                return(false);
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
                Debug.WriteLine($"Failed to get the device's current location: {fneEx}.");
                await App.Current.MainPage.DisplayAlert("GPS Not Enabled", "Your device does not have its gps enabled.\n\nLocation tracking will still be enabled but it won't receive updates untill the gps is enabled.", "OK");

                return(true);
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
                Debug.WriteLine($"Failed to get the device's current location: {pEx}.");
                await App.Current.MainPage.DisplayAlert("GPS Permission Denied", "This app does not have permission to access your location.\n\nLocation tracking can't be enabled untill permission is granted.", "OK");

                return(false);
            }
            catch (Exception ex)
            {
                // Unable to get location
                Debug.WriteLine($"Failed to get the device's current location: {ex}.");
                await App.Current.MainPage.DisplayAlert("Unexpected GPS Failure", "Something unexpected happened.\n\nLocation tracking won't be enabled for now. If this continues to occur then something might have broken in this app.", "OK");

                return(false);
            }
            return(true);
        }
        //------------------------------------------EVENT----LOAD-WORKS----------------------------------------------

        private async void LoadWorkAssignments(object sender, EventArgs e)
        {
            //Alustus, ennen palvelimen vastauksen saapumista näytetään ilmoitus lataamisesta.
            assignmentList.ItemsSource = new string[] { "Ladataan..." };


            // -------------------Sijainnin haku ja näyttäminen--------
            try
            {
                var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
                var location = await Geolocation.GetLocationAsync(request);

                if (location != null)
                {
                    longitudeLabel.Text = location.Longitude.ToString();

                    latitudeLabel.Text = location.Latitude.ToString();
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                longitudeLabel.Text = "error";
            }
            catch (FeatureNotEnabledException fneEx)
            {
                longitudeLabel.Text = "error";
            }
            catch (PermissionException pEx)
            {
                longitudeLabel.Text = "error";
            }
            catch (Exception ex)
            {
                longitudeLabel.Text = "error";
            }

            try //----------HTTP pyyntö--------------------
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("https://timesheetrestapi.azurewebsites.net/");
                string json = await client.GetStringAsync("/api/workassignments/");

                string[] assignments = JsonConvert.DeserializeObject <string[]>(json);

                assignmentList.ItemsSource = assignments;
            }
            catch (Exception ex)
            {
                string errorMessage = ex.GetType().Name + ": " + ex.Message;
                assignmentList.ItemsSource = new string[] { errorMessage };
            }
        }
        public async void ObtainDeviceLocation()
        {
            //var policy = Policy
            //        .Handle<HttpRequestException>()
            //        .RetryAsync
            //        (3);

            //await policy.ExecuteAsync(async () =>
            //{
            try
            {
                var request = new GeolocationRequest(GeolocationAccuracy.High);
                var lc      = await Geolocation.GetLocationAsync(request);

                if (lc != null)
                {
                    if (lc.IsFromMockProvider)
                    {
                        // location is from a mock provider
                        await DisplayAlert("Mock", "Mock Location Detected!", "Close");
                    }
                    else
                    {
                        lat = lc.Latitude;
                        lon = lc.Longitude;
                        lblLocation.Text = lat.ToString();
                        //lblLocation.Text = "ENUGU";
                        //locationLoader.IsRunning = false;
                        //locationLoader.IsEnabled = false;
                        //locationLoader.IsVisible = false;
                        verifyUserLocation(lat, lon);
                    }
                }
            }
            catch (FeatureNotSupportedException featureNotSupportedException)
            {
            }
            catch (FeatureNotEnabledException featureNotEnabledException)
            {
                //> I would force to enable device's gps in this line
                await PopupNavigation.Instance.PushAsync(new EnableGPS());
            }
            catch (PermissionException permissionException)
            {
                AppInfo.ShowSettingsUI();
            }
            catch (Exception exception)
            {
            }

            //});
        }
Пример #4
0
        protected override async void OnAppearing()
        {
            base.OnAppearing();

            //  chiamataAPi today activities();
            HttpResponseMessage response = await RestService.GetLogToday();

            Debug.Print(response.ToString());
            if (response.IsSuccessStatusCode)
            {
                if (response.Content.ToString() != "null" && !String.IsNullOrEmpty(response.Content.ToString()))
                {
                    string contents = await response.Content.ReadAsStringAsync();

                    activities.attivitaGiornaliera = JsonConvert.DeserializeObject <ActivityComplete>(contents);
                    Debug.Print(activities.attivitaGiornaliera.ToString());
                }
                else
                {
                }
            }
            //GEOLOCALIZZAZIONE CHECKIN CHECKOUT
            try
            {
                var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
                var location = await Geolocation.GetLocationAsync(request);


                if (location != null)
                {
                    await DisplayAlert("gps", "Latitude:" + location.Latitude + "\nLongitude:" + location.Longitude + "\nAltitude" + location.Altitude, "OK");

                    Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
                }


                //coordinate campus reti: 45.609344, 8.849487
                //coordinate mie: 45.6086928, 8.8474045
                Xamarin.Essentials.Location its = new Xamarin.Essentials.Location(45.609344, 8.849487);
                double dist = Xamarin.Essentials.Location.CalculateDistance(location, its, DistanceUnits.Kilometers); //distanza in kilometri --> metri = dist*1000


                await DisplayAlert("distanza", dist.ToString() + "\nDistanza metri:" + (dist * 1000).ToString(), "OK");
            }
            catch (Exception excp)
            {
                Console.WriteLine(excp);
            }


            // chiamata check
        }
Пример #5
0
        private void OnTimedGetLocationEvent(object sender, ElapsedEventArgs e)
        {
            try
            {
                Device.BeginInvokeOnMainThread(async() =>
                {
                    var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
                    var location = await Geolocation.GetLocationAsync(request);

                    if (location != null)
                    {
                        LatLonCollection.Insert(0, new LatLon {
                            Latitude = location.Latitude.ToString(), Longitude = location.Longitude.ToString()
                        });
                        //Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
                        string loca = Newtonsoft.Json.JsonConvert.SerializeObject(new
                        {
                            uid       = id,
                            latitude  = location.Latitude,
                            longitude = location.Longitude,
                        });
                        var content = new StringContent(loca, Encoding.UTF8, "application/json");


                        var response = await client.PostAsync("https://162.236.218.100:5005//gpsdata", content);
                        var result   = response.Content.ReadAsStringAsync().Result;

                        Debug.WriteLine("Neku for smash" + result);
                    }
                });
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
                Console.WriteLine(fnsEx.Message);
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
                Console.WriteLine(fneEx.Message);
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
                Console.WriteLine(pEx.Message);
            }
            catch (Exception ex)
            {
                // Unable to get location
                Console.WriteLine(ex.Message);
            }
        }
Пример #6
0
        private async void BtnSearch_Click(object sender, RoutedEventArgs e)
        {
            var locationFrom = new LocationDto();
            var locationTo   = new LocationDto();

            try
            {
                if (_from == null)
                {
                    var request  = new GeolocationRequest(GeolocationAccuracy.High);
                    var location = await Geolocation.GetLocationAsync(request);

                    if (location != null)
                    {
                        var gpsLocation = new LocationDto
                        {
                            Altitude  = location.Altitude.ToString(),
                            Latitude  = location.Latitude.ToString(),
                            Longitude = location.Longitude.ToString()
                        };
                        locationFrom = gpsLocation;
                    }
                    if (_to == null)
                    {
                        _to = new MatrackPlace
                        {
                            Name        = "Nairobi CBD",
                            LocationDto = new LocationDto
                            {
                                Latitude  = "-1.292066",
                                Longitude = "36.821945"
                            }
                        };
                    }
                }
                else
                {
                    locationFrom = _from.LocationDto;
                }
                if (GlobalHelpers.HubConnection.State == HubConnectionState.Disconnected)
                {
                    await GlobalHelpers.HubConnection.StartAsync();
                }
                await GlobalHelpers.HubConnection.InvokeAsync("GetLocation",
                                                              _from, _to);
            }
            catch (Exception ex)
            {
                MessageDialog messageDialog = new MessageDialog(ex.Message);
                await messageDialog.ShowAsync();
            }
        }
        public async System.Threading.Tasks.Task sendLocation(string number, bool playAudio)
        {
            var request  = new GeolocationRequest(GeolocationAccuracy.Best);
            var location = await Geolocation.GetLocationAsync(request);

            string message = "I got lost around here: http://www.google.com/maps/place/" + location.Latitude + "," + location.Longitude;

            SmsManager.Default.SendTextMessage(number, null, message, null, null);
            if (playAudio)
            {
                locationSent.Start();
            }
        }
Пример #8
0
        public void GeolocationWhenConsiderIpTest()
        {
            var request = new GeolocationRequest
            {
                Key        = this.ApiKey,
                ConsiderIp = true
            };

            var result = GoogleMaps.Geolocation.Query(request);

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);
        }
Пример #9
0
        public void GeolocationWhenHomeMobileNetworkCodeTest()
        {
            var request = new GeolocationRequest
            {
                Key = this.ApiKey,
                HomeMobileNetworkCode = "410"
            };

            var result = GoogleMaps.Geolocation.Query(request);

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);
        }
Пример #10
0
        public void GeolocationWhenCarrierTest()
        {
            var request = new GeolocationRequest
            {
                Key     = this.ApiKey,
                Carrier = "Vodafone"
            };

            var result = GoogleMaps.Geolocation.Query(request);

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);
        }
Пример #11
0
        async Task OpenLocation()
        {
            var request = new GeolocationRequest(GeolocationAccuracy.Medium);
            var gps     = await Geolocation.GetLocationAsync(request);

            var placemarks = await Geocoding.GetPlacemarksAsync(gps.Latitude, gps.Longitude);

            var placemark = placemarks?.FirstOrDefault();

            Latitud   = gps.Latitude.ToString();
            Longitud  = gps.Longitude.ToString();
            Direccion = placemark.FeatureName.ToString();
        }
Пример #12
0
        public async void EnviarCoordenadas(int orden)
        {
            //var position = await Task.Run(() => CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(2)));
            var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
            var location = await Geolocation.GetLocationAsync(request);

            await hubConnection.SendAsync("EnviarMessage", orden, location.Latitude, location.Longitude);

            //var locator = CrossGeolocator.Current;
            //var position2 = await locator.GetPositionAsync(TimeSpan.FromSeconds(20), null, true);

            //var sendlocation = new Signalr(position2.Latitude, position2.Longitude);
        }
Пример #13
0
        public void GeolocationWhenRadioTypeTest()
        {
            var request = new GeolocationRequest
            {
                Key = this.ApiKey
            };

            var result = GoogleMaps.Geolocation.QueryAsync(request).Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);
            Assert.IsNotNull(result.Location);
        }
Пример #14
0
        public override Result DoWork()
        {
            Location local   = null;
            var      request = new GeolocationRequest(GeolocationAccuracy.Default);

            local = Geolocation.GetLocationAsync(request).GetAwaiter().GetResult();

            Log.Info("Teste", $"Trabalho funcionando - {DateTime.Now}");

            Log.Info("Local", $"Latitude:{local?.Latitude}, Longitude:{local?.Longitude}");

            return(new Result.Retry());
        }
Пример #15
0
        private async void ShowMap()
        {
            var request      = new GeolocationRequest(GeolocationAccuracy.Medium);
            var gps_location = await Geolocation.GetLocationAsync(request);

            location.currentLocation = new Android.Locations.Location(LocationService)
            {
                Latitude = gps_location.Latitude, Longitude = gps_location.Longitude
            };
            var mapFragment = (SupportMapFragment)SupportFragmentManager.FindFragmentById(Resource.Id.fragment1);

            mapFragment.GetMapAsync(this);
        }
Пример #16
0
 private async void GetLocationButtonOnClicked(object sender, EventArgs e)
 {
     try
     {
         var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
         var location = await Geolocation.GetLocationAsync(request);
         await DisplayAlert("Geolocation", location != null?$"Latitude: {location.Latitude}{Environment.NewLine}Longitude: {location.Longitude}" : "Your last known location is currently unknown.", "Ok");
     }
     catch (Exception ex)
     {
         await DisplayAlert("Geolocation", $"Something went wrong: {ex}", "Ok");
     }
 }
Пример #17
0
        public async Task <string> GetUserLocationAsync()
        {
            //More accurate/recent, may take some time for a response
            var request  = new GeolocationRequest(GeolocationAccuracy.High, TimeSpan.FromSeconds(10));
            var location = await Geolocation.GetLocationAsync(request);

            //faster, will return null if there is no cached location
            //var location = await Geolocation.GetLastKnownLocationAsync();
            var latstr = location.Latitude.ToString();
            var lonstr = location.Longitude.ToString();

            return(latstr + ',' + lonstr);
        }
Пример #18
0
        public static async Task <Plugin.Permissions.Abstractions.PermissionStatus> CheckLocationServices()
        {
            try
            {
                Plugin.Permissions.Abstractions.PermissionStatus status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);

                Plugin.Permissions.Abstractions.PermissionStatus status2 = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.LocationWhenInUse);

                Plugin.Permissions.Abstractions.PermissionStatus status3 = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.LocationAlways);

                Console.WriteLine("Location Permissions: Location: " + status.ToString() + ", When In Use: " + status2.ToString() + ", Always: " + status3.ToString());
                if (status3 != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        if (Device.RuntimePlatform == Device.iOS)
                        {
                            ILocationManager manager = DependencyService.Get <ILocationManager>();
                            manager.RequestBackgroundLocation();
                        }
                    });
                }
                else
                {
                    try
                    {
                        var request  = new GeolocationRequest(GeolocationAccuracy.Lowest, new TimeSpan(0, 0, 0, 0, 100));
                        var location = await Geolocation.GetLocationAsync(request);

                        if (location != null)
                        {
                            Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
                        }
                    }
                    catch (FeatureNotSupportedException)
                    {
                        return(Plugin.Permissions.Abstractions.PermissionStatus.Denied);
                    }
                    catch (FeatureNotEnabledException)
                    {
                        return(Plugin.Permissions.Abstractions.PermissionStatus.Denied);
                    }
                }
                return(status3);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                return(Plugin.Permissions.Abstractions.PermissionStatus.Denied);
            }
        }
Пример #19
0
        //protected async override void OnAppearing()
        //{
        //    base.OnAppearing();
        //    try
        //    {
        //        var location = await Geolocation.GetLastKnownLocationAsync();
        //        if (location != null)
        //        {
        //            Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
        //            LabelLatLong.Text = "Lat : " + location.Latitude + "Long : " + location.Longitude;
        //        }
        //    }
        //    catch (FeatureNotSupportedException fnsEx)
        //    {
        //        // Handle not supported on device exception
        //        Console.WriteLine(fnsEx);
        //    }
        //    catch (FeatureNotEnabledException fneEx)
        //    {
        //        // Handle not enabled on device exception
        //        Console.WriteLine(fneEx);
        //    }
        //    catch (PermissionException pEx)
        //    {
        //        // Handle permission exception
        //        Console.WriteLine(pEx);
        //    }
        //    catch (Exception ex)
        //    {
        //        // Unable to get location
        //        Console.WriteLine(ex);
        //    }
        //}

        private async void Button_Clicked(object sender, EventArgs e)
        {
            try
            {
                DateStart.Text = "DateStart : " + DateTime.UtcNow.ToString();
                //DependencyService.Get<IGetGPS>().GetGPS();
                var request  = new GeolocationRequest(GeolocationAccuracy.Best, TimeSpan.FromSeconds(10));
                var location = await Geolocation.GetLocationAsync(request);

                LabelLatLong.Text = "Lat : " + location.Latitude + "Long : " + location.Longitude;
                DateEnd.Text      = "DateEnd : " + DateTime.UtcNow.ToString();
                //var check = DependencyService.Get<IGetGPS>().Getvalue();
                //var request = new GeolocationRequest(GeolocationAccuracy.Best, TimeSpan.FromSeconds(1));
                //DateStart.Text = "DateStart : " + DateTime.UtcNow.ToString();
                //if (check == false)
                //{
                //    bool answer = await DisplayAlert("แจ้งเตือน", "กรุณาเปิดตำแหน่งของโทรศัพย์ก่อน", "เปิด", "ไม่เปิด");
                //    //Debug.WriteLine("Answer: " + answer);
                //    if (answer == true)
                //    {
                //        DependencyService.Get<IGetGPS>().GetGPS();
                //    }
                //}
                //else
                //{
                //    var location = await Geolocation.GetLocationAsync(request);
                //    LabelLatLong.Text = "Lat : " + location.Latitude + "Long : " + location.Longitude;
                //    DateEnd.Text = "DateEnd : " + DateTime.UtcNow.ToString();
                //}
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
                Console.WriteLine(fnsEx);
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
                Console.WriteLine(fneEx);
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
                Console.WriteLine(pEx);
            }
            catch (Exception ex)
            {
                // Unable to get location
                Console.WriteLine(ex);
            }
        }
Пример #20
0
        private async void GenerateAPin()
        {
            try
            {
                var response = await Helpers.Utils.PermissionsStatus(Plugin.Permissions.Abstractions.Permission.Location);

                if (response)
                {
                    var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
                    var location = await Geolocation.GetLocationAsync(request);

                    if (location != null)
                    {
                        var pin = new Pin
                        {
                            Type     = PinType.Place,
                            Label    = "Aqui estas!!",
                            Position = new Position(location.Latitude, location.Longitude),
                        };
                        map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(location.Latitude, location.Longitude), Distance.FromMeters(500)));
                        //pin.Icon= BitmapDescriptorFactory.FromBundle("");
                        map.Pins.Add(pin);
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    var location = await Geolocation.GetLastKnownLocationAsync();

                    if (location != null)
                    {
                        if (location != null)
                        {
                            var pin = new Pin
                            {
                                Type     = PinType.Place,
                                Label    = "Aqui estas!!",
                                Position = new Position(location.Latitude, location.Longitude)
                            };
                            map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(location.Latitude, location.Longitude), Distance.FromMeters(500)));
                            map.Pins.Add(pin);
                        }
                    }
                }
                catch (Exception e)
                {
                }
            }
        }
        public MainPageViewModel(INavigationService navigationService,
                                 IPageDialogService dialogService)
        {
            _navigationService = navigationService;
            _dialogService     = dialogService;
            GetLocationCommand = new DelegateCommand(async() =>
            {
                if (GeolocationAccuracySelected == null)
                {
                    await _dialogService.DisplayAlertAsync("錯誤", "請選擇GPS定位精確度", "確定");
                    return;
                }
                CTS         = new CancellationTokenSource();
                Token       = CTS.Token;
                GetLocation = true;

                try
                {
                    var request  = new GeolocationRequest(GeolocationAccuracySelected.Item, TimeSpan.FromSeconds(10));
                    var location = await Geolocation.GetLocationAsync(request, Token);

                    if (location != null)
                    {
                        YourLocation = $"Latitude 緯度 : {location.Latitude}, Longitude 經度 : {location.Longitude}";
                    }
                }
                catch (FeatureNotSupportedException fnsEx)
                {
                    // 處理裝置不支援這項功能的例外異常
                }
                catch (PermissionException pEx)
                {
                    // 處理關於權限上的例外異常
                }
                catch (AggregateException ae)
                {
                    // 處理取消的例外異常
                }
                catch (Exception ex)
                {
                    // 無法取得該GPS位置之例外異常
                }

                GetLocation = false;
            });
            CancelLocationCommand = new DelegateCommand(() =>
            {
                GetLocation = false;
                CTS.Cancel();
            });
        }
Пример #22
0
        async void Gps_Clicked(System.Object sender, System.EventArgs e)
        {
            try
            {
                // configuramos el nivel de precisión y el tiempo de espera de respuesta
                // es importante considerar que a mayor precisión  se requiere mas tiempo de calculo.
                var request = new GeolocationRequest(GeolocationAccuracy.Best, TimeSpan.FromSeconds(10));
                // obtenemos el token de cancelación
                cts = new CancellationTokenSource();
                // y pasamos a pedir que el celular calcule la ubicación
                var location = await Geolocation.GetLocationAsync(request, cts.Token);

                // el objeto location nos entrega los valores para trabajar con ellos.

                // location.Accuracy :  precisión horizontal
                // location.VerticalAccuracy : precisión vertical
                // location.Timestamp : fecha hora de la lectura por el celular
                // location.Speed :  velocidad de desplazamiento entre diferentes lecturas, da el promedio de velocidad entre puntos
                // location.Course : número de grados con respecto al norte
                // location.Altitude : altitude  que reporta el celular cuando este puede dar la altitud da null o 0 si no hay dato
                // location.OpenMapsAsync  : abre mapa con las coordenadas

                if (location != null)
                {
                    txtLat.Text       = location.Latitude.ToString();
                    txtLong.Text      = location.Longitude.ToString();
                    txtAltitud.Text   = location.Altitude.ToString();
                    txtVelocidad.Text = location.Speed.ToString();
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                // Handle not supported on device exception
                await DisplayAlert("Mi App", "Mi dispositivo no soporta GPS", "Continuar");
            }
            catch (FeatureNotEnabledException fneEx)
            {
                // Handle not enabled on device exception
                await DisplayAlert("Mi App", "Mi dispositivo genero un error", "Continuar");
            }
            catch (PermissionException pEx)
            {
                // Handle permission exception
                await DisplayAlert("Mi App", "Mi dispositivo no tiene permiso para el gps", "Continuar");
            }
            catch (Exception ex)
            {
                // Unable to get location
                await DisplayAlert("Mi App", "Mi dispositivo fallo al traer mi ubicación", "Continuar");
            }
        }
Пример #23
0
        private async Task FallDetectedAsync()
        {
            stopPressed                 = false;
            stopButton.IsEnabled        = true;
            fallDetectedLabel.IsVisible = true;
            //System.Threading.Thread.Sleep(10000);

            var duration = TimeSpan.FromSeconds(10);

            Vibration.Vibrate(duration);

            await Task.Delay(10000);

            if (stopPressed == false)
            {
                if (telephone.Text != null)
                {
                    string latitude  = null;
                    string longitude = null;
                    try
                    {
                        var request  = new GeolocationRequest(GeolocationAccuracy.Best);
                        var location = await Geolocation.GetLocationAsync(request);

                        if (location != null)
                        {
                            latitude  = location.Latitude.ToString();
                            longitude = location.Longitude.ToString();

                            latitude  = latitude.Replace(',', '.');
                            longitude = longitude.Replace(',', '.');
                        }
                    }
                    catch (FeatureNotSupportedException fnsEx)
                    { }
                    catch (FeatureNotEnabledException fneEx)
                    { }
                    catch (PermissionException pEx)
                    { }
                    catch (Exception ex)
                    { }

                    if (latitude != null && longitude != null)
                    {
                        string link = "https://www.google.com/maps/search/?api=1&query=" + latitude + "," + longitude;
                        string msg  = "Pomocy, upadłem! Moja lokalizacja: " + link;
                        await SendSms(msg, telephone.Text);
                    }
                }
            }
        }
Пример #24
0
        public void GeolocationWhenHomeMobileCountryCodeTest()
        {
            var request = new GeolocationRequest
            {
                Key = this.ApiKey,
                HomeMobileCountryCode = "310"
            };

            var result = GoogleMaps.Geolocation.QueryAsync(request).Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(Status.Ok, result.Status);
            Assert.IsNotNull(result.Location);
        }
Пример #25
0
        public async void StartMap(bool first)
        {
            //renders map, centres on user, creates pins from plots
            try
            {
                Pins = new List <TKCustomMapPin>();
                int num = ((List <Plot>)Application.Current.Properties["Plots"]).Count();
                for (int x = 0; x < num; x++)
                {
                    double[] pinLoc   = ((List <Plot>)Application.Current.Properties["Plots"]).ElementAt(x).GetTag();
                    Position position = new Position(pinLoc[0], pinLoc[1]);
                    Pins.Add(new TKCustomMapPin
                    {
                        Position    = position,
                        Title       = ((List <Plot>)Application.Current.Properties["Plots"]).ElementAt(x).GetName(),
                        IsVisible   = true,
                        ShowCallout = true
                    });
                }
                MyMap.Pins = Pins;
            }
            catch {
                Device.BeginInvokeOnMainThread(() =>
                {
                    DisplayAlert("dataLoad", "Data load error", "OK");
                });
            }
            try
            {
                if (first)
                {
                    request = new GeolocationRequest(GeolocationAccuracy.High);
                    var location = await Geolocation.GetLocationAsync(request);

                    if (location != null)
                    {
                        MyMap.MoveToMapRegion(
                            MapSpan.FromCenterAndRadius(
                                new Position(location.Latitude, location.Longitude), Distance.FromKilometers(1)));
                    }
                }
            }
            catch (Exception ex)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    DisplayAlert("map load error", ex.Message, "OK");
                });
            }
        }
Пример #26
0
        public static async Task <bool> IsMockProvider()
        {
            var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
            var location = await Geolocation.GetLocationAsync(request);

            if (location != null && location.IsFromMockProvider)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #27
0
        public async Task <string> GetLocation()
        {
            var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
            var location = await Geolocation.GetLocationAsync(request);

            if (location != null)
            {
                return(location.Latitude + "," + location.Longitude);
            }
            else
            {
                return("Boş Koordinat");
            }
        }
Пример #28
0
        async public static System.Threading.Tasks.Task <Sight> BuildSightAsync(int?positionID)
        {
            try
            {
                var request  = new GeolocationRequest(GeolocationAccuracy.High);
                var location = await Geolocation.GetLocationAsync(request);

                return(new Sight(positionID, location));
            }
            catch (Exception ex)
            {
                return(new Sight(positionID));
            }
        }
Пример #29
0
        public static async Task <Location> CurrentLocation()
        {
            try
            {
                var request  = new GeolocationRequest(GeolocationAccuracy.Medium);
                var location = await Geolocation.GetLocationAsync(request);

                return(location);
            }
            catch (Exception ex)
            {
                throw new Exception(nameof(CurrentLocation), ex);
            }
        }
Пример #30
0
        public async Task <string> GetGpsLocation()
        {
            var request  = new GeolocationRequest(GeolocationAccuracy.High);
            var location = await Geolocation.GetLocationAsync(request);

            if (location != null)
            {
                return($"{nameof(Location.Latitude)}: {location.Latitude}<br />" +
                       $"{nameof(Location.Longitude)}: {location.Longitude}<br />" +
                       $"{nameof(Location.Altitude)}: { location.Altitude ?? 0.00 }");
            }

            return(null);
        }