public string GetLatLonFromAddress(string address)
        {
            Func <string> getCordsFromAddress = delegate()
            {
                IGeocoder googleGeoCoder = new GoogleGeocoder()
                {
                    ApiKey = Config.MappingConfig.GoogleMapsApiKey
                };
                IGeocoder bingGeoCoder = new BingMapsGeocoder(Config.MappingConfig.BingMapsApiKey);
                string    coordinates  = null;

                try
                {
                    var addresses = googleGeoCoder.Geocode(address);

                    if (addresses != null && addresses.Any())
                    {
                        var firstAddress = addresses.First();

                        coordinates = string.Format("{0},{1}", firstAddress.Coordinates.Latitude, firstAddress.Coordinates.Longitude);
                    }
                }
                catch
                { }

                if (string.IsNullOrWhiteSpace(coordinates))
                {
                    try
                    {
                        var coords = GetLatLonFromAddressLocationIQ(address);

                        if (coords != null)
                        {
                            coordinates = string.Format("{0},{1}", coords.Latitude, coords.Longitude);
                        }
                    }
                    catch
                    { }
                }

                if (string.IsNullOrWhiteSpace(coordinates))
                {
                    try
                    {
                        var addresses = bingGeoCoder.Geocode(address);

                        if (addresses != null && addresses.Count() > 0)
                        {
                            coordinates = string.Format("{0},{1}", addresses.First().Coordinates.Latitude, addresses.First().Coordinates.Longitude);
                        }
                    }
                    catch
                    { }
                }

                return(coordinates);
            };

            return(_cacheProvider.Retrieve <string>(string.Format(ForwardCacheKey, address.GetHashCode()), getCordsFromAddress, CacheLength));
        }
        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 <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));
        }
Exemple #4
0
        // Geocodes an address using the Bing Maps engine
        public static Location SearchBing(string add)
        {
            try
            {
                // Calls the Werservice
                BingMapsGeocoder      geocoder  = new BingMapsGeocoder(ConfigurationManager.AppSettings["BingApiKey"]);
                IEnumerable <Address> addresses = geocoder.Geocode(add);

                // Selects the firt result
                BingAddress b = (BingAddress)addresses.FirstOrDefault();

                Location r = new Location();

                r.Lat     = addresses.FirstOrDefault().Coordinates.Latitude;
                r.Lon     = addresses.FirstOrDefault().Coordinates.Longitude;
                r.Quality = b.Confidence.ToString();
                r.Address = addresses.FirstOrDefault().FormattedAddress;

                return(r);
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message);
            }
        }
        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));
        }
Exemple #6
0
        public Dictionary <string, double> GetCoordinates(string location)
        {
            string address = location;

            IGeocoder geocoder = new BingMapsGeocoder(_apiKey);
            var       result   = new Dictionary <string, double>();

            try
            {
                IEnumerable <Address> response = geocoder.Geocode(location);

                if (response != null)
                {
                    result.Add("lat", response.First().Coordinates.Latitude);
                    result.Add("long", response.First().Coordinates.Longitude);

                    Debug.WriteLine("Location: " + location);
                    Debug.WriteLine("Lat: " + result["lat"]);
                    Debug.WriteLine("Long: " + result["long"]);
                }
                ;
            } catch (Exception e)
            {
                Debug.WriteLine("Exception was thrown while processing location: " + location);
                Debug.WriteLine(e.Message);
                result.Add("lat", 0);
                result.Add("long", 0);
            }


            return(result);
        }
        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);
        }
Exemple #9
0
        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 <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());
        }
Exemple #11
0
        public async Task <string> GetAddressFromLatLong(double lat, double lon)
        {
            async Task <string> getAddressFromCords()
            {
                IGeocoder googleGeoCoder = new GoogleGeocoder()
                {
                    ApiKey = Config.MappingConfig.GoogleMapsApiKey
                };
                IGeocoder bingGeoCoder = new BingMapsGeocoder(Config.MappingConfig.BingMapsApiKey);

                string address = null;

                try
                {
                    var addresses = await googleGeoCoder.ReverseGeocodeAsync(lat, lon);

                    if (addresses != null && addresses.Any())
                    {
                        address = addresses.First().FormattedAddress;
                    }
                }
                catch { /* Don't report on GeoLocation failures */ }

                if (string.IsNullOrWhiteSpace(address))
                {
                    try
                    {
                        var addressGeo = GetAddressFromLatLonLocationIQ(lat.ToString(), lon.ToString());

                        if (!String.IsNullOrWhiteSpace(addressGeo))
                        {
                            address = addressGeo;
                        }
                    }
                    catch { /* Don't report on GeoLocation failures */ }
                }

                if (string.IsNullOrWhiteSpace(address))
                {
                    try
                    {
                        var addresses = await bingGeoCoder.ReverseGeocodeAsync(lat, lon);

                        if (addresses != null && addresses.Count() > 0)
                        {
                            address = addresses.First().FormattedAddress;
                        }
                    }
                    catch { /* Don't report on GeoLocation failures */ }
                }
                return(address);
            }

            return(await _cacheProvider.RetrieveAsync <string>(string.Format(ReverseCacheKey, string.Format("{0} {1}", lat, lon).GetHashCode()), getAddressFromCords, CacheLength));
        }
        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));
        }
Exemple #14
0
        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));
        }
