public GoogleAddress GeocodeAddress(IAddress address) { var key = Engine.Settings.Integrations.GoogleMapsApiKey; if (!key.IsSet() || !Engine.Settings.Integrations.EnableGoogleGeocoding) { return(null); } IGeocoder geocoder = new GoogleGeocoder() { ApiKey = key }; IEnumerable <Address> addresses = geocoder.GeocodeAsync( address.Number.IsSet() ? string.Format("{0} {1}", address.Number, address.Address1) : address.Address1, address.City, address.County, address.Postcode, address.Country ).Result; if (addresses.Count() == 0) { addresses = geocoder.GeocodeAsync(address.Postcode).Result; if (addresses.Count() == 0) { return(null); } } return((GoogleAddress)addresses.First()); }
public static async Task <Geoposition> GetCoordinatesByAddressAsync(Geoposition geoposition) { try { IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyCDDmQbMj74oDWZoLco5W7t4nMKP8 - 77Qg" }; var literalAddress = new StringBuilder(); literalAddress.Append(geoposition.Country) .Append(' ') .Append(geoposition.City) .Append(' ') .Append(geoposition.Region) .Append(' ') .Append(geoposition.Address); IEnumerable <Address> addresses = await geocoder.GeocodeAsync(literalAddress.ToString()); var firstAddress = addresses.First(); geoposition.Latitude = firstAddress.Coordinates.Latitude.ToString(); geoposition.Longitude = firstAddress.Coordinates.Longitude.ToString(); return(geoposition); }catch (Exception ex) { return(geoposition); } }
public async Task <IActionResult> Create([Bind("Id,Name,StreetAddress,AddressCity,AddressState,AddressZip,StoreHours,PhoneNumber,Logo,CompanyVision,Email,Latitude,Longitude")] StoreInfo storeInfo) { if (ModelState.IsValid) { _context.Add(storeInfo); await _context.SaveChangesAsync(); var addressString = string.Format("https://maps.googleapis.com/maps/api/geocode/json?address=" + storeInfo.StreetAddress + " " + storeInfo.AddressCity + " " + storeInfo.AddressState + " " + storeInfo.AddressZip + "&key=" + APIKEYS.GoogleAPI); IGeocoder geocoder = new GoogleGeocoder() { ApiKey = APIKEYS.GoogleAPI }; IEnumerable <Address> addresses = await geocoder.GeocodeAsync(addressString); storeInfo.Latitude = addresses.First().Coordinates.Latitude; storeInfo.Longitude = addresses.First().Coordinates.Longitude; _context.Update(storeInfo); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(storeInfo)); }
public async Task <Patient> AddLatLongToPatient(Patient patient) { var formattedAddress = $"{patient.HouseNumber} {patient.HouseNumberAddon} {patient.Street} {patient.City} {patient.Country}"; var geocoder = new GoogleGeocoder { ApiKey = _configuration["GoogleApiKey"] }; try { var addresses = await geocoder.GeocodeAsync(formattedAddress); var enumerable = addresses.ToList(); patient.Latitude = enumerable.First().Coordinates.Latitude; patient.Longitude = enumerable.First().Coordinates.Longitude; } catch (Exception) { throw new ArgumentException("Invalid address."); } return(patient); }
public async void ConvertToLatLongAsync(string address) { IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyAtdAqKhJlXMN2ON9tmKuZQwndEI8dDWe8" }; IEnumerable <Address> addresses = await geocoder.GeocodeAsync(address); MySqlConnection conn = DB.Connection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand() as MySqlCommand; cmd.CommandText = @"UPDATE sightings SET lat = @Latitude, lng = @Longitude ORDER BY id DESC LIMIT 1"; cmd.Parameters.AddWithValue("@Latitude", addresses.First().Coordinates.Latitude); cmd.Parameters.AddWithValue("@Longitude", addresses.First().Coordinates.Longitude); cmd.ExecuteNonQuery(); conn.Close(); if (conn != null) { conn.Dispose(); } }
public async Task <GeocodedAddress> Geocode(string address) { var googleAddresses = await _geocoder.GeocodeAsync(address); if (!googleAddresses.Any()) { throw new GeocodingServiceException( $"No results for this address : {address}" ); } var formattedAddress = googleAddresses.First(); var coordinates = googleAddresses.First(); var street = googleAddresses.Select(a => a[GoogleAddressType.Route]).First(); var streetNumber = googleAddresses.Select(a => a[GoogleAddressType.StreetNumber]).First(); var city = googleAddresses.Select(a => a[GoogleAddressType.Locality]).First(); var country = googleAddresses.Select(a => a[GoogleAddressType.Country]).First(); var zipCode = googleAddresses.Select(a => a[GoogleAddressType.PostalCode]).First(); var department = googleAddresses.Select(a => a[GoogleAddressType.AdministrativeAreaLevel2]).First(); return(new GeocodedAddress { Address = formattedAddress?.FormattedAddress, Lat = coordinates.Coordinates.Latitude, Lng = coordinates.Coordinates.Longitude, Street = street?.LongName, StreetNumber = streetNumber?.LongName, City = city?.LongName, Department = department?.LongName, DepartmentCode = zipCode?.LongName.Substring(0, 2), Country = country?.LongName, ZipCode = zipCode?.LongName, }); }
public async Task CanParseAddressTypes(string address, GoogleAddressType type) { var result = await geoCoder.GeocodeAsync(address); GoogleAddress[] addresses = result.ToArray(); Assert.Equal(type, addresses[0].Type); }
public static async Task <Point> GeocodeAsync(string location, GeocodingApi apiType) { Point result; switch (apiType) { case GeocodingApi.Yandex: var codingResult = await YandexGeocoder.GeocodeAsync(location); if (!codingResult.Any()) { return(null); } var firstPoint = codingResult.First().Point; result = new Point { Latitude = firstPoint.Latitude, Longitude = firstPoint.Longitude }; break; case GeocodingApi.Google: var geocoder = new GoogleGeocoder(); lock (KeyLock) { if (!string.IsNullOrEmpty(_googleApiKey)) { geocoder.ApiKey = _googleApiKey; } } IEnumerable <GoogleAddress> addresses; try { addresses = await geocoder.GeocodeAsync(location); } catch (Exception ex) { Logger.LogException("GOOGLE GEO", LogLevel.Debug, ex); return(null); } var firstAddress = addresses?.FirstOrDefault(); if (firstAddress == null) { return(null); } result = new Point { Latitude = firstAddress.Coordinates.Latitude, Longitude = firstAddress.Coordinates.Longitude }; break; default: throw new ArgumentOutOfRangeException(nameof(apiType), apiType, null); } return(result); }
public async Task <bool> Create(User user) { IEnumerable <GoogleAddress> addresses = null; try { var geocoder = new GoogleGeocoder(); addresses = await geocoder.GeocodeAsync($"{user.Organization_Address_Line1} {user.Organization_Address_Line2}, {user.Organization_City}, {user.Organization_State}, {user.Organization_PostalCode}"); } catch (Exception ex) { Console.WriteLine("Error geocoding: " + ex.StackTrace); } var query = $"INSERT INTO [User] (Oid, Email, Person_Name, Verified, Admin, Recipient, Status, Phone_Number, Organization_Name, Organization_Address_Line1, " + "Organization_Address_Line2, Organization_City, Organization_State, Organization_PostalCode, Organization_Country, Lat, Long) VALUES " + $"(@Oid, " + $"@Email, " + $"@Person_Name, " + "0, " + "0, " + "0, " + $"'{UserStatus.Active.ToString()}', " + $"@Phone_Number, " + $"@Organization_Name, " + $"@Organization_Address_Line1, " + $"@Organization_Address_Line2, " + $"@Organization_City, " + $"@Organization_State, " + $"@Organization_PostalCode, " + $"@Organization_Country, " + $"@Lat, " + $"@Long)"; using (SqlConnection connection = new SqlConnection(builder.ConnectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@Oid", user.Oid); command.Parameters.AddWithValue("@Email", user.Email); command.Parameters.AddWithValue("@Person_Name", user.Person_Name ?? ""); command.Parameters.AddWithValue("@Phone_Number", user.Phone_Number ?? ""); command.Parameters.AddWithValue("@Organization_Name", user.Organization_Name ?? ""); command.Parameters.AddWithValue("@Organization_Address_Line1", user.Organization_Address_Line1 ?? ""); command.Parameters.AddWithValue("@Organization_Address_Line2", user.Organization_Address_Line2 ?? ""); command.Parameters.AddWithValue("@Organization_City", user.Organization_City ?? ""); command.Parameters.AddWithValue("@Organization_State", user.Organization_State ?? ""); command.Parameters.AddWithValue("@Organization_PostalCode", user.Organization_PostalCode ?? ""); command.Parameters.AddWithValue("@Organization_Country", user.Organization_Country ?? ""); command.Parameters.AddWithValue("@Lat", addresses?.FirstOrDefault()?.Coordinates.Latitude ?? 0.0); command.Parameters.AddWithValue("@Long", addresses?.FirstOrDefault()?.Coordinates.Longitude ?? 0.0); var res = command.ExecuteNonQuery(); command.Parameters.Clear(); return(res == 1); } } }
public void CanParseAddressTypes(string address, GoogleAddressType type) { geoCoder.GeocodeAsync(address).ContinueWith(task => { GoogleAddress[] addresses = task.Result.ToArray(); Assert.Equal(type, addresses[0].Type); }); }
public async Task <(double lat, double lon)> ObterCoordenadas(string endereco) { IGeocoder geocoder = new GoogleGeocoder(_configuration["Maps:ApiKey"]); var enderecos = await geocoder.GeocodeAsync(endereco); var resultado = enderecos.First(); return(resultado.Coordinates.Latitude, resultado.Coordinates.Longitude); }
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 <GeoLocation> GetGeoLocationFromAddress(string address) { var response = await geocoder.GeocodeAsync(address); var googleAddresses = response as GoogleAddress[] ?? response.ToArray(); return(googleAddresses .Select(x => new GeoLocation(x.Coordinates.Latitude, x.Coordinates.Longitude)) .FirstOrDefault()); }
public async Task <Location> GetLocationByAddress(string address) { IGeocoder geocoder = new GoogleGeocoder() { ApiKey = _appConfiguration.GoogleMapApiKey }; IEnumerable <Address> addresses = await geocoder.GeocodeAsync(address); return(addresses.First()?.Coordinates ?? new Location(0, 0)); }
public static async Task <Address> GetAddressAsync(string pointAddress) { var geocoder = new GoogleGeocoder { ApiKey = ConfigurationManager.AppSettings["Google.Maps.Key"] }; var addresses = await geocoder.GeocodeAsync(pointAddress); var addressesArray = addresses as GoogleAddress[] ?? addresses.ToArray(); return(addressesArray.Length == 0 ? null : addressesArray.First()); }
private async Task <GoogleAddress> GeoCodeLocation(Profile p) { if (string.IsNullOrWhiteSpace(_configuration["GoogleAPIKey"])) { return(null); } var geocoder = new GoogleGeocoder(_configuration["GoogleAPIKey"]); var addresses = await geocoder.GeocodeAsync(string.Join(',', p.Address, p.City, p.State).Trim(' ', ',')); return(addresses.First()); }
private async void GeoTest() { Geocoding.IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyAXD-mMtl9NDibrKZzYt6J2CvGr5_NKThI" }; IEnumerable <Geocoding.Address> addresses = await geocoder.GeocodeAsync("1600 pennsylvania ave washington dc"); Console.WriteLine("Formatted: " + addresses.First().FormattedAddress); //Formatted: 1600 Pennsylvania Ave SE, Washington, DC 20003, USA Console.WriteLine("Coordinates: " + addresses.First().Coordinates.Latitude + ", " + addresses.First().Coordinates.Longitude); //Coordinates: 38.8791981, -76.9818437 }
public static async Task<Tuple<double, double>> GeocodeAddressAsync(string address) { IGeocoder geocoder = new GoogleGeocoder() { ApiKey = Consts.GOOGLE_MAPS_API_KEY }; IEnumerable<Address> addresses = await geocoder.GeocodeAsync(address); if (addresses.Count() != 0) { return new Tuple<double, double>(addresses.First().Coordinates.Latitude, addresses.First().Coordinates.Longitude); } return null; }
private async Task <(double, double)> LocationFromAddress(string address) { IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "123abc" }; //replace this with your apiKey IEnumerable <Address> addresses = await geocoder.GeocodeAsync(address); //MessageBox.Show("Formatted: " + addresses.First().FormattedAddress); //Formatted: 1600 Pennsylvania Ave SE, Washington, DC 20003, USA //MessageBox.Show("Coordinates: " + addresses.First().Coordinates.Latitude + ", " + addresses.First().Coordinates.Longitude); //Coordinates: 38.8791981, -76.9818437 return(addresses.First().Coordinates.Latitude, addresses.First().Coordinates.Longitude); }
public static async Task <string> GetWeather(string address) { IGeocoder geocoder = new GoogleGeocoder(); IEnumerable <Address> addresses = await geocoder.GeocodeAsync(address); var georesult = addresses.First(); Forecast forecast = new Forecast(); var result = forecast.GetWeatherDataByCityNameAsync("a3222c3f65f66410ab8e7604f6d6a8d2", address, "gb", WeatherUnits.imperial); var test = Convert.ToString(result.Result.main.temp); return(test); }
public async Task <VehicleService> ConvertPostcode(VehicleService vehicleService) { IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyBj8k95-RJyz0HNan_RcgS_-suLQVb7NzA" }; IEnumerable <Address> addresses = await geocoder.GeocodeAsync(vehicleService.Postcode); vehicleService.Latitude = addresses.First().Coordinates.Latitude; vehicleService.Longitude = addresses.First().Coordinates.Longitude; return(vehicleService); }
public async System.Threading.Tasks.Task <string> ReturnPostalAsync(string postal, GoogleAddressType type) { Debug.WriteLine("postal" + postal); GoogleGeocoder geocoder = new GoogleGeocoder(); geocoder.ApiKey = "AIzaSyCY8FWydp6zky0N4TVk44x5xao2JjBFios"; IEnumerable <GoogleAddress> addresses = await geocoder.GeocodeAsync("Singapore" + postal); Debug.WriteLine(addresses.First().Coordinates.Latitude + ": :" + addresses.First().Coordinates.Longitude); IEnumerable <GoogleAddress> reverse = await geocoder.ReverseGeocodeAsync(addresses.First().Coordinates.Latitude, addresses.First().Coordinates.Longitude); Debug.WriteLine(addresses.First().FormattedAddress); Debug.WriteLine(reverse.First().FormattedAddress); return(reverse.First().FormattedAddress); }
public async Task Integration() { // Arrange var client = new Client(); var target = new GoogleGeocoder(client, Configuration.GoogleApiKey); // Act var location = await target.GeocodeAsync("1600 pennsylvania ave nw washington dc 20500"); // Assert Assert.NotNull(location); Assert.Equal(1, location.Locations.Length); Assert.Equal("The White House, 1600 Pennsylvania Ave NW, Washington, DC 20500, USA", location.Locations[0].Name); Assert.Equal(38.90, location.Locations[0].Latitude, 2); Assert.Equal(-77.04, location.Locations[0].Longitude, 2); }
public async Task <ActionResult <Local> > PostLocal(Local local) { //TODO: geocode the address IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyBspmkDaTr3qyTe6fXB5qT6MCQKiABCTKc" }; IEnumerable <Address> addresses = await geocoder.GeocodeAsync(local.Address + ' ' + local.City + ' ' + local.State + ' ' + local.State); local.Latitude = addresses.First().Coordinates.Latitude; local.Longitude = addresses.First().Coordinates.Longitude; _context.Locals.Add(local); await _context.SaveChangesAsync(); return(CreatedAtAction("GetLocal", new { id = local.Id }, local)); }
public async Task getCoordinates() { coordinates = new List <Coordinate>(); GoogleGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyDluSC2z6JF_8GDjqnZ8A5itPnwI4EWD4A" }; foreach (var mapPoint in addressList.Where(a => a.city.Equals(userAddress.Locality))) { string address = mapPoint.address1 + ", " + mapPoint.address2 + ", " + mapPoint.city + ", " + mapPoint.postcode; IEnumerable <GoogleAddress> addresses = await geocoder.GeocodeAsync(address); var latitude = addresses.FirstOrDefault().Coordinates.Latitude; var longitude = addresses.FirstOrDefault().Coordinates.Longitude; coordinates.Add(new Coordinate(latitude, longitude, mapPoint.address1)); } }
public async Task <IActionResult> Edit(Customer customer) { if (ModelState.IsValid) { try { customer.IdentityUserId = this.User.FindFirstValue(ClaimTypes.NameIdentifier); _context.Update(customer); await _context.SaveChangesAsync(); var customerAddress = _context.Address.Where(a => a.Id == customer.AddressId).SingleOrDefault(); IGeocoder geocoder = new GoogleGeocoder() { ApiKey = APIKeys.GOOGLE_API_KEY }; IEnumerable <Geocoding.Address> addresses = await geocoder.GeocodeAsync(customerAddress.AddressLine1 + " " + customerAddress.City + " " + customerAddress.State + " " + customerAddress.ZipCode); customerAddress.Latitude = addresses.First().Coordinates.Latitude; customerAddress.Longitude = addresses.First().Coordinates.Longitude; _context.Update(customerAddress); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CustomerExists(customer.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } if (customer.Id == 0) { return(RedirectToAction("Create", customer)); } return(View("Index")); }
public async Task <string> Get(string address) { try { Console.WriteLine("Getting by address"); IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyAZU4WGweBjNGS3l-a_i81SlD2OtgqggSw" }; IEnumerable <Address> addresses = await geocoder.GeocodeAsync(address); var googleAddress = addresses.First(); Console.WriteLine($"Found coordinates for address " + $"Lat: {googleAddress.Coordinates.Latitude} " + $"Long: {googleAddress.Coordinates.Longitude}"); var weatherClient = new WeatherGovClient(); var welcome = await weatherClient.GetWelcome(googleAddress.Coordinates.Latitude.ToString(), googleAddress.Coordinates.Longitude.ToString()); if (welcome == null) { return("{\"success\": false, \"message\": \"failed to get welcome\"}"); } var forecast = await weatherClient.GetForecastFromWelcome(welcome); if (forecast == null) { return("{\"success\": false, \"message\": \"failed to get forecast\"}"); } return(forecast.ToJSON()); } catch (Exception e) { // default error message return($"{{\"success\": false, \"message\": \"{e.Message}\"}}"); } }
//need to improve detection with Levenshtein distance public async Task <(string, Location)> GetAddressAndLocation(string[] FirstLine) { IGeocoder geocoder = new GoogleGeocoder() { ApiKey = Environments.AppConfig.GoogleMapsGeocodingAPIKey }; for (int i = 1; i < FirstLine.Count() - 2; i++) { var text = FirstLine[i - 1] + FirstLine[i] + FirstLine[i + 1] + FirstLine[i + 2]; IEnumerable <Address> addresses = await geocoder.GeocodeAsync(text); if (addresses.Count() != 0) { string address = addresses.First().FormattedAddress; Location location = addresses.First().Coordinates; return(address, location); } } return(null, new Location(0, 0)); }
public async Task getCoordinates() { coordinates = new List <Coordinate>(); GoogleGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyBQL6EeEsDIqm2FFp8hvcbgTReAAjFeIVc" }; // Sets up the geocoder using a Google Play plugin and using a GMAPS API Key that I have generated for the app foreach (var mapPoint in addressList.Where(a => a.city.Equals(usersAddress.Locality))) { string address = mapPoint.address1 + ", " + mapPoint.address2 + ", " + mapPoint.city + ", " + mapPoint.postcode; // Builds the address based on the address IEnumerable <GoogleAddress> addresses = await geocoder.GeocodeAsync(address); // This geocoder is a function made by the plugin and returns a lat and long point var latitude = addresses.FirstOrDefault().Coordinates.Latitude; var longitude = addresses.FirstOrDefault().Coordinates.Longitude; // Gets the co ordinates coordinates.Add(new Coordinate(latitude, longitude, mapPoint.address1)); // Adds it to a list } }
public async Task <IActionResult> PutLocal(int id, Local local) { if (id != local.Id) { return(BadRequest()); } _context.Entry(local).State = EntityState.Modified; IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "AIzaSyBspmkDaTr3qyTe6fXB5qT6MCQKiABCTKc" }; IEnumerable <Address> addresses = await geocoder.GeocodeAsync(local.Address + ' ' + local.City + ' ' + local.State + ' ' + local.State); local.Latitude = addresses.First().Coordinates.Latitude; local.Longitude = addresses.First().Coordinates.Longitude; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!LocalExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
static void Main(string[] args) { string search = "victoria"; string baseAddress = "https://www.aif.adfa.edu.au/"; HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb(); HtmlAgilityPack.HtmlDocument doc = web.Load($"{baseAddress}search?type=search&name=®Num=&place={search}&includeNOK=n&townOnly=n&start=0&pageSize=1000&totFound=1000"); var listings = doc.DocumentNode.SelectNodes("//tr"); System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Aidan\Desktop\aifScrap.json"); file.AutoFlush = true; file.WriteLine("["); foreach (var item in listings.Where(l => l != listings.Last())) { Console.WriteLine(item); string num = item.ChildNodes[1].InnerHtml; string name = item.ChildNodes[2].InnerText; string address = item.ChildNodes[3].InnerHtml; string battalion = item.ChildNodes[4].InnerText; IGeocoder geocoder = new GoogleGeocoder() { ApiKey = "" }; IEnumerable <Address> addresses = geocoder.GeocodeAsync(address).Result; string entry = "{\"name\": \"" + name + "\"," + "\"address\": \"" + address + "\"},"; file.WriteLine(entry); } file.WriteLine("]"); }