public async Task <Coordinates> GetCoordinatesAsync(string addressQuery) { var result = await _bingMapsGeocoder.GeocodeAsync(addressQuery); var bestMatch = result.FirstOrDefault(); return(MapResultToCoordinates(bestMatch)); }
public async Task <ActionResult <Party> > PostParty(Party party) { // Create a new geocoder var geocoder = new BingMapsGeocoder(BING_MAPS_KEY); // Request this address to be geocoded. var geocodedAddresses = await geocoder.GeocodeAsync(party.Address); // ... and pick out the best address sorted by the confidence level var bestGeocodedAddress = geocodedAddresses.OrderBy(address => address.Confidence).LastOrDefault(); // If we have a best geocoded address, use the latitude and longitude from that result if (bestGeocodedAddress != null) { party.Location = new Point(bestGeocodedAddress.Coordinates.Latitude, bestGeocodedAddress.Coordinates.Longitude) { SRID = 4326 }; } party.UserId = GetCurrentUserId(); _context.Parties.Add(party); await _context.SaveChangesAsync(); return(CreatedAtAction("GetParty", new { id = party.Id }, party)); }
private async Task <MapPoint> AddLongLatAsync(string apartmentAddress) { MapPoint point; // Getting the location of the address try { IGeocoder geocoder = new BingMapsGeocoder("AgnX4fQVaxUmGPZMrIAWH2sVbJ34rY2GR-qjkOWUCJprHGbHX5iMfjlq-xOIYelB"); IEnumerable <Address> addresses = await geocoder.GeocodeAsync(apartmentAddress); point = new MapPoint { Latitude = addresses.First().Coordinates.Latitude, Longitude = addresses.First().Coordinates.Longitude }; } catch (Exception ex) { Console.WriteLine("----------------------------------------------"); Console.WriteLine(ex); Console.WriteLine("----------------------------------------------"); point = new MapPoint { Latitude = 32.1637206, Longitude = 34.8647352 }; } return(point); }
public async Task <ActionResult <Restaurant> > PostRestaurant(Restaurant restaurant) { // Create a new geocoder var geocoder = new BingMapsGeocoder(BING_MAPS_KEY); // Request this address to be geocoded. var geocodedAddresses = await geocoder.GeocodeAsync(restaurant.Address); // ... and pick out the best address sorted by the confidence level var bestGeocodedAddress = geocodedAddresses.OrderBy(address => address.Confidence).LastOrDefault(); // If we have a best geocoded address, use the latitude and longitude from that result if (bestGeocodedAddress != null) { restaurant.Latitude = bestGeocodedAddress.Coordinates.Latitude; restaurant.Longitude = bestGeocodedAddress.Coordinates.Longitude; } // Set the UserID to the current user id, this overrides anything the user specifies. restaurant.UserId = GetCurrentUserId(); // Indicate to the database context we want to add this new record _context.Restaurants.Add(restaurant); await _context.SaveChangesAsync(); // Return a response that indicates the object was created (status code `201`) and some additional // headers with details of the newly created object. return(CreatedAtAction("GetRestaurant", new { id = restaurant.Id }, restaurant)); }
public async Task CanParseAddressTypes(string address, EntityType type) { var result = await geoCoder.GeocodeAsync(address); BingAddress[] addresses = result.ToArray(); Assert.Equal(type, addresses[0].Type); }
private async Task <IEnumerable <BingAddress> > GetBingAddresses(string location) { BingMapsGeocoder geocoder = new BingMapsGeocoder(SystemResources.BING_API_KEY); var addresses = await geocoder.GeocodeAsync(location); return(addresses); }
public async void addPushPin(object sender, RoutedEventArgs e) { if (!validFields()) { MessageBox.Show("Please fill all text fields"); return; } Service newService = null; Pushpin pushPin = new Pushpin(); Geocoding.IGeocoder geocoder = new BingMapsGeocoder("vuOU7tN47KBhly1BAyhi~SKpEroFcVqMGYOJVSj-2HA~AhGXS-dV_H6Ofvn920LLMyvxfUUaLfjpZTD54fSc3WO-qRE7x6225O22AP_0XjDn"); IEnumerable <Address> addresses = await geocoder.GeocodeAsync(addressTextBox.Text); if (addresses.Count() == 0) { MessageBox.Show("We couldn't find that place, please try to clarify the address"); return; } double lati = addresses.First().Coordinates.Latitude; double longi = addresses.First().Coordinates.Longitude; pushPin.Location = new Microsoft.Maps.MapControl.WPF.Location(lati, longi); myMap.Children.Add(pushPin); myMap.Center = pushPin.Location; switch (createServiceCB.SelectedIndex) { //Food case 0: { newService = new FoodService(addressTextBox.Text, new Microsoft.Maps.MapControl.WPF.Location(lati, longi)); pushPin.Background = newService.color; servicesList[(int)ServiceType.FOOD].Add(newService); break; } //Car Repair case 1: { newService = new CarRepairService(addressTextBox.Text, new Microsoft.Maps.MapControl.WPF.Location(lati, longi)); pushPin.Background = newService.color; servicesList[(int)ServiceType.CAR_REPAIR].Add(newService); break; } //Other case 2: { newService = new OtherService(addressTextBox.Text, new Microsoft.Maps.MapControl.WPF.Location(lati, longi)); pushPin.Background = newService.color; servicesList[(int)ServiceType.OTHER].Add(newService); break; } } updateServiceListAndMap(null, null); }
public void CanParseAddressTypes(string address, EntityType type) { geoCoder.GeocodeAsync(address).ContinueWith(task => { BingAddress[] addresses = task.Result.ToArray(); Assert.Equal(type, addresses[0].Type); }); }
public async Task <BingAddress> GetCoordinatesAsync(string street, string city, string state, string postalCode, string country) { var result = await _bingMapsGeocoder.GeocodeAsync(street, city, state, postalCode, country); var bestMatch = result.FirstOrDefault(); return(bestMatch); }
public static async void SetCoordinates() { IGeocoder geocoder = new BingMapsGeocoder("Am2EX-qk3vxDWfcvExTEY9frj2m0Y5I4_YEayIlQvDInm-t6ueJ52uOOvEqGgTvE"); IEnumerable <Address> addresses = await geocoder.GeocodeAsync("petrosani hunedoara romania"); CoordinatesModel.Latitude = addresses.First().Coordinates.Latitude; CoordinatesModel.Longitude = addresses.First().Coordinates.Longitude; }
public async Task <IEnumerable <Essentials.Location> > GetLocationsAsync(string address) { var bingAddresses = await Geocoder.GeocodeAsync(address); var locations = bingAddresses.Select(x => new Essentials.Location(x.Coordinates.Latitude, x.Coordinates.Longitude)); return(locations); }
public async Task <string> GetLatLonFromAddress(string address) { async Task <string> getCordsFromAddress() { IGeocoder googleGeoCoder = new GoogleGeocoder() { ApiKey = Config.MappingConfig.GoogleMapsApiKey }; IGeocoder bingGeoCoder = new BingMapsGeocoder(Config.MappingConfig.BingMapsApiKey); string coordinates = null; try { var addresses = await googleGeoCoder.GeocodeAsync(address); if (addresses != null && addresses.Any()) { var firstAddress = addresses.First(); coordinates = string.Format("{0},{1}", firstAddress.Coordinates.Latitude, firstAddress.Coordinates.Longitude); } } catch { /* Don't report on GeoLocation failures */ } if (string.IsNullOrWhiteSpace(coordinates)) { try { var coords = GetLatLonFromAddressLocationIQ(address); if (coords != null) { coordinates = string.Format("{0},{1}", coords.Latitude, coords.Longitude); } } catch { /* Don't report on GeoLocation failures */ } } if (string.IsNullOrWhiteSpace(coordinates)) { try { var addresses = await bingGeoCoder.GeocodeAsync(address); if (addresses != null && addresses.Count() > 0) { coordinates = string.Format("{0},{1}", addresses.First().Coordinates.Latitude, addresses.First().Coordinates.Longitude); } } catch { /* Don't report on GeoLocation failures */ } } return(coordinates); } return(await _cacheProvider.RetrieveAsync <string>(string.Format(ForwardCacheKey, address.GetHashCode()), getCordsFromAddress, CacheLength)); }
public async Task <ActionResult <IEnumerable <Party> > > GetParties(string filter, string dateFilter, string typeFilter, string locationFilter) { var parties = _context.Parties.AsQueryable(); if (filter != null) { parties = parties.Where(party => party.Name.ToUpper(). Contains(filter.ToUpper()) || (party.Event.ToUpper().Contains(filter.ToUpper()))). Include(party => party.Comments). ThenInclude(comment => comment.User); } if (dateFilter != null) { parties = parties.Where(party => party.Date == dateFilter). Include(party => party.Comments). ThenInclude(comment => comment.User); } if (typeFilter != null) { parties = parties.Where(party => party.Type == typeFilter). Include(party => party.Comments). ThenInclude(comment => comment.User); } if (locationFilter != null) { Console.WriteLine($"The location filter is {locationFilter}"); // Create a new geocoder var geocoder = new BingMapsGeocoder(BING_MAPS_KEY); // Request this address to be geocoded. var geocodedAddresses = await geocoder.GeocodeAsync(locationFilter); // ... and pick out the best address sorted by the confidence level var bestGeocodedAddress = geocodedAddresses.Where(address => address.Confidence == ConfidenceLevel.High).OrderBy(address => address.Confidence).LastOrDefault(); // If we have a best geocoded address, use the latitude and longitude from that result if (bestGeocodedAddress != null) { var location = new Point(bestGeocodedAddress.Coordinates.Latitude, bestGeocodedAddress.Coordinates.Longitude) { SRID = 4326 }; parties = parties.Where(party => party.Location.Distance(location) <= .144); } else { parties = parties.Where(party => party.Id == 0); } } return(await parties.OrderBy(party => party.Date). Include(party => party.Comments). ThenInclude(comment => comment.User).ToListAsync()); }
public async Task <IActionResult> PutParty(int id, Party party) { if (id != party.Id) { return(BadRequest()); } // Find this restaurant by looking for the specific id *AND* check the UserID against the current logged in user var partyExists = await _context.Parties.Where(party => party.Id == id && party.UserId == GetCurrentUserId()).AnyAsync(); if (!partyExists) { // There wasn't a restaurant with that id so return a `404` not found return(NotFound()); } // Create a new geocoder var geocoder = new BingMapsGeocoder(BING_MAPS_KEY); // Request this address to be geocoded. var geocodedAddresses = await geocoder.GeocodeAsync(party.Address); // ... and pick out the best address sorted by the confidence level var bestGeocodedAddress = geocodedAddresses.OrderBy(address => address.Confidence).LastOrDefault(); // If we have a best geocoded address, use the latitude and longitude from that result if (bestGeocodedAddress != null) { party.Location = new Point(bestGeocodedAddress.Coordinates.Latitude, bestGeocodedAddress.Coordinates.Longitude) { SRID = 4326 }; } _context.Entry(party).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PartyExists(id)) { return(NotFound()); } else { throw; } } return(Ok(party)); }
public async Task <ActionResult <Location> > PostLocation(Location location) { // Create a new geocoder var geocoder = new BingMapsGeocoder(BING_MAPS_KEY); // Request this address to be geocoded. var geocodedAddresses = await geocoder.GeocodeAsync(location.Address); // ... and pick out the best address sorted by the confidence level var bestGeocodedAddress = geocodedAddresses.OrderBy(address => address.Confidence).LastOrDefault(); // If we have a best geocoded address, use the latitude and longitude from that result if (bestGeocodedAddress != null) { location.Latitude = bestGeocodedAddress.Coordinates.Latitude; location.Longitude = bestGeocodedAddress.Coordinates.Longitude; } // Set the UserID to the current user id, this overrides anything the user specifies. location.UserId = GetCurrentUserId(); // Indicate to the database context we want to add this new record _context.Locations.Add(location); await _context.SaveChangesAsync(); Console.WriteLine("name: " + location.Name); Console.WriteLine("ID: " + location.Id); Console.WriteLine("Address: " + location.Address); Console.WriteLine("UserId: " + location.UserId); Console.WriteLine("Movie: " + location.Movie); Console.WriteLine("Lat: " + location.Latitude); Console.WriteLine("Long: " + location.Longitude); Console.WriteLine("Photo: " + location.PhotoURL); Console.WriteLine("FilmId: " + location.FilmId); Console.WriteLine("Desc: " + location.Description); // for (var index = 0; index < location.Reviews.Count; index++) // { // Console.WriteLine("review: " + location.Reviews[index]); // } // Return a response that indicates the object was created (status code `201`) and some additional // headers with details of the newly created object. return(CreatedAtAction("GetLocation", new { id = location.Id }, location)); }
public async Task <LookupResult> LookupAsync(string postalCode, string city, string street) { _logger.GeocodingStartLookup(postalCode, city, street); IGeocoder geocoder = new BingMapsGeocoder(_options.Value.ApiKey); IList <Address> addresses = (await geocoder.GeocodeAsync(street, city, null, postalCode, "Switzerland")).ToList(); if (!addresses.Any()) { _logger.GeocodingLookupNoResultsFound(postalCode, city, street); return(new LookupResult()); } if (addresses.Count > 1) { _logger.GeocodingLookupMultipleAddressesFound(postalCode, city, street, string.Join(';', addresses.Select(a => a.FormattedAddress))); } return(new LookupResult(addresses.First().Coordinates.Longitude, addresses.First().Coordinates.Latitude)); }
public async Task ApplyCulture(string address, string culture, string result) { geoCoder.Culture = culture; BingAddress[] addresses = (await geoCoder.GeocodeAsync(address)).ToArray(); Assert.Equal(result, addresses[0].FormattedAddress); }
public async Task <IActionResult> PutRestaurant(int id, Restaurant restaurant) { // If the ID in the URL does not match the ID in the supplied request body, return a bad request if (id != restaurant.Id) { return(BadRequest()); } // Find this restaurant by looking for the specific id *AND* check the UserID against the current logged in user var restaurantExists = await _context.Restaurants.Where(restaurant => restaurant.Id == id && restaurant.UserId == GetCurrentUserId()).AnyAsync(); if (!restaurantExists) { // There wasn't a restaurant with that id so return a `404` not found return(NotFound()); } // Create a new geocoder var geocoder = new BingMapsGeocoder(BING_MAPS_KEY); // Request this address to be geocoded. var geocodedAddresses = await geocoder.GeocodeAsync(restaurant.Address); // ... and pick out the best address sorted by the confidence level var bestGeocodedAddress = geocodedAddresses.OrderBy(address => address.Confidence).LastOrDefault(); // If we have a best geocoded address, use the latitude and longitude from that result if (bestGeocodedAddress != null) { restaurant.Latitude = bestGeocodedAddress.Coordinates.Latitude; restaurant.Longitude = bestGeocodedAddress.Coordinates.Longitude; } // Tell the database to consider everything in restaurant to be _updated_ values. When // the save happens the database will _replace_ the values in the database with the ones from restaurant _context.Entry(restaurant).State = EntityState.Modified; try { // Try to save these changes. await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { // Ooops, looks like there was an error, so check to see if the record we were // updating no longer exists. if (!RestaurantExists(id)) { // If the record we tried to update was already deleted by someone else, // return a `404` not found return(NotFound()); } else { // Otherwise throw the error back, which will cause the request to fail // and generate an error to the client. throw; } } // return NoContent to indicate the update was done. Alternatively you can use the // following to send back a copy of the updated data. // return(Ok(restaurant)); }
// only get the data here, buddy public async Task <WeatherRendererInfo> GetForecastAsync(string query) { // use google to get address, lat, and lng for a human-entered string Location location; try { IGeocoder geocoder = new BingMapsGeocoder(bingApiKey); var geoResult = await geocoder.GeocodeAsync(query); dynamic address = geoResult.FirstOrDefault(); if (address == null) { return(null); } location = new Location { Latitude = address.Coordinates.Latitude, Longitude = address.Coordinates.Longitude, FormattedAddress = address.FormattedAddress }; if (address.Type.ToString().StartsWith("Postcode")) { location.FormattedAddress = $"{address.Locality} {address.FormattedAddress}"; } } catch (Exception) { return(null); } // request darksky without minutely/hourly, and use location to determine units var WeatherService = new DarkSkyService(darkSkyApiKey); DarkSkyResponse forecast = await WeatherService.GetForecast(location.Latitude, location.Longitude, new DarkSkyService.OptionalParameters { DataBlocksToExclude = new List <ExclusionBlock> { ExclusionBlock.Minutely, ExclusionBlock.Hourly, }, MeasurementUnits = "auto" }); var timezone = DateTimeZoneProviders.Tzdb[forecast.Response.TimeZone]; var myTime = SystemClock.Instance.GetCurrentInstant(); var info = new WeatherRendererInfo() { Address = location.FormattedAddress, Unit = forecast.Response.Flags.Units == "us" ? "F" : "C", Date = myTime.InZone(timezone), Temperature = forecast.Response.Currently.Temperature, FeelsLike = forecast.Response.Currently.ApparentTemperature, Alert = forecast.Response.Alerts?[0].Title }; int counter = 0; foreach (var day in forecast.Response.Daily.Data.Take(4)) { var dayRender = new WeatherRendererDay() { HiTemp = day.TemperatureHigh, LoTemp = day.TemperatureLow, Summary = weatherDescription.ContainsKey(day.Icon.ToString()) ? weatherDescription[day.Icon.ToString()] : day.Icon.ToString().Replace("-", ""), Icon = string.Join("-", Regex.Split(day.Icon.ToString(), @"(?<!^)(?=[A-Z])")).ToLower(), Date = info.Date.Plus(Duration.FromDays(counter)) }; info.Forecast.Add(dayRender); counter++; } return(info); }
async Task PlacePointsAsync(List <Transaction> listTransac, List <Appointment> listAppoint, List <Person> listClients) { IGeocoder geocoder = new BingMapsGeocoder("2nbycCL6Gzmsr7jeoLGt~i-GGspDBBqMJLETkBSB4AA~AkYmtyboWJkGoYbS734ufkxbskzYOGwHuAG79CvLt1wiYNviJBQ8EwLd2IIO9-K3"); IEnumerable <Address> addresses = null; foreach (var item in listTransac) { try { addresses = await geocoder.GeocodeAsync(item.Estate.Address + " " + item.Estate.ZipCode + " " + item.Estate.City); Application.Current.Dispatcher.Invoke(() => { OcMapPoints.Add(new MapPoint() { Latitude = addresses.First().Coordinates.Latitude, Longitude = addresses.First().Coordinates.Longitude, Name = "Transaction : " + item.Title, Description = item.Description }); }); } catch (Exception) { } } foreach (var item in listAppoint) { try { addresses = await geocoder.GeocodeAsync(item.Address + " " + item.ZipCode + " " + item.City); Application.Current.Dispatcher.Invoke(() => { OcMapPoints.Add(new MapPoint() { Latitude = addresses.First().Coordinates.Latitude, Longitude = addresses.First().Coordinates.Longitude, Name = "Appointnment : " + item.Reason, Description = item.Person1.FirstName + " avec " + item.Person2.FirstName }); }); } catch (Exception) { } } foreach (var item in listClients) { try { addresses = await geocoder.GeocodeAsync(item.Address + " " + item.ZipCode + " " + item.City); Application.Current.Dispatcher.Invoke(() => { OcMapPoints.Add(new MapPoint() { Latitude = addresses.First().Coordinates.Latitude, Longitude = addresses.First().Coordinates.Longitude, Name = "Person : " + item.FirstName + " " + item.LastName, Description = item.Mail }); }); } catch (Exception) { } } }