private void _geolocationService_LocationUpatedHandler(object sender, Xamarin.Essentials.Location e) { var position = new Position(e.Latitude, e.Longitude); MapSpan mapSpan = MapSpan.FromCenterAndRadius(position, Distance.FromKilometers(20)); Xamarin.Essentials.MainThread.InvokeOnMainThreadAsync(() => this.MoveToRegion(mapSpan)); }
async void LoadMap() { restraunts.Clear(); var client = new System.Net.Http.HttpClient(); client.BaseAddress = new Uri("https://www.tokyo-city.ru"); var restraunt = await RequestHelper.GetData <List <Restraunt> >(client, "data/app_addresses.php?version="); await Xamarin.Essentials.Geolocation.GetLocationAsync(); Xamarin.Essentials.Location loc = await Xamarin.Essentials.Geolocation.GetLastKnownLocationAsync(); Map.Children.Clear(); Position pos = new Position(loc.Latitude, loc.Longitude); Position posTest = new Position(59.868079, 30.332312); var span = MapSpan.FromCenterAndRadius(posTest, new Distance(1000)); span.WithZoom(3); map = new Map(span); //map.HasZoomEnabled = false; foreach (var rest in restraunt) { var restLoc = new Xamarin.Essentials.Location(rest.latitude, rest.longitude); rest.Distance = Xamarin.Essentials.Location.CalculateDistance(loc, restLoc, Xamarin.Essentials.DistanceUnits.Kilometers) * 1000; var pin = new Pin(); pin.Label = rest.name; pin.Position = new Position(rest.longitude, rest.latitude); map.Pins.Add(pin); restraunts.Add(rest); } map.MapType = MapType.Street; Map.Children.Add(map); }
public async static Task <Map> CreateMap(List <Restraunt> pins = null, bool test = false) { if (!test) { location = await Xamarin.Essentials.Geolocation.GetLastKnownLocationAsync(); } else { location = new Xamarin.Essentials.Location(59.874972, 30.27188); } MapSpan span = MapSpan.FromCenterAndRadius(new Position(location.Latitude, location.Longitude), Distance.FromKilometers(1)); span.WithZoom(3); var map = new Map(span); foreach (var pin in pins) { map.Pins.Add(new Pin() { Label = pin.address, Position = new Position(pin.longitude, pin.latitude) }); } return(map); }
protected async override void OnAppearing() { restraunts = new List <Restraunt>(); restraunts.Clear(); var client = new System.Net.Http.HttpClient(); client.BaseAddress = new Uri("https://www.tokyo-city.ru"); restraunts = await RequestHelper.GetData <List <Restraunt> >(client, "data/app_addresses.php?version="); await Xamarin.Essentials.Geolocation.GetLocationAsync(); Xamarin.Essentials.Location loc = await Xamarin.Essentials.Geolocation.GetLastKnownLocationAsync(); Map.Children.Clear(); base.OnAppearing(); Position pos = new Position(loc.Latitude, loc.Longitude); var span = MapSpan.FromCenterAndRadius(pos, new Distance(1000)); span.WithZoom(3); map = new Map(span); //map.HasZoomEnabled = false; foreach (var rest in restraunts) { var pin = new Pin(); pin.Label = rest.name; pin.Position = new Position(rest.longitude, rest.latitude); map.Pins.Add(pin); } map.MapType = MapType.Street; Map.Children.Add(map); }
public async Task <Xamarin.Essentials.Location> GetUserLocationFromAddress(string address) { //Example: address = "Microsoft Building 25 Redmond WA USA"; Xamarin.Essentials.Location location = null; try { var locations = await Xamarin.Essentials.Geocoding.GetLocationsAsync(address); location = locations?.FirstOrDefault(); if (location != null) { Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}"); } } catch (Xamarin.Essentials.FeatureNotSupportedException fnsEx) { // Feature not supported on device } catch (Exception ex) { // Handle exception that may have occurred in geocoding location = null; } return(location); }
public async Task <List <Bathroom> > Search(Xamarin.Essentials.Location location, String name) { List <Bathroom> resultList = new List <Bathroom>(); HttpResponseMessage response = null; var jsonResults = new StringBuilder(); var url = $"{PlacesApiBase}/nearbysearch/json?key={ApiKey}&location={location.Latitude},{location.Longitude}&radius={Radius}&name={name}"; response = (client.GetAsync(url)).Result; // Create a JSON object hierarchy from the results var result = await response.Content.ReadAsStringAsync(); var json = JsonConvert.DeserializeObject <SearchResponse>(result); try { foreach (var place in json?.results) { resultList.Add(new Bathroom() { Address = place.vicinity, PlaceName = place.name, Location = new Xamarin.Essentials.Location { Latitude = place.geometry.location.lat, Longitude = place.geometry.location.lng } }); } }catch (Exception e) { Console.WriteLine(e.ToString()); } return(resultList); }
public static Restraunt CalculateRestrauntDistance(Restraunt rest) { var restLoc = new Xamarin.Essentials.Location(rest.latitude, rest.longitude); rest.Distance = Xamarin.Essentials.Location.CalculateDistance(location, restLoc, Xamarin.Essentials.DistanceUnits.Kilometers) * 1000; return(rest); }
public static async Task <List <Place> > GetNearByPlacesAsync(Xamarin.Essentials.Location location, string Type) { RootObject rootObject = null; var client = new HttpClient(); CultureInfo In = new CultureInfo("en-IN"); //string latitude = "21.202305";//position.Latitude.ToString(In); //string longitude = "72.801437";//position.Longitude.ToString(In); //string search = "hospital"; //string Api_Key = "AIzaSyAm9ja67DHCyiQyzdbZow0d1XFQ8syh0LA"; // "AIzaSyDkp7eNYThyLFBoT3la-sPzg_W1sW4YtCE"; //"AIzaSyAm9ja67DHCyiQyzdbZow0d1XFQ8syh0LA"; //"AIzaSyB9aXHKKB_wIah3UQKybWzZak7RRoM1-FI"; //https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.2125959,72.8004598&radius=1500&type=restaurant&key=AIzaSyB9aXHKKB_wIah3UQKybWzZak7RRoM1-FI string restUrl = $"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + ChangeLocationformat(location.Latitude.ToString()) + "," + ChangeLocationformat(location.Longitude.ToString()) + "&radius=150000&type=" + Type.ToLower() + "&key=" + App.API_Key; var uri = new Uri(restUrl); var response = await client.GetAsync(uri); if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); rootObject = JsonConvert.DeserializeObject <RootObject>(content); } else { await Application.Current.MainPage.DisplayAlert("No web response", "Unable to retrieve information, please try again", "OK"); } return(rootObject.results); }
private async void LocateNow() { CurrentLocation = await GetLocation.LocateMobile(); var OpenStreetMapAPI = new OpenStreetMapAPI(); MyAdress = await OpenStreetMapAPI.GetCurrentAdressAsync(CurrentLocation); }
public ManifestModel GenerateManifest(IList <PalletModel> palletCollection, Xamarin.Essentials.Location location) { List <string> closedBatches = new List <string>(); List <NewPallet> newPallets = new List <NewPallet>(); NewPallet newPallet = null; List <TItem> palletItems = new List <TItem>(); TItem palletItem = null; foreach (var pallet in palletCollection) { foreach (var item in pallet.Barcode) { palletItem = new TItem { Barcode = item.Barcode, ScanDate = DateTimeOffset.UtcNow.Date, Icon = item.Icon, TagsStr = item.TagsStr }; if (item.Tags != null) { foreach (var tag in item.Tags) { palletItem.Tags.Add(tag); } } palletItems.Add(palletItem); } newPallet = new NewPallet { Barcode = pallet.ManifestId, BuildDate = DateTimeOffset.UtcNow.Date, StockLocation = ConstantManager.Partner.PartnerId, StockLocationId = ConstantManager.Partner.PartnerId, StockLocationName = ConstantManager.Partner.FullName, OwnerId = AppSettings.CompanyId, PalletId = pallet.BatchId, ReferenceKey = "", IsPalletze = IsPalletze }; foreach (var item in palletItems) { newPallet.PalletItems.Add(item); } newPallets.Add(newPallet); } List <NewBatch> newBatches = new List <NewBatch> { NewBatchModel, }; return(_manifestManager.GetManifestDraft(eventTypeEnum: EventTypeEnum.FILL_MANIFEST, manifestId: ManifestId, barcodeCollection: ConstantManager.Barcodes ?? new List <BarcodeModel>(), (long)location.Latitude, (long)location.Longitude, tags: new List <Tag>(), tagsStr: "", partnerModel: ConstantManager.Partner, newPallets: newPallets ?? new List <NewPallet>(), batches: newBatches, closedBatches: new List <string>(), null, validationStatus: 4, contents: SizeButtonTitle, size: SizeButtonTitle)); }
public void LocationUpdated(Xamarin.Essentials.Location updatedLocation) { Console.WriteLine("Got " + _locationListeners.Count + " location listener instances to inform about updated location."); _locationListeners.ForEach(listener => { Console.WriteLine("Informing " + listener.Key.GetType().Name + " about changed location."); listener.Key.LocationUpdated(updatedLocation); }); }
public MapPage() { InitializeComponent(); VM = BindingContext as MapPageViewModel; VM.MyMap = MyMap; this.CurrentLocation = VM.CurrentLocation; MyMap.PinClicked += VM.PinClicked; MyMap.Map = VM.Map; }
public static GpsLocation Convert(Xamarin.Essentials.Location loc) { GpsLocation converted = new GpsLocation(); converted.Altitude = loc.Altitude ?? 0; converted.Longitude = loc.Longitude; converted.Latitude = loc.Latitude; return(converted); }
/// <summary> /// Creates a new event args object /// </summary> /// <param name="position">position object</param> public GeolocationEventArgs(Xamarin.Essentials.Location position) { this.Point = new MapPoint( position.Latitude, position.Longitude, position.Altitude); this.Position = position; }
private async void MapMarker_Tapped(object sender, EventArgs e) { var marker = new Xamarin.Essentials.Location(this.cinemaInfo.X, this.cinemaInfo.Y); var options = new Xamarin.Essentials.MapLaunchOptions() { Name = this.cinemaInfo.Name, NavigationMode = Xamarin.Essentials.NavigationMode.None }; await Xamarin.Essentials.Map.OpenAsync(marker, options); }
private async void Timer_ElapsedAsync(object sender, ElapsedEventArgs e) { Xamarin.Essentials.Location location = await Xamarin.Essentials.Geolocation.GetLocationAsync(); if (location != null) { location = await Xamarin.Essentials.Geolocation.GetLastKnownLocationAsync(); } System.Net.WebRequest webRequest = System.Net.WebRequest.Create("http://kidstracking.azurewebsites.net/api/Parent/UpdateLocation"); }
public void LocationUpdated(Xamarin.Essentials.Location updatedLocation) { if (_registrationService.IsRegistered()) { SendPosition(updatedLocation); } else { Console.WriteLine("Got a location update without being registered to a server. Cannot send update!"); } }
/// <summary> /// Starts route navigation to given named point /// </summary> /// <param name="name">name of point on map to navigate to; may be empty</param> /// <param name="point">map point to navigate to</param> /// <returns>task to wait on</returns> private static async Task NavigateToPointAsync(string name, MapPoint point) { var navigateLocation = new Xamarin.Essentials.Location( latitude: point.Latitude, longitude: point.Longitude); var options = new Xamarin.Essentials.MapLaunchOptions { Name = name, NavigationMode = Xamarin.Essentials.NavigationMode.Driving, }; await Xamarin.Essentials.Map.OpenAsync(navigateLocation, options); }
private async void Button_Clicked(object sender, EventArgs e) { double latitude = 0, longitude = 0; // get the latitude and longitude somehow??? Xamarin.Essentials.Location location = await Xamarin.Essentials.Geolocation.GetLocationAsync(); latitude = location.Latitude; longitude = location.Longitude; LatitudeLabel.Text = latitude.ToString(); LongitudeLabel.Text = longitude.ToString(); }
public async void GetCurrentPosition() { try { CheckAndRequestLocationPermission(); currentPosition = await Xamarin.Essentials.Geolocation.GetLastKnownLocationAsync(); map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(currentPosition.Latitude, currentPosition.Longitude), Distance.FromMiles(3))); } catch (Exception ex) { // Unable to get location } }
/// <summary> /// Called when "Navigate here" menu item is selected /// </summary> /// <returns>task to wait on</returns> private async Task OnNavigateToLocationAsync() { var navigateLocation = new Xamarin.Essentials.Location( latitude: this.location.MapLocation.Latitude, longitude: this.location.MapLocation.Longitude); var options = new Xamarin.Essentials.MapLaunchOptions { Name = this.location.Name, NavigationMode = Xamarin.Essentials.NavigationMode.Driving, }; await Xamarin.Essentials.Map.OpenAsync(navigateLocation, options); }
public async Task <Xamarin.Essentials.Location> CurrentLocation() { var currentLocation = new Xamarin.Essentials.Location(); try { var locationManager = new LocationMonanager(); currentLocation = await locationManager.GetLocationCache(); return(currentLocation); } catch { throw; } }
public async static Task <Position> GetCurrentLocation() { Xamarin.Essentials.Location location = new Xamarin.Essentials.Location(); try { location = await Xamarin.Essentials.Geolocation.GetLastKnownLocationAsync(); return(new Position(location.Latitude, location.Longitude)); } catch (Xamarin.Essentials.FeatureNotSupportedException fnsEx) { throw new Exception(fnsEx.Message, fnsEx.InnerException); } catch (Xamarin.Essentials.FeatureNotEnabledException fneEx) { throw new Exception(fneEx.Message, fneEx.InnerException); } catch (Xamarin.Essentials.PermissionException pEx) { throw new Exception(pEx.Message, pEx.InnerException); } catch (Exception ex) { throw new Exception(ex.Message, ex.InnerException); } }
public void TestUnsetAltitude() { // set up var appSettings = new AppSettings(); var viewModel = new CurrentPositionDetailsViewModel(appSettings); // run var location = new Xamarin.Essentials.Location(48.137222, 11.575556); viewModel.OnPositionChanged( this, new Core.GeolocationEventArgs(location)); // check Assert.AreEqual(string.Empty, viewModel.Altitude, "accessing altitude must not crash"); Assert.AreEqual(string.Empty, viewModel.Accuracy, "accessing accuracy must not crash"); Assert.AreEqual(0, viewModel.HeadingInDegrees, "accessing heading must not crash"); }
public Boolean IsMockLocation(Xamarin.Essentials.Location location) //Copying ESSENTIAL VARIABLE TO ANDRIOD LOCATION VARIABLE { Boolean isMock = false; Context context = Android.App.Application.Context; Location alocation = new Location(""); alocation.Latitude = location.Latitude; alocation.Longitude = location.Longitude; //alocation.Accuracy = (float)location.Accuracy; //alocation.Altitude = (float)location.Altitude; //alocation.Speed = (float)location.Speed; //alocation.Time = location.Timestamp.Ticks; // if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.JellyBeanMr2) isMock = alocation.IsFromMockProvider; //using marshmallow so this part is executing // else // isMock =Settings.Secure.GetString(context.ContentResolver, Settings.Secure.AllowMockLocation).Equals("0"); //this is below jellybean return(isMock); }
private void OnLocationChanged(Xamarin.Essentials.Location updatedLocation) { Log.Debug(LoggerTag, "Got a location update from location provider. location: " + updatedLocation); var wakeLock = _powerManager.NewWakeLock(WakeLockFlags.Partial, WakeLockTag); wakeLock.Acquire(); Log.Debug(LoggerTag, "Acquired wake lock in android location service."); if (updatedLocation != null) { _locationChangeRegistry.LocationUpdated(updatedLocation); } else { Log.Info(LoggerTag, "Updated location was null!"); } wakeLock.Release(); Log.Debug(LoggerTag, "Released wake lock in android location service."); }
private void SendPosition(Xamarin.Essentials.Location location) { var positionsUrl = CreateGeoServerLocationUrl(); var positionObject = new JObject { { GeobrokerConstants.GeoPositionLatitudeProperty, location.Latitude }, { GeobrokerConstants.GeoPositionLongitudeProperty, location.Longitude }, { GeobrokerConstants.GeoPositionTimestampProperty, location.Timestamp.UtcDateTime.ToString("s") + "Z" }, { GeobrokerConstants.GeoPositionAccuracyProperty, location.Accuracy }, { GeobrokerConstants.GeoPositionHeadingProperty, location.Course }, { GeobrokerConstants.GeoPositionSpeedProperty, location.Speed } }; new Task(async() => { var locationSendingFinalizer = BeforeLocationSending(); var positionObjectJsonString = positionObject.ToString(Formatting.None); Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ": Sending Data to Server: " + positionObjectJsonString); var postPositionAsyncTask = _positionHttpClient.PostAsync( positionsUrl, new StringContent(positionObjectJsonString, Encoding.UTF8, JsonContentType)); await postPositionAsyncTask.ContinueWith(postPositionResponse => { try { var responseString = postPositionResponse.Result.Content.ReadAsStringAsync().Result; var statusString = postPositionResponse.Result.StatusCode.ToString(); Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ": Response from Server: Status: " + statusString + ", response: " + responseString); } catch (Exception e) { Console.WriteLine("Failed to get response from server!"); Console.WriteLine(e.ToString()); } locationSendingFinalizer(); }); }).RunSynchronously(_taskScheduler); }
/// <summary> /// Получение местоположение и выполнение какого-то действия. /// </summary> private async void GetLocation(Func <Task> action) { try { var request = new Xamarin.Essentials.GeolocationRequest(Xamarin.Essentials.GeolocationAccuracy.Medium); location = await Xamarin.Essentials.Geolocation.GetLocationAsync(request); if (location != null) { await action(); } else { indicator.IsRunning = false; } } catch (Xamarin.Essentials.FeatureNotSupportedException fnsEx) { // Handle not supported on device exception await DisplayAlert("Ошибка", "Не удается определить местоположение", "OK"); } catch (Xamarin.Essentials.FeatureNotEnabledException fneEx) { // Handle not enabled on device exception await DisplayAlert("Ошибка", "Не удается определить местоположение", "OK"); } catch (Xamarin.Essentials.PermissionException pEx) { // Handle permission exception await DisplayAlert("Ошибка", "Не удается определить местоположение", "OK"); } catch (Exception ex) { // Unable to get location await DisplayAlert("Ошибка", "Не удается определить местоположение " + ex.Message, "OK"); } }
public async static Task <Position> GetLocationFromAddress(string address) { try { IEnumerable <Xamarin.Essentials.Location> locations = await Xamarin.Essentials.Geocoding.GetLocationsAsync(address); Xamarin.Essentials.Location location = locations?.FirstOrDefault(); if (location != null) { return(new Position(location.Latitude, location.Longitude)); } else { return(new Position()); //throw new Exception("Impossible to get address results. 404"); } } catch (Xamarin.Essentials.FeatureNotSupportedException fnsEx) { // Feature not supported on device return(new Position()); //throw new Xamarin.Essentials.FeatureNotSupportedException(fnsEx.Message, fnsEx.InnerException); } catch (Exception ex) { // Handle exception that may have occurred in geocoding return(new Position()); //throw new Exception(ex.Message, ex.InnerException); } }
public void TestLocationUpdate() { // set up var appSettings = new AppSettings { CoordinateDisplayFormat = CoordinateDisplayFormat.Format_dd_mm_sss }; var viewModel = new CurrentPositionDetailsViewModel(appSettings); // run var location = new Xamarin.Essentials.Location(48.137222, 11.575556, 512) { AltitudeReferenceSystem = Xamarin.Essentials.AltitudeReferenceSystem.Geoid, Accuracy = 42, Course = 64.2, Speed = 4.1, Timestamp = new DateTimeOffset(2022, 4, 19, 7, 44, 0, TimeSpan.FromHours(2)), IsFromMockProvider = true, }; viewModel.OnPositionChanged( this, new Core.GeolocationEventArgs(location)); // check Assert.AreEqual("11° 34' 32\"", viewModel.Longitude, "longitude text must be correct"); Assert.AreEqual("48° 8' 13\"", viewModel.Latitude, "latitude text must be correct"); Assert.AreEqual("512", viewModel.Altitude, "altitude text must be correct"); Assert.AreEqual("42", viewModel.Accuracy, "accuracy text must be correct"); Assert.AreEqual(Color.FromHex("#E0E000"), viewModel.PositionAccuracyColor, "accuracy color must be black"); Assert.IsTrue(viewModel.LastPositionFix.Length > 0, "last position fix text must contain text"); Assert.AreEqual(14, viewModel.SpeedInKmh, "speed value must be correct"); Assert.IsTrue(viewModel.IsHeadingAvail, "initially heading is not available"); Assert.AreEqual(64, viewModel.HeadingInDegrees, "heading value must be correct"); Assert.IsTrue(viewModel.IsSunriseSunsetAvail, "sunrise/sunset must not be available"); Assert.AreEqual("6:09:21", viewModel.SunriseTime, "sunrise time text must be correct"); Assert.AreEqual("20:17:45", viewModel.SunsetTime, "sunset time text must be correct"); }