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(); }
private async Task SetLocation() { App.CurrentLocation = await Geolocation.GetLocationAsync(new GeolocationRequest { DesiredAccuracy = GeolocationAccuracy.High, Timeout = TimeSpan.FromSeconds(5) }); if (App.CurrentLocation == null) { App.CurrentLocation = await Geolocation.GetLastKnownLocationAsync(); } }
private async Task InitPosizione() { posizione = await Geolocation.GetLastKnownLocationAsync(); if (posizione is null) { posizione = await Geolocation.GetLocationAsync(new GeolocationRequest() { DesiredAccuracy = GeolocationAccuracy.Medium, Timeout = TimeSpan.FromSeconds(30) }); } }
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"); } }
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()); }
private async void GetPosition() { await Device.InvokeOnMainThreadAsync(async() => await Permissions.RequestAsync <Permissions.LocationAlways>()); while (true) { Location position = await Geolocation.GetLocationAsync(new GeolocationRequest(GeolocationAccuracy.Best, TimeSpan.FromSeconds(1))); Device.BeginInvokeOnMainThread(() => MainMap.UserCurrentLocation = position); //await Task.Delay(TimeSpan.FromSeconds(1)); } }
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); }
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(); } }
async void Button_Clicked(System.Object sender, System.EventArgs e) { isGettingLocation = true; while (isGettingLocation) { var result = await Geolocation.GetLocationAsync(new GeolocationRequest(GeolocationAccuracy.Default, TimeSpan.FromMinutes(1))); resultLocation.Text += $"lat: {result.Latitude}, lng: {result.Longitude}{Environment.NewLine}"; await Task.Delay(1000); } }
public static async Task <Location> GetMyLocation() { try { var location = await Geolocation.GetLocationAsync(); return(location); } catch (Exception ex) { return(null); } }
public override async void OnAppearing() { Barometer.ReadingChanged += OnReadingChanged; if (!Barometer.IsMonitoring) { Barometer.Start(SensorSpeed.UI); } var location = await Geolocation.GetLocationAsync(); GPSAltitude = location.Altitude.GetValueOrDefault(); }
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); }
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); }
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 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); } }
// ---------------------- EVENT - LADATAAN KAIKKI TEHTÄVÄT TIETOKANNASTA FRONTIIN ----------------------------------------// private async void btnGetWorkAssignments_Clicked(object sender, EventArgs e) { //viesti, ennen kuin näytetään palvelimelta tuleva sisältö listWorkAssignments.ItemsSource = new string[] { "Odota...ladataan tietoja" }; try { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("https://timesheetrestapiske.azurewebsites.net/"); string json = await client.GetStringAsync("/api/workassignments"); string[] assignments = JsonConvert.DeserializeObject <string[]>(json); listWorkAssignments.ItemsSource = assignments; } catch (Exception ex) { string errorMessage = ex.GetType().Name + ": " + ex.Message; listWorkAssignments.ItemsSource = new string[] { errorMessage }; } try { var location = await Geolocation.GetLastKnownLocationAsync(); if (location == null) { location = await Geolocation.GetLocationAsync(new GeolocationRequest { DesiredAccuracy = GeolocationAccuracy.Medium, Timeout = TimeSpan.FromSeconds(30) }); } if (location == null) { //lblGeo.Text = "Ei GPS-tietoja"; lblLatitude.Text = "Ei GPS-tietoja"; } else { lblLatitude.Text = ($"Lat: {location.Latitude}"); lblLongitude.Text = ($"Lon: {location.Longitude}"); } } catch (Exception ex) { lblLatitude.Text = ($"Jokin meni vikaan: {ex.Message}"); } }
//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); } }
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(); }); }
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"); } }
private async void actualizar_click(object sender, EventArgs e) { if (CheckConnection()) { try { MainThread.BeginInvokeOnMainThread(async() => { string resultado = ""; try { var g = await Geolocation.GetLocationAsync(); if (g != null) { resultado = "false"; } } catch (FeatureNotSupportedException fnsEx) { resultado = fnsEx.Message; } catch (FeatureNotEnabledException fneEx) { resultado = fneEx.Message; // Handle not enabled on device exception } catch (PermissionException pEx) { resultado = pEx.Message; // Handle permission exception } catch (Exception ex) { resultado = ex.Message; // Unable to get location } if (resultado.Equals(true)) { await DisplayAlert("GPS", resultado, "Aceptar"); return; } }); } catch (Exception ex) { string msg = ex.Message; } } }
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); } } } }
/// <summary>Gets the location asynchronously using geo coordinates from the device.</summary> /// <returns></returns> public async static Task <Location> GetLocationAsync() { var status = await CheckAndRequestPermissionAsync(new Permissions.LocationWhenInUse()); if (status != PermissionStatus.Granted) { // Return null and Notify user permission was denied return(null); } var location = await Geolocation.GetLocationAsync(); return(location); }
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); } }
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); } }
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)); } }
public async Task <Xamarin.Essentials.Location> GetLocation() { try { return(await Geolocation.GetLocationAsync(new GeolocationRequest(GeolocationAccuracy.Medium))); } catch (Exception) { Toast.MakeText(this, "Error occured", ToastLength.Long).Show(); var intent = new Intent(this, typeof(MainPage)); StartActivity(intent); } return(null); }
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"); } }
public static async Task <Location> GetLocation() { try { var location = await Geolocation.GetLocationAsync(GeolocationRequestHolder).ConfigureAwait(false); return(location); } catch (Exception e) { OnGeolocationFailed(e); return(null); } }
public async Task <Xamarin.Essentials.Location> CreateObjectAsyncYelp() { var locationResult = await Geolocation.GetLocationAsync(); if (locationResult != null) { Console.WriteLine($"Latitude: {locationResult.Latitude}, Longitude: {locationResult.Longitude}"); } // var result = await _logger.GetAsync(); // more code here... return(locationResult); }
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); }