private async void Alerts_ShowMapHandler(object sender, AlertsFragment.ShowMapFragmentArgs e) { if (e.Type == 1) { System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US"); cultureInfo.NumberFormat.NumberDecimalSeparator = "."; System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo; MapFragmentDialog profile = new MapFragmentDialog(e.Alerts.UserKey); SupportFragmentManager.BeginTransaction() .Replace(Resource.Id.fragHost, profile) .Commit(); } else { System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US"); cultureInfo.NumberFormat.NumberDecimalSeparator = "."; System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo; var location = new Xamarin.Essentials.Location(double.Parse(e.Alerts.Lat), double.Parse(e.Alerts.Lon)); var options = new MapLaunchOptions { Name = "Victim", }; try { await Map.OpenAsync(location, options); } catch (Exception ex) { // No map application available to open Console.WriteLine(ex.Message); } } }
public static async Task <PlaceInfo> AsyncGetPlaceName(GpsLocation location) { //https://docs.microsoft.com/en-us/xamarin/essentials/geocoding?tabs=android try { var loc = new Xamarin.Essentials.Location(location.Latitude, location.Longitude); var placemarks = await Geocoding.GetPlacemarksAsync(loc); var placemark = placemarks?.FirstOrDefault(); if (placemark != null) { var geocodeAddress = placemark.Thoroughfare; geocodeAddress = geocodeAddress.Append(" ", placemark.SubThoroughfare); geocodeAddress = geocodeAddress.Append(", ", placemark.SubLocality); geocodeAddress = geocodeAddress.Append(", ", placemark.Locality); geocodeAddress = geocodeAddress.Append(", ", placemark.CountryCode); var country = PoiCountryHelper.GetCountry(placemark.CountryCode) ?? PoiCountryHelper.GetDefaultCountryByPhoneSettings(); return(new PlaceInfo(geocodeAddress, country)); } return(new PlaceInfo()); } catch { return(new PlaceInfo()); } }
//void PlaceList_ItemSelected(object sender, Xamarin.Forms.SelectedItemChangedEventArgs e) //{ // var item = (string)e.SelectedItem; // CategoryName.Text = item; // CategoryName.TextColor = Color.Black; // //throw new NotImplementedException(); //} //void Handle_ItemTapped(object sender, Xamarin.Forms.ItemTappedEventArgs e) //{ // var data = e.Item; // //throw new NotImplementedException(); //} async void PlaceType_ItemSelected(object sender, System.EventArgs e) { Label lblClicked = (Label)sender; CategoryName.Text = lblClicked.Text; CategoryName.TextColor = Color.Black; CetegoryPopup.IsVisible = !CetegoryPopup.IsVisible; BlurBG.IsVisible = !BlurBG.IsVisible; //var city = Address?.FirstOrDefault(). //CurrentCity.Text = $"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + location.Latitude + "," + location.Longitude + "&radius=150000&type=" + CategoryName.Text.ToLower(); var result = await NearByService.GetNearByPlacesAsync(location, CategoryName.Text); foreach (var item in result) { //FInd Distance Xamarin.Essentials.Location sourceCoordinates = location; Xamarin.Essentials.Location destinationCoordinates = new Xamarin.Essentials.Location(item.geometry.location.lat, item.geometry.location.lng); //new Location(destinationLocations.Latitude, destinationLocations.Longitude); double distance = Xamarin.Essentials.Location.CalculateDistance(sourceCoordinates, destinationCoordinates, DistanceUnits.Kilometers); item.distance = distance; } PlaceList.ItemsSource = result; }
public async Task RetrieveLocation() { var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 20; //initialize point A var positionA = await locator.GetPositionAsync(); do { //wait 10 sec for point B await Task.Delay(10000); //get new position var positionB = await locator.GetPositionAsync(); Xamarin.Essentials.Location FromLocA = new Xamarin.Essentials.Location(positionA.Longitude, positionA.Latitude); Xamarin.Essentials.Location ToLocB = new Xamarin.Essentials.Location(positionB.Longitude, positionB.Latitude); //running total of gps distances totalDistance += LocationExtensions.CalculateDistance(FromLocA, ToLocB, DistanceUnits.Miles); //set point A to point B to collect new distance positionA = positionB; if (totalDistance == 0) { lblDistance.Text = "0.00 miles walked"; } else { lblDistance.Text = totalDistance.ToString("#.##") + " miles walked"; } } while (stopGeo == false); }
private async Task <SimplyWeatherLocation> GetLastKnownLocation() { try { Xamarin.Essentials.Location lastKnownLocation = await Geolocation.GetLastKnownLocationAsync(); if (lastKnownLocation != null) { return(SimplyWeatherLocation.Known(lastKnownLocation.Latitude, lastKnownLocation.Longitude)); } } catch (FeatureNotSupportedException) { return(SimplyWeatherLocation.Unavailable()); } catch (FeatureNotEnabledException) { return(SimplyWeatherLocation.Disabled()); } catch (PermissionException) { return(SimplyWeatherLocation.PermissionRequired()); } catch (Exception e) { Debug.WriteLine($"Error retrieving last known location: {e.StackTrace}"); return(SimplyWeatherLocation.Unknown()); } throw new Exception("Unable to get Last location"); }
public async Task UpdateLocationAsync(Xamarin.Essentials.Location position, Placemark address, string mood, string accessToken) { try { var client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); var location = new SharedModels.LocationUpdate { Country = address.CountryCode, Position = new Microsoft.Azure.Documents.Spatial.Point(position.Longitude, position.Latitude), State = address.AdminArea, Town = address.Locality, Mood = mood }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(location); var content = new System.Net.Http.StringContent(json); var resp = await client.PostAsync(CommonConstants.FunctionUrl, content); var respBody = await resp.Content.ReadAsStringAsync(); } catch (Exception ex) { Crashes.TrackError(ex); System.Diagnostics.Debug.WriteLine($"ERROR: {ex.Message}"); } }
public async void GetLocation() { loca = await Geolocation.GetLastKnownLocationAsync(); if (loca == null) { loca = await Geolocation.GetLocationAsync(new GeolocationRequest { DesiredAccuracy = GeolocationAccuracy.Medium, Timeout = TimeSpan.FromSeconds(30) });; } loc.Text = "enlem; " + loca.Latitude.ToString() + " boylam: " + loca.Longitude.ToString(); if (!string.IsNullOrWhiteSpace(nameEntry.Text)) { await App.Database.SavePersonAsync(new Person { Name = nameEntry.Text, enlem = loca.Latitude, boylam = loca.Longitude, }); nameEntry.Text = string.Empty; listView.ItemsSource = await App.Database.GetPeopleAsync(); } }
//int x = 0; public async void UploadLocation(Xamarin.Essentials.Location location) { try { var id = await SecureStorage.GetAsync("clientId"); var address = $"http://192.168.1.103:5166?id=1234{id}×tamp={location.Timestamp.UtcDateTime}&lat={location.Latitude}&lon={location.Longitude}&altitude={location.Altitude}&speed={location.Speed}&bearing={location.Course}&accuracy={location.Accuracy}"; // var address = $"http://sake.org.ng:5166?id={id}×tamp={location.Timestamp.UtcDateTime}&lat={location.Latitude}&lon={location.Longitude}&altitude={location.Altitude}&speed={location.Speed}&bearing={location.Course}&accuracy={location.Accuracy}"; //notifier.ScheduleNotification("Location", x.ToString()); //x++; var client = new HttpClient(); //client.BaseAddress = new Uri(address); var content = new StringContent("", Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(address, content); var result = await response.Content.ReadAsStringAsync(); if (location != null) { Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}"); } lastLocation = location; }catch (Exception e) { } }
private async Task <Xamarin.Essentials.Location> GetLocation() { Xamarin.Essentials.Location location = null; try { location = await Geolocation.GetLastKnownLocationAsync(); if (location != null) { Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}"); } } catch (FeatureNotSupportedException fnsEx) { // Handle not supported on device exception } catch (FeatureNotEnabledException fneEx) { // Handle not enabled on device exception } catch (PermissionException pEx) { // Handle permission exception } catch (Exception ex) { // Unable to get location } return(location); }
public static async Task <Placemark> ReverseGeocodeLocation(Xamarin.Essentials.Location currentLocation) { var lat = currentLocation.Latitude; var lon = currentLocation.Longitude; var placemarks = await Geocoding.GetPlacemarksAsync(lat, lon); var placemark = placemarks?.FirstOrDefault(); if (placemark != null) { var geocodeAddress = $"AdminArea: {placemark.AdminArea}\n" + $"CountryCode: {placemark.CountryCode}\n" + $"CountryName: {placemark.CountryName}\n" + $"FeatureName: {placemark.FeatureName}\n" + $"Locality: {placemark.Locality}\n" + $"PostalCode: {placemark.PostalCode}\n" + $"SubAdminArea: {placemark.SubAdminArea}\n" + $"SubLocality: {placemark.SubLocality}\n" + $"SubThoroughfare: {placemark.SubThoroughfare}\n" + $"Thoroughfare: {placemark.Thoroughfare}\n"; Debug.WriteLine(geocodeAddress); return(placemark); } else { return(null); } }
public static async Task GetCurrentLocation() { try { var request = new GeolocationRequest(GeolocationAccuracy.Best, TimeSpan.FromSeconds(2)); cts = new CancellationTokenSource(); location = await Geolocation.GetLocationAsync(request, cts.Token); if (location != null) { Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}"); } } catch (FeatureNotSupportedException fnsEx) { Serilog.Log.Information($"FeatureNotSupportedException: '{fnsEx}'"); } catch (FeatureNotEnabledException fneEx) { Serilog.Log.Information($"FeatureNotEnabledException: '{fneEx}'"); } catch (PermissionException pEx) { Serilog.Log.Information($"PermissionException: '{pEx}'"); } catch (Exception ex) { Serilog.Log.Information($"Unable to get location: '{ex}'"); } }
public static double CalculateTargetDirection(Essentials.Location location1, Essentials.Location location2) { if (location1 == null || location2 == null) { return(double.NaN); } var lat1 = location1.Latitude; //緯度 var lon1 = location1.Longitude; //経度 var lat2 = location2.Latitude; var lon2 = location2.Longitude; double y = Math.Cos(lon2 * Math.PI / 180) * Math.Sin(lat2 * Math.PI / 180 - lat1 * Math.PI / 180); double x = Math.Cos(lon1 * Math.PI / 180) * Math.Sin(lon2 * Math.PI / 180) - Math.Sin(lon1 * Math.PI / 180) * Math.Cos(lon2 * Math.PI / 180) * Math.Cos(lat2 * Math.PI / 180 - lat1 * Math.PI / 180); double dirE0 = 180 * Math.Atan2(y, x) / Math.PI; if (dirE0 < 0) { dirE0 = dirE0 + 360;//0~360に保つため } var direction = (dirE0 + 90) % 360;//北を基準にする。 return(direction); }
public Location(Xamarin.Essentials.Location loc) { this.Created = DateTime.Now; Carrier_Data_Point = User.carrierStatus; Latitude = loc.Latitude; Longitude = loc.Longitude; }
protected override void OnAppearing() { base.OnAppearing(); CustomMap.MyLocationEnabled = false; CustomMap.UiSettings.ZoomControlsEnabled = true; CustomMap.UiSettings.ZoomGesturesEnabled = true; CustomMap.UiSettings.MyLocationButtonEnabled = false; CustomMap.UiSettings.CompassEnabled = true; // TODO: Remove this line and activate GPS permissions //var location = await Xamarin.Essentials.Geolocation.GetLocationAsync(); var location = new Xamarin.Essentials.Location(20.697657, -103.372877); Pin currentLocationPin = new Pin() { Icon = BitmapDescriptorFactory.DefaultMarker(Color.Gray), Type = PinType.Place, Label = "Guadalajara, Mexico", Position = new Position(location.Latitude, location.Longitude), ZIndex = 5 }; CustomMap.Pins.Add(currentLocationPin); CustomMap.SelectedPin = currentLocationPin; if (initialLoadNeeded) { CustomMap.MoveToRegion( MapSpan.FromCenterAndRadius( new Position(location.Latitude, location.Longitude), Distance.FromMiles(0.30))); initialLoadNeeded = false; } }
public static async Task GetCurrentLocation() { location = new Xamarin.Essentials.Location(); try { var request = new GeolocationRequest(GeolocationAccuracy.Medium, new TimeSpan(0, 1, 0)); location = await Geolocation.GetLocationAsync(request); // here it is requesting the location from the mobile } catch (FeatureNotSupportedException fnsEx) { throw new FeatureNotSupportedException(); } catch (FeatureNotEnabledException fneEx) { throw new FeatureNotEnabledException(); } catch (PermissionException pEx) { throw new PermissionException(""); } catch (Exception e) { } }
public async Task UpdateLocationAsync(Xamarin.Essentials.Location position, Placemark address, string mood, string accessToken) { //This should call an azure service try { var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); var location = new LocationUpdate { Country = address?.CountryCode ?? string.Empty, Position = new Point(position.Longitude, position.Latitude), State = address?.AdminArea ?? string.Empty, Town = address?.Locality ?? string.Empty, Mood = mood ?? string.Empty }; var json = JsonConvert.SerializeObject(location); var content = new StringContent(json); var resp = await client.PostAsync(CommonConstants.FunctionUrl, content); var respBody = await resp.Content.ReadAsStringAsync(); } catch (Exception ex) { Crashes.TrackError(ex); System.Diagnostics.Debug.WriteLine($"ERROR: {ex.Message}"); throw; } }
private async void FindADrink(object sender, EventArgs e) { HttpClient httpClient = new HttpClient(); string baseUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="; string apiKey = "{API_KEY}"; var result = await httpClient.GetAsync(baseUrl + location.Latitude + "," + location.Longitude + "&radius=1000&type=bar&key=" + apiKey); var responseString = await result.Content.ReadAsStringAsync(); var responseObject = JsonConvert.DeserializeObject <RouteModel>(responseString); Random random = new Random(); var randomNumber = random.Next(0, responseObject.results.Count - 1); location = new Xamarin.Essentials.Location(responseObject.results[randomNumber].geometry.location.lat, responseObject.results[randomNumber].geometry.location.lng); Position position = new Position(location.Latitude, location.Longitude); barName = responseObject.results[randomNumber].name; MapSpan mapSpan = new MapSpan(position, 0.01, 0.01); Pin pin = new Pin { Label = barName, Address = responseObject.results[randomNumber].vicinity, Type = PinType.Place, Position = position }; CityMap.MoveToRegion(mapSpan); ResultLabel.Text = "YOUR NEXT DRINK IS AT: " + barName; CityMap.Pins.Clear(); CityMap.Pins.Add(pin); RouteButton.IsVisible = true; }
private static bool IsLocationChangedOrNull(Xamarin.Essentials.Location location, IEnumerable <Installation> i) { bool r = false; if (i == null || location == null) { return(true); } foreach (var e in i) { if ( Math.Round(e.Location.Latitude, 3) != Math.Round(location.Latitude, 3) && Math.Round(e.Location.Longitude, 3) != Math.Round(location.Longitude, 3) ) { r = true; break; } } ; return(r); }
public static GeoLocation.Helpers.ZoneEvent GetClosestContainingZoneEvent(Xamarin.Essentials.Location location) { var closestZoneEvent = new GeoLocation.Helpers.ZoneEvent() { ZoneName = DefaultZone.Name, ZoneColor = DefaultZone.Color, DistanceFromZoneInMeters = double.MaxValue, RelativeDistanceFromZone = 1.0 }; foreach (var zone in _zones) { var distance = GetDistanceInMeters(location, zone); if (IsLocationInsideZone(distance, zone)) { var relativeDistance = GetRelativeDistanceFromZoneNexus(distance, zone); if (relativeDistance < closestZoneEvent.RelativeDistanceFromZone) { closestZoneEvent.RelativeDistanceFromZone = relativeDistance; closestZoneEvent.DistanceFromZoneInMeters = distance; closestZoneEvent.ZoneName = zone.Name; closestZoneEvent.ZoneColor = GetZoneColorAccountingForDistance(zone, relativeDistance); } } } return(closestZoneEvent); }
private async Task <Xamarin.Essentials.Location> InternalGetLocation() { MasterDetail.statusPermissions = new Utils.StatusPermissions(); if (MasterDetail.statusPermissions.CheckConnection()) { Xamarin.Essentials.Location results = null; try { Xamarin.Essentials.GeolocationRequest geoRequest = new Xamarin.Essentials.GeolocationRequest(Xamarin.Essentials.GeolocationAccuracy.Medium); results = await Xamarin.Essentials.Geolocation.GetLocationAsync(geoRequest); } catch (Exception ex) { await this.DisplayAlert("Need location", "Active location sensor", "OK"); } return(results); } else { return(null); }; }
public ManifestModel GenerateManifest(Xamarin.Essentials.Location location) { return(_manifestManager.GetManifestDraft(eventTypeEnum: EventTypeEnum.MOVE_MANIFEST, manifestId: ManifestId, barcodeCollection: ConstantManager.Barcodes ?? new List <BarcodeModel>(), (long)location.Latitude, (long)location.Longitude, tags: Tags ?? new List <Tag>(), tagsStr: TagsStr, partnerModel: ConstantManager.Partner, newPallets: new List <NewPallet>(), batches: new List <NewBatch>(), closedBatches: new List <string>(), null, validationStatus: 2, contents: Contents)); }
public async Task <string> GetFoursquareCheckin(Xamarin.Essentials.Location cor) { HttpResponseMessage foursquareResponse = new HttpResponseMessage(); foursquareResponse = await client.GetAsync(" https://api.foursquare.com/v2/venues/search?client_id=VFAATN22EINFZGCHWKOQCUPOE0U3XIU4LL44DCQ2KWBA3JFV%20&client_secret=NL1XOSKNPJTNNQK3JPVVXHGS2AG4PM014AONQVSF2NGTX20V&ll=" + cor.Latitude + "," + cor.Longitude + "&&v=20190418"); if (foursquareResponse.IsSuccessStatusCode) { string content = await foursquareResponse.Content.ReadAsStringAsync(); FoursquareResponse fResponse = new FoursquareResponse(); fResponse = JsonConvert.DeserializeObject <FoursquareResponse>(content); List <Venue> venues; string CurrentVenue; venues = new List <Venue>(); if (fResponse.response.venues.Count != 0) { venues = fResponse.response.venues.OrderBy(o => o.location.distance).ToList(); CurrentVenue = venues[0].name; return(CurrentVenue); } } return(null); }
/// <summary> /// Finds the location of the device /// </summary> /// <returns>The location of the device as a Models.Location object</returns> private async Task <Models.Location> FindLocation() { Models.Location location = null; bool isLocationValid = true; GeolocationRequest request = null; Xamarin.Essentials.Location position = null; await Task.Run(async() => { await Device.InvokeOnMainThreadAsync(async() => { try { request = new GeolocationRequest(GeolocationAccuracy.Best); position = await Geolocation.GetLocationAsync(request); } catch (Exception) { Application.Current.MainPage.DisplayAlert("GPS ikke tændt", "Tænd GPS'en på din telefon", "Ok"); isLocationValid = false; } }); if (isLocationValid) { location = new Models.Location { EventRegId = selectedEvent.EventRegId, Longtitude = position.Longitude, Latitude = position.Latitude, LocationTime = DateTime.Now }; } }); return(location); }
public async Task <Xamarin.Essentials.Location> GetCurrentLocationCoordinates() { try { var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10)); _cts = new CancellationTokenSource(); Xamarin.Essentials.Location location = await Geolocation.GetLocationAsync(request, _cts.Token); return(location); } catch (FeatureNotSupportedException fnsEx) { // Handle not supported on device exception Debug.WriteLine(fnsEx); return(null); } catch (FeatureNotEnabledException fneEx) { // Handle not enabled on device exception Debug.WriteLine(fneEx); return(null); } catch (PermissionException pEx) { // Handle permission exception Debug.WriteLine(pEx); return(null); } catch (Exception ex) { // Unable to get location Debug.WriteLine(ex); return(null); } }
private async Task GetPermissionsDroid() { Plugin.Permissions.Abstractions.PermissionStatus status = PermissionStatus.Unknown; bool beforeNotLet = false; try { status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location); if (status != PermissionStatus.Granted) { if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location)) { beforeNotLet = true; } var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location); //Best practice to always check that the key exists if (results.ContainsKey(Permission.Location)) { status = results[Permission.Location]; } } if (status == PermissionStatus.Granted) { if (beforeNotLet) { ToolbarItems.Remove(requestLocationItem); (mainGrid.Children[0] as StackLayout).Children.Remove(lblLocError); IsBusy = true; LoadingFragment(); } Xamarin.Essentials.Location results = await InternalGetLocation(); App.Latitude = results.Latitude; App.Longitude = results.Longitude; ShowInfo(); } else if (status == PermissionStatus.Denied) { ReqLocationToolbarItem(); } else if (status == PermissionStatus.Unknown) { ReqLocationToolbarItem(); } else { await DisplayAlert("Error", "Error not expected", "OK"); } } catch (Exception ex) { await DisplayAlert("Error: " + ex, "55", "55"); } }
public override async Task Init() { //use this opportunity to grab the long/lat. var request = new GeolocationRequest(GeolocationAccuracy.Medium); var locationRealtime = await Geolocation.GetLocationAsync(request); location = (locationRealtime == null) ? await Geolocation.GetLastKnownLocationAsync() : locationRealtime; }
private string SendLocation(Xamarin.Essentials.Location location) { var apiclient = new ApiClient(); var trips = apiclient.GetTripsByClientId("2191f20f-aa85-4dda-82ef-e979ea5815fc"); return(apiclient.PostLocation(location) ? "ok" : "not ok"); }
private async void btnPostoProximo_Clicked(object sender, System.EventArgs e) { var location = new Xamarin.Essentials.Location(PostoProximo.Latitude, PostoProximo.Longitude); var options = new Xamarin.Essentials.MapLaunchOptions { NavigationMode = Xamarin.Essentials.NavigationMode.Driving }; await Xamarin.Essentials.Map.OpenAsync(location, options); }
public static double CalculateDistance(Essentials.Location location1, Essentials.Location location2) { if (location1 == null || location2 == null) { return(double.NaN); } return(Essentials.Location.CalculateDistance(location1, location2, Essentials.DistanceUnits.Kilometers)); }
async void OnStartup() { //var request = new GeolocationRequest(GeolocationAccuracy.Best); //location = await Geolocation.GetLocationAsync(request); location = new Xamarin.Essentials.Location(50.1118331, 8.6608024); Position position = new Position(location.Latitude, location.Longitude); MapSpan mapSpan = new MapSpan(position, 0.01, 0.01); CityMap.MoveToRegion(mapSpan); }