async Task <MapSpan> GeocoderPueblo() { var nombrePueblo = txtNombre.Text; Geocoder geoCoder = new Geocoder(); string address = nombrePueblo + ", Andalucía, Spain"; IEnumerable <Position> approximateLocations = await geoCoder.GetPositionsForAddressAsync(address); Position position = approximateLocations.FirstOrDefault(); if (position == new Position(0, 0)) { string direccion = nombrePueblo + ", Andalucía"; IEnumerable <Position> direccionesAproximadas = await geoCoder.GetPositionsForAddressAsync(direccion); Position posicion = direccionesAproximadas.FirstOrDefault(); if (posicion == new Position(0, 0) || Connectivity.NetworkAccess != NetworkAccess.Internet) { stackMapa.IsVisible = false; stackMapa.IsEnabled = false; //Como hay que devolver un MapSpan, devuelvo la posición de Almería return(new MapSpan(new Position(36.834047, -2.4637136), 0.01, 0.01)); } else { return(new MapSpan(posicion, 0.01, 0.01)); } } else { return(new MapSpan(position, 0.01, 0.01)); } }
public async Task <Position> GetPosition() { if (!HasAddress) { return(new Position(0, 0)); } IsBusy = true; Position p; p = (await _Geocoder.GetPositionsForAddressAsync(Acquaintance.AddressString)).FirstOrDefault(); // The Android geocoder (the underlying implementation in Android itself) fails with some addresses unless they're rounded to the hundreds. // So, this deals with that edge case. if (p.Latitude == 0 && p.Longitude == 0 && AddressBeginsWithNumber(Acquaintance.AddressString) && Device.OS == TargetPlatform.Android) { var roundedAddress = GetAddressWithRoundedStreetNumber(Acquaintance.AddressString); p = (await _Geocoder.GetPositionsForAddressAsync(roundedAddress)).FirstOrDefault(); } IsBusy = false; return(p); }
//Preenche o mapa com pins dos registros no banco de dados public async void OnAppearing() { try { this.IsBusy = true; _listaCeps.Clear(); var listaBD = _cepRepository.GetAllCepsData(); if (listaBD.Count > 0) { listaBD = listaBD.OrderByDescending(x => x.Id).ToList(); _listaCeps.AddRange(listaBD); Geocoder posicoes = new Geocoder(); foreach (CepModel c in _listaCeps) { var cepPosicoes = (await posicoes.GetPositionsForAddressAsync(c.Cep)).ToList(); if (cepPosicoes.Count != 0) { var pinCep = new Pin { Type = PinType.Place, Label = c.Cep, Position = new Position(cepPosicoes[0].Latitude, cepPosicoes[0].Longitude) }; _mapa.Pins.Add(pinCep); } } //Centraliza o mapa para o último Cep gravado var ultimoCep = (await posicoes.GetPositionsForAddressAsync(_listaCeps[0].Cep)).ToList(); _mapa.MoveToRegion(MapSpan.FromCenterAndRadius( new Position(ultimoCep[0].Latitude, ultimoCep[0].Longitude), Distance.FromKilometers(3.0))); } } catch (Exception) { throw; } finally { this.IsBusy = false; } }
private async Task LocalizarNoMapa(string param) { Geocoder geocoder = new Geocoder(); Task <IEnumerable <Position> > resultado = geocoder.GetPositionsForAddressAsync(param); IEnumerable <Position> posicoes = await resultado; foreach (Position item in posicoes) { meuMapa.MoveToRegion(MapSpan.FromCenterAndRadius(item, Distance.FromMiles(2.0))); meuMapa.Pins.Clear(); var pin = new Pin { Type = PinType.Generic, Position = item, Label = "Localização", Address = txtPesquisa.Text }; meuMapa.Pins.Add(pin); break; } }
protected async void ButtonShowMap_Clicked(object sender, EventArgs e) { Geocoder geoCoder = new Geocoder(); StringBuilder customerAddress = new StringBuilder(); Pin pin = new Pin(); customerAddress.Append(_vm.SalesOrder.ShipToAddress1); customerAddress.Append(", "); customerAddress.Append(_vm.SalesOrder.ShipToCity); customerAddress.Append(", "); customerAddress.Append(_vm.SalesOrder.ShipToState); customerAddress.Append(" "); customerAddress.Append(_vm.SalesOrder.ShipToZipCode); string addr = customerAddress.ToString(); try { var location = await geoCoder.GetPositionsForAddressAsync(addr); List <Position> approximateLocation = location.ToList(); pin.Position = approximateLocation[0]; pin.Label = _vm.Customer.CustomerName; pin.Address = customerAddress.ToString(); await Navigation.PushAsync(new CustomerMapPage(pin)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); await DisplayAlert("Invalid Location", "Address cannot be mapped.", "OK"); return; } }
/// <summary> /// Get address geocode position /// </summary> /// <param name="fullAddress"></param> /// <returns></returns> public static async Task <Position?> GetPositionAsync(this string fullAddress) { try { if (string.IsNullOrEmpty(fullAddress)) { return(null); } var current = Connectivity.NetworkAccess; if (current == NetworkAccess.None) { await DependencyService.Get <IUserDialogs>().DisplayAlertAsync("Geocode Address", "No internet connectivity is available now, check airplain mode if apply your addres is not be setted to geocode.", "Ok"); return(null); } Geocoder geoCoder = new Geocoder(); IEnumerable <Position> approximateLocations = await geoCoder.GetPositionsForAddressAsync(fullAddress); Position position = approximateLocations.FirstOrDefault(); return(position); } catch (Exception e) { Debug.WriteLine(e); return(null); } }
public async Task <double> getLocation(string address, string type) { Position p = new Position(); var _address = address; Geocoder geoCoder = new Geocoder(); IEnumerable <Position> result = await geoCoder.GetPositionsForAddressAsync(_address); if (result != null) { foreach (Position pos in result) { System.Diagnostics.Debug.WriteLine("Lat: {0}, Lng: {1}", pos.Latitude, pos.Longitude); p = pos; if (type == "longditude") { return(pos.Longitude); } else { return(pos.Latitude); } } } return(0); }
async Task SearchLocation() { if (String.IsNullOrWhiteSpace(Address)) { return; } try { var possibleAddresses = await geocoder.GetPositionsForAddressAsync(Address); if (possibleAddresses != null && possibleAddresses.Any()) { position = possibleAddresses.FirstOrDefault(); foreach (var item in possibleAddresses) { Debug.WriteLine($"Lat:{item.Latitude}, Long:{item.Longitude}"); } } } catch (Exception) { return; } }
private async Task ExecuteGetLocationsCommand() { if (IsBusy || !(await LoginAsync())) { return; } //if (ForceSync) //Settings.LastSync = DateTime.Now.AddDays (-30); IsBusy = true; GetLocationsCommand.ChangeCanExecute(); try{ Locations.Clear(); //var stores = new List<Store>(); Geocoder geoCoder = new Geocoder(); var locations = await azureService.GetLocations(); foreach (var location in locations) { if (string.IsNullOrWhiteSpace(location.Image)) { location.Image = "http://refractored.com/images/wc_small.jpg"; } //added by aditmer on 2/14/18 because GeoCoding fails when offline if (CrossConnectivity.Current.IsConnected) { //geocode the street address if the data doesn't contain coordinates if (location.Latitude == 0 && location.Longitude == 0) { var address = location.StreetAddress + ", " + location.City + ", " + location.State + ", " + location.ZipCode; var approximateLocations = await geoCoder.GetPositionsForAddressAsync(address); Position pos = approximateLocations.FirstOrDefault(); location.Latitude = pos.Latitude; location.Longitude = pos.Longitude; } } Locations.Add(location); } Sort(); } catch (Exception ex) { _page.DisplayAlert("Uh Oh :(", "Unable to gather locations.", "OK"); Analytics.TrackEvent("Exception", new Dictionary <string, string> { { "Message", ex.Message }, { "StackTrace", ex.ToString() } }); } finally { IsBusy = false; GetLocationsCommand.ChangeCanExecute(); } }
public async void GetPosition(string pinLabel) { Geocoder gcoder = new Geocoder(); double x = 0.0, y = 0.0; try { var posList = await gcoder.GetPositionsForAddressAsync(address); foreach (var p in posList) { x = p.Latitude; y = p.Longitude; } map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(x, y), Distance.FromMiles(2.0))); pin = new Pin { Type = PinType.Place, Position = new Position(x, y), Label = pinLabel, Address = address }; pin.Clicked += OpenMaps; map.Pins.Add(pin); } catch (Exception ex) { await DisplayAlert("Oops", ex.ToString(), "Close"); } }
async void getPosition(string address) { try { Geocoder gc = new Geocoder(); IEnumerable <Position> possibleAddresses = await gc.GetPositionsForAddressAsync(address); foreach (var result in possibleAddresses) { if (check == 0) { AddDeliveryAddressPage.Latitude = result.Latitude.ToString(); AddDeliveryAddressPage.Longitude = result.Longitude.ToString(); } else { EditDeliveryAddressPage.Latitude = result.Latitude.ToString(); EditDeliveryAddressPage.Longitude = result.Longitude.ToString(); } break; } } catch { } }
/// <summary> /// Method populate Pin to Map /// </summary> /// <param name="address"></param> /// <param name="name"></param> /// <param name="description"></param> /// <param name="raiting"></param> private async void AddPinToMap(string address, string name, string description, string raiting) { Position pinPosition = new Position(); var pinPositions = await geocoder.GetPositionsForAddressAsync(address); if (pinPositions != null && pinPositions.Any()) { pinPosition = pinPositions.First(); } await Task.Delay(1000); // workaround for #30 [Android]Map.Pins.Add doesn't work when page OnAppearing var pin = new Pin { Address = address, Position = pinPosition, Icon = BitmapDescriptorFactory.FromView(new BindingPinView("")), Label = $"{name}, {description}, {raiting}" }; map.Pins.Add(pin); map.MoveToRegion(MapSpan.FromCenterAndRadius(pinPosition, Distance.FromKilometers(1))); }
public async Task <IEnumerable <Position> > FindAddress(string addressQuery) { var geoCoder = new Geocoder(); var locations = await geoCoder.GetPositionsForAddressAsync(addressQuery); return(locations); }
//Sets location based on string entry private async void Set_Location() { Set_.IsEnabled = false; var locator = new Geocoder(); IEnumerable <Position> pos = await locator.GetPositionsForAddressAsync(SetLocation.Text); ((Appointment)BindingContext).Address = SetLocation.Text; if (pos != null) { ((Appointment)BindingContext).Longitude = pos.First().Longitude; ((Appointment)BindingContext).Latitude = pos.First().Latitude; DegMinSecConversion(); var answer = await DisplayAlert("Would you like to view location on map?", null, "Yes", "No"); if (answer) { await Navigation.PushAsync(new SamplePage(((Appointment)BindingContext).Longitude, ((Appointment)BindingContext).Latitude, (Appointment)BindingContext)); } } else { await DisplayAlert("Error", SetLocation.Text + "could not be found", "Ok"); } Set_.IsEnabled = true; }
public GeocoderPage() { geoCoder = new Geocoder(); var b1 = new Button { Text = "反定位 '25.0436439, 121.525664'" }; b1.Clicked += async (sender, e) => { var fortMasonPosition = new Position(25.0436439, 121.525664); var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(fortMasonPosition); foreach (var a in possibleAddresses) { l.Text += a + "\n"; } }; var b2 = new Button { Text = "定位 '多奇數位創意有限公司'" }; b2.Clicked += async (sender, e) => { var xamarinAddress = "多奇數位創意有限公司"; var approximateLocation = await geoCoder.GetPositionsForAddressAsync(xamarinAddress); foreach (var p in approximateLocation) { l.Text += p.Latitude + ", " + p.Longitude + "\n"; } }; Content = new StackLayout { Padding = new Thickness(0, 20, 0, 0), Children = { b2, b1, l } }; }
async Task GetCoordinates(Geocoder g) { try { var locations = await g.GetPositionsForAddressAsync("77009"); Position location = locations.FirstOrDefault(); if (location == null) { nowWeatherLabel.StringValue = "unable"; } else { Task forecast = GetForecast((double)location.Longitude, (double)location.Latitude); } } catch (Exception e) { nowWeatherLabel.StringValue = e + "unable"; var alert = new NSAlert() { AlertStyle = NSAlertStyle.Critical, InformativeText = e.ToString(), MessageText = "Save Document", }; alert.RunModal(); } }
private async void OnBtnPesquisarClicked(object sender, EventArgs e) { if (String.IsNullOrEmpty(EntryCep.Text)) { await DisplayAlert("Erro", "O campo do cep deve ser preenchido", "Ok"); return; } Geocoder geocoder = new Geocoder(); var localizacoes = await geocoder.GetPositionsForAddressAsync(EntryCep.Text); if (localizacoes.Any()) { var enderecos = await geocoder.GetAddressesForPositionAsync(new Position(localizacoes.FirstOrDefault().Latitude, localizacoes.FirstOrDefault().Longitude)); var endereco = enderecos.FirstOrDefault(); EnderecoCompleto = endereco; LabelEndereco.Text = endereco.Substring(0, endereco.IndexOf('-')); MapLocalizacao.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(localizacoes.FirstOrDefault().Latitude, localizacoes.FirstOrDefault().Longitude), Distance.FromKilometers(1))); MapLocalizacao.Pins.RemoveAt(0); var pinCarro = new Pin() { Position = new Position(localizacoes.FirstOrDefault().Latitude, localizacoes.FirstOrDefault().Longitude), Label = "Seu carro" }; MapLocalizacao.Pins.Add(pinCarro); } }
private async void SearchBar_SearchButtonPressed(object sender, EventArgs e) { var positions = await geocoder.GetPositionsForAddressAsync(searchBar.Text); var position = positions.FirstOrDefault(); if (position != null) { map.MoveToRegion( MapSpan.FromCenterAndRadius( position, Distance.FromMiles(0.2))); var addresses = await geocoder.GetAddressesForPositionAsync(position); var address = addresses.FirstOrDefault(); if (address != null) { map.Pins.Clear(); var pin = new Pin { Type = PinType.Place, Position = position, Label = searchBar.Text, Address = address.Replace("\n", "") }; map.Pins.Add(pin); } } }
private async Task <Location> GetTargetLocation() { if (currentJob == null) { arrivalRadius = DEFAULT_ARRIVAL_RADIUS; targetLocation = new Location(); } else if (currentJob.GpsLatitude != 0.0 && currentJob.GpsLongitude != 0.0) { arrivalRadius = currentJob.GpsRadius == 0.0 ? DEFAULT_ARRIVAL_RADIUS : currentJob.GpsRadius / FEET_PER_MILE; targetLocation = new Location(currentJob.GpsLatitude, currentJob.GpsLongitude); } else { string targetAddress = (currentJob.Street1 ?? "") + " " + (currentJob.Street2 ?? "") + " " + (currentJob.City ?? "") + " " + (currentJob.State ?? "") + " " + (currentJob.ZipCode ?? ""); var targetPositions = await geocoder.GetPositionsForAddressAsync(targetAddress).ConfigureAwait(false); if (targetPositions != null && targetPositions.Count() >= 1) { arrivalRadius = currentJob.GpsRadius == 0.0 ? DEFAULT_GEOCODED_ARRIVAL_RADIUS : currentJob.GpsRadius / FEET_PER_MILE; var pos = targetPositions.First(); targetLocation = new Location(pos.Latitude, pos.Longitude); } } return(targetLocation); }
async void TxtLocation_Completed(object sender, EventArgs e) { var address = txtLocation.Text; LocationName = address; var approximateLocations = await geoCoder.GetPositionsForAddressAsync(address); foreach (var position in approximateLocations) { //geocodedOutputLabel.Text += position.Latitude + ", " + position.Longitude + "\n"; Debug.WriteLine("Position Status: {0}, {1}", position.Latitude, position.Longitude); pickupPosition = new Position(position.Latitude, position.Longitude); map.MoveToRegion(MapSpan.FromCenterAndRadius(pickupPosition, Distance.FromMiles(3))); if (pin != null) { map.Pins.Remove(pin); } pin = new Pin { Type = PinType.Place, Position = position , Label = address //,Address = "custom detail info" }; map.Pins.Add(pin); } }
public async void getPosition(string address) { var loadingDialog = await MaterialDialog.Instance.LoadingDialogAsync(message : "Please Wait.."); try { Geocoder gc = new Geocoder(); IEnumerable <Position> possibleAddresses = await gc.GetPositionsForAddressAsync(address); foreach (var result in possibleAddresses) { await loadingDialog.DismissAsync(); HomePage.Lat = result.Latitude; HomePage.Lng = result.Longitude; await navigation.PopModalAsync(); break; } } catch (Exception ex) { } }
async void CrearMapa() { Loading2(true); var pueblo = await FirebaseHelper.ObtenerPueblo(Ruta.IdPueblo); if (string.IsNullOrEmpty(pueblo.Nombre)) { UserDialogs.Instance.Alert("Advertencia", Constantes.TitlePuebloRequired + " A continuación guarde el nombre antes de empezar a crear contenido.", "OK"); return; } Geocoder geoCoder = new Geocoder(); string address = pueblo.Nombre + ", Andalucía, Spain"; IEnumerable <Position> approximateLocations = await geoCoder.GetPositionsForAddressAsync(address); Position position = approximateLocations.FirstOrDefault(); MapSpan mapSpan = MapSpan.FromCenterAndRadius(position, Distance.FromKilometers(0.5)); Map = new Map(mapSpan) { WidthRequest = -1, HeightRequest = 300, HasScrollEnabled = true, HasZoomEnabled = true, IsShowingUser = true }; PonerRuta(); PonerPins(); stackMapa.Children.Add(Map); Loading2(false); }
async void SearchForAddress(object sender, EventArgs e) { var searchAddress = (SearchBar)sender; var addressQuery = searchAddress.Text; searchAddress.Text = ""; searchAddress.Unfocus(); var positions = (await _geocoder.GetPositionsForAddressAsync(addressQuery)).ToList(); if (!positions.Any()) { return; } var position = positions.First(); Map.MoveToRegion(MapSpan.FromCenterAndRadius(position, Distance.FromMeters(4000))); Map.Pins.Add(new Pin { Label = addressQuery, Position = position, Address = addressQuery }); }
private async void GetLocations(List <Residence> residences) { var geoCoder = new Geocoder( ); foreach (var residence in residences) { var position = (await geoCoder.GetPositionsForAddressAsync(residence.Address)).ToList( )[0]; var pin = new CustomPin { Pin = new Pin { Type = PinType.Place, Position = position, Label = residence.Address }, Residence = residence }; //pin.Clicked += delegate { // Navigation.PushAsync ( new SelectedResidencePage ( residence ), true ); //}; map.CustomPins.Add(pin); map.Pins.Add(pin.Pin); Debug.WriteLine("Latitude: {0} Longitude: {1}", position.Latitude, position.Longitude); } var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 50; var devicePosition = await locator.GetPositionAsync(2000); map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(devicePosition.Latitude, devicePosition.Longitude), Distance.FromKilometers(2.0))); }
async void OnReverseGeocodeButtonClicked(object sender, EventArgs e) { var latlong2 = "16.43307340526658, 102.8255601788635"; map.MapClicked += (s, arg) => { var x = arg.Position.Latitude; var y = arg.Position.Longitude; latlong2 = x + "," + y; }; if (!string.IsNullOrWhiteSpace(latlong2)) { string[] coordinates = latlong2.Split(','); double? latitude = Convert.ToDouble(coordinates[0]); double? longitude = Convert.ToDouble(coordinates[1]); if (latitude != null && longitude != null) { Position position = new Position(latitude.Value, longitude.Value); IEnumerable <string> possibleAddresses = await geoCoder.GetAddressesForPositionAsync(position); IEnumerable <Position> possibleAddresses2 = await geoCoder.GetPositionsForAddressAsync(possibleAddresses.FirstOrDefault()); //Geocoder; string address = possibleAddresses.FirstOrDefault(); reverseGeocodedOutputLabel.Text = address; } } }
private async void OnSearch(object sender, EventArgs e) { var theEnteredAdress = searchQueryEntry.Text; Geocoder gc = new Geocoder(); IEnumerable <Position> result = await gc.GetPositionsForAddressAsync(theEnteredAdress); foreach (Position pos in result) { System.Diagnostics.Debug.WriteLine("Lat: {0}, Lng: {1}", pos.Latitude, pos.Longitude); gmapsView.MoveToRegion( MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(pos.Latitude, pos.Longitude), Distance.FromMiles(1))); pin = new Pin { Type = PinType.Place, Position = new Position(pos.Latitude, pos.Longitude), Address = "ElixirCT", Label = "ShopRConnect" }; gmapsView.Pins.Add(pin); } }
public async void CrearMapa() { var nombrePueblo = Pueblo.Nombre; Geocoder geoCoder = new Geocoder(); string address = nombrePueblo + ", Andalucía, Spain"; IEnumerable <Position> approximateLocations = await geoCoder.GetPositionsForAddressAsync(address); Position position = approximateLocations.FirstOrDefault(); MapSpan mapSpan = new MapSpan(position, 0.01, 0.01); map = new Map(mapSpan) { WidthRequest = -1, HeightRequest = 300, HasScrollEnabled = true, HasZoomEnabled = true }; Pin pin = new Pin { Label = nombrePueblo, Type = PinType.Place, Position = position }; map.Pins.Add(pin); stackMapa.Children.Add(map); }
public async Task <GeocodeLocationResponse> FindLocationAsync(GeocodeLocationRequest request) { var result = await _geoCoder.GetPositionsForAddressAsync(request.Address); return(new GeocodeLocationResponse(result.Select(pos => new GeoLocation { Latitude = pos.Latitude, Longitude = pos.Longitude, Description = request.Address }).ToList())); }
public async void PositionsForAddress() { Geocoder.GetPositionsForAddressAsyncFunc = GetPositionsForAddressAsyncFunc; var geocoder = new Geocoder(); var result = await geocoder.GetPositionsForAddressAsync("quux"); Assert.AreEqual(new Position [] { new Position(1, 2), new Position(3, 4) }, result); }
protected override async void OnAppearing() { DetailLayout.BindingContext = _e; var address = _e.MeetingLocation; var approximateLocations = await geoCoder.GetPositionsForAddressAsync(address); var position = approximateLocations.FirstOrDefault(); var pin = new Pin { Type = PinType.Place, Position = position, Label = "Meeting Point", Address = _e.MeetingLocation }; MeetupLocationMap.Pins.Add(pin); MeetupLocationMap.MoveToRegion( MapSpan.FromCenterAndRadius( position, Distance.FromKilometers(1))); AttendingButton.Text = "I'm Attending"; if (_e.Image == null) { BikesquatButton.IsVisible = true; BikeSquatImage.Source = ImageSource.FromFile("KangarooP.JPG"); BikeSquatImage.WidthRequest = App.ScreenSize.Width; } else { //BikesquatButton.IsVisible = false; BikeSquatImage.Source = _e.Image.ImageSource; } foreach (Event.rideType r in Enum.GetValues(typeof(Event.rideType))) { if (_e.RideType == r) { //RideTypeLabel.Text = r.ToString(); } } foreach (Event.elevation e in Enum.GetValues(typeof(Event.elevation))) { if (_e.Elevation == e) { //ElevationTypeLabel.Text = e.ToString(); } } base.OnAppearing(); }