Exemple #15
0
        // Geocodes an address using the Bing Maps engine
        public static Location Geocode_Bing(string ADDRESS)
        {
            try
            {
                // Calls the Werservice
                BingMapsGeocoder      GEOCODER  = new BingMapsGeocoder(ConfigurationManager.AppSettings["BingApiKey"]);
                IEnumerable <Address> ADDRESSES = GEOCODER.Geocode(ADDRESS);

                Location R = new Location();

                // Checks if the process returned a valid result
                if (ADDRESSES.Count() > 0)
                {
                    // Selects the firt result
                    BingAddress B = (BingAddress)ADDRESSES.FirstOrDefault();

                    R.Lat        = B.Coordinates.Latitude;
                    R.Lon        = B.Coordinates.Longitude;
                    R.Address    = B.AddressLine;      // Street + Number
                    R.City       = B.Locality;         // City
                    R.State      = B.AdminDistrict;    // State
                    R.PostalCode = B.PostalCode;       // Postal Code
                    R.Quality    = B.Confidence.ToString();
                    R.Complete   = B.FormattedAddress; // Full Address
                }
                else
                {
                    R.Lat     = 0;
                    R.Lon     = 0;
                    R.Quality = "Bad";
                }

                return(R);
            }
            catch (Exception ERROR)
            {
                throw new Exception(ERROR.Message);
            }
        }
Exemple #16
0
        /// <summary>
        /// Método para visualizar localização passada como parametro no construtor
        /// </summary>
        private void SetLocation()
        {
            //Instanciando objeto para recuperar as cordenadas
            IGeocoder geocoder = new BingMapsGeocoder(
                "AsHgFB0MOC02SgIYNbIwV9WOuo94eLp3brN5PvlD9Vu-p9DSjVUYfUZZIS5jfOeb"
                );
            IEnumerable <Address> results = geocoder.Geocode(this.location);

            //Recuperando primeiro endereco
            loc = new Microsoft.Maps.MapControl.WPF.Location();
            foreach (Address a in results)
            {
                loc = new Microsoft.Maps.MapControl.WPF.Location(
                    a.Coordinates.Latitude,
                    a.Coordinates.Longitude
                    );
                break;
            }

            //Visualizando coordenadas encontradas no mapa com zoom proprio
            bingMap.SetView(loc, zoom);    //Visualização em mapa
            bingMarker.Location = loc;     //Marcador de destino
        }
Exemple #17
0
 public GeoLocator()
 {
     _bingMapsGeocoder = new BingMapsGeocoder(@"ZiGnzRNQHfRYgXKEDqrd~FS9jVQ-P5OhNnMh4CgshlA~Am9JZXG8Ujt0mcai2JnjnrWn3UMisVbNZUzBzMVa0cx9XbFKtzU03LgIlYsQKUhm");
 }
        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)
                {
                }
            }
        }
 protected override IAsyncGeocoder CreateAsyncGeocoder()
 {
     geoCoder = new BingMapsGeocoder(ConfigurationManager.AppSettings["bingMapsKey"]);
     return(geoCoder);
 }
Exemple #20
0
 protected override IGeocoder CreateGeocoder()
 {
     geoCoder = new BingMapsGeocoder("" /*ConfigurationManager.AppSettings["bingMapsKey"]*/);
     return(geoCoder);
 }
Exemple #21
0
 protected override IGeocoder CreateGeocoder()
 {
     geoCoder = new BingMapsGeocoder(settings.BingMapsKey);
     return(geoCoder);
 }
 public GeocodeController(ILogger <WeatherController> logger, BingMapsGeocoder geocoder)
 {
     _logger   = logger;
     _geocoder = geocoder;
 }
        public string GetAddressFromLatLong(double lat, double lon)
        {
            Func <string> getAddressFromCords = delegate()
            {
                IGeocoder googleGeoCoder = new GoogleGeocoder()
                {
                    ApiKey = Config.MappingConfig.GoogleMapsApiKey
                };
                IGeocoder bingGeoCoder = new BingMapsGeocoder(Config.MappingConfig.BingMapsApiKey);

                string address = null;

                try
                {
                    var addresses = googleGeoCoder.ReverseGeocode(lat, lon);

                    if (addresses != null && addresses.Any())
                    {
                        address = addresses.First().FormattedAddress;
                    }
                }
                catch
                {
                }

                if (string.IsNullOrWhiteSpace(address))
                {
                    try
                    {
                        var addressGeo = GetAddressFromLatLonLocationIQ(lat.ToString(), lon.ToString());

                        if (!String.IsNullOrWhiteSpace(addressGeo))
                        {
                            address = addressGeo;
                        }
                    }
                    catch
                    {
                    }
                }

                if (string.IsNullOrWhiteSpace(address))
                {
                    try
                    {
                        var addresses = bingGeoCoder.ReverseGeocode(lat, lon);

                        if (addresses != null && addresses.Count() > 0)
                        {
                            address = addresses.First().FormattedAddress;
                        }
                    }
                    catch
                    {
                    }
                }
                return(address);
            };

            return(_cacheProvider.Retrieve <string>(string.Format(ReverseCacheKey, string.Format("{0} {1}", lat, lon).GetHashCode()), getAddressFromCords, CacheLength));
        }
        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));
        }
Exemple #25
0
        // 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);
        }
Exemple #26
0
 public BingGeoCodeProvider(IConfiguration configuration)
 {
     _bingMapsGeocoder = new BingMapsGeocoder(configuration["BingKey"]);
 }