private void GetLocationFromResponse(dynamic result, ref GoogleDataObject data)
        {
            foreach (var res in result.address_components)
            {
                if (data.City == null && res.types[0] == "locality")
                {
                    data.City = res.long_name;
                }
                else if (data.City == null && data.CityAlt == null && res.types[0] == "administrative_area_level_1")
                {
                    data.CityAlt = res.long_name;
                }
                else if (data.Country == null && res.types[0] == "country")
                {
                    data.Country     = res.long_name;
                    data.CountryCode = res.short_name;
                }

                if (data.City != null && data.Country != null)
                {
                    break;
                }
            }


            data.Latitude  = result.geometry.location.lat;
            data.Longitude = result.geometry.location.lng;
            data.PlaceId   = result.place_id;
        }
        public async Task DistanceDurationBetweenLocationsCoordinates()
        {
            // Inject
            // Arrange
            var expected = new GoogleDataObject()
            {
                Distance = "130 km", Duration = "2 hours 4 mins"
            };

            var loc1 = new GoogleDataObject()
            {
                Latitude = 42.504792599999988, Longitude = 27.4626361
            };
            var loc2 = new GoogleDataObject()
            {
                Latitude = 43.2140504, Longitude = 27.9147333
            };


            // Act
            var result = await service.DistanceDurationBetweenLocations(loc1, loc2);

            // Assert
            Assert.Equal(Serialize(expected), Serialize(result));
        }
        public async Task <List <GooglePlaceObject> > GetNearbyPlaces(UserKeywords input, string type = null, int radius = 25000, string searchKeyword = "attraction")
        {
            //location lng ltd
            // Dont include radius if rankby DISTANCE exists
            // keyword - name type address etc.
            // rankny prominence
            // type - ONLY ONE TYPE MAY BE SUPPLIED

            GoogleDataObject coordinates;

            if (input.KeywordAddress.Latitude == null || input.KeywordAddress.Longitude == null)
            {
                coordinates = await CoordinatesFromLocation(input.Keyword);
            }
            else
            {
                coordinates = new GoogleDataObject
                {
                    Latitude  = input.KeywordAddress.Latitude,
                    Longitude = input.KeywordAddress.Longitude
                };
            }


            type          = type != null ? $"&type={type}" : "";
            searchKeyword = searchKeyword != null ? $"&keyword={searchKeyword}" : "";

            string responseBody = await GetStringAsync($"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={coordinates.Latitude},{coordinates.Longitude}&rankby=prominence&radius={radius}{type}{searchKeyword}");

            dynamic result = JsonConvert.DeserializeObject(responseBody);

            if (result.status != "OK" && result.status != "ZERO_RESULTS")
            {
                throw new ArgumentException("An unexpected error occured while contacting google API");
            }

            var output = new List <GooglePlaceObject>();

            foreach (var a in result.results)
            {
                if (a.photos != null)
                {
                    output.Add(new GooglePlaceObject()
                    {
                        Guid           = Guid.NewGuid(),
                        BusinessStatus = a.business_status,
                        Name           = a.name,
                        PlaceId        = a.place_id,
                        Vicinity       = a.vicinity,
                        Latitude       = a.geometry.location.lat,
                        Longtitude     = a.geometry.location.lng,
                        Rating         = a.rating,
                        PhotoReference = a.photos[0].photo_reference,
                    });
                }
            }

            return(output);
        }
        private async Task AddKeyword(string keyword, GoogleDataObject result)
        {
            if (result == null)
            {
                throw new ArgumentException("Data object was empty");
            }
            if (keyword == null)
            {
                throw new ArgumentException("Keyword was empty");
            }
            var userId = await base.GetUserId(httpContext.GetCurrentAuth());

            if (userId == 0)
            {
                throw new Exception("There isn't such a user in the system");
            }

            using (var a = contextFactory.CreateDbContext())
            {
                if (await a.UserKeywords.FirstOrDefaultAsync(x => x.Keyword == keyword) != null)
                {
                    throw new ArgumentException("This keyword already exists in our database");
                }

                var address = new KeywordAddress()
                {
                    City        = result.City,
                    CityAlt     = result.CityAlt,
                    Country     = result.Country,
                    CountryCode = result.CountryCode,
                    Latitude    = result.Latitude,
                    Longitude   = result.Longitude
                };

                var types = new List <KeywordType>();

                foreach (var r in result.Types)
                {
                    types.Add(new KeywordType()
                    {
                        Type = r
                    });
                }

                var key = new UserKeywords()
                {
                    UserId = userId, Keyword = keyword, KeywordAddress = address, KeywordType = types
                };

                await a.UserKeywords.AddAsync(key);

                await a.SaveChangesAsync();
            }
        }
        public async Task CoordinatesFromLocation()
        {
            // Inject
            // Arrange
            var expected = new GoogleDataObject()
            {
                Latitude = 42.504792599999988, Longitude = 27.4626361
            };

            // Act
            var result = await service.CoordinatesFromLocation("Burgas");

            // Assert
            Assert.Equal(Serialize(expected), Serialize(result));
        }
Beispiel #6
0
        public async Task SearchForLocation()
        {
            // Inject
            // Arrange
            var expected = new GoogleDataObject()
            {
                City = "Burgas", Country = "Bulgaria", CountryCode = "BG", Latitude = 42.5138584, Longitude = 27.469502, Types = { "establishment", "point_of_interest", "school" }, PlaceId = "ChIJc-mFqIaUpkARt2OCHhOpfk4"
            };
            // Act
            //var types = new string[2] { "airport", "park" };
            var result = await service.SearchForLocation("НЕГ Гьоте");

            // Assert
            Assert.Equal(typeof(GoogleDataObject), result.GetType());
        }
        public async Task LocationFromCoordinates()
        {
            // Inject
            // Arrange
            var coordinates = new GoogleDataObject()
            {
                Latitude = 42.513361, Longitude = 27.465091
            };
            var expected = new GoogleDataObject()
            {
                City = "Burgas", Country = "Bulgaria", Latitude = 42.5133555, Longitude = 27.4650935, CountryCode = "BG", Types = { "establishment", "health", "hospital", "point_of_interest" }
            };
            // Act
            var result = await service.LocationFromCoordinates(coordinates);

            // Assert
            Assert.Equal(Serialize(expected), Serialize(result));
        }
        public async Task <GoogleDataObject> LocationFromLandmark(string landmark, string[] givenType = null)
        {
            landmark.IsNull();

            //Creates a types string
            string outputType = "&types=";

            outputType = givenType != null ? outputType + string.Join("|", givenType) : "";

            string responseBody = await GetStringAsync($"https://maps.googleapis.com/maps/api/geocode/json?address={landmark}{outputType}");

            dynamic result = JsonConvert.DeserializeObject(responseBody);

            if (result.status != "OK")
            {
                throw new ArgumentException("An unexpected error occured while contacting google API");
            }

            string fields = $"business_status,international_phone_number,name,opening_hours,rating,website,user_ratings_total,vicinity,photos";

            string responsePlace = await GetStringAsync($"https://maps.googleapis.com/maps/api/place/details/json?place_id={result.results[0].place_id}&fields={fields}");

            dynamic resultPlace = JsonConvert.DeserializeObject(responsePlace);

            if (resultPlace.status != "OK")
            {
                throw new ArgumentException("An unexpected error occured while contacting google API");
            }


            var data = new GoogleDataObject();

            // Get location details

            GetLocationFromResponse(result.results[0], ref data);

            // Google place details
            GetDetailsFromResponse(resultPlace.result, ref data);


            return(data);
        }
        public async Task <GoogleDataObject> GetLocationFromPlaceID(string placeId)
        {
            string fields = $"business_status,international_phone_number,name,opening_hours,rating,website,user_ratings_total,vicinity,photos,address_component,adr_address,geometry,vicinity,type,place_id";

            string responsePlace = await GetStringAsync($"https://maps.googleapis.com/maps/api/place/details/json?place_id={placeId}&fields={fields}");

            dynamic resultPlace = JsonConvert.DeserializeObject(responsePlace);

            if (resultPlace.status != "OK")
            {
                throw new ArgumentException("An unexpected error occured while contacting google API");
            }

            var data = new GoogleDataObject();

            //
            GetDetailsFromResponse(resultPlace.result, ref data);

            //
            GetLocationFromResponse(resultPlace.result, ref data);

            return(data);
        }
        private void GetDetailsFromResponse(dynamic resultPlace, ref GoogleDataObject data)
        {
            data.Business_status            = resultPlace.business_status;
            data.International_phone_number = resultPlace.international_phone_number;
            data.Name = resultPlace.name;
            if (resultPlace.photos != null)
            {
                data.PhotoReference = resultPlace.photos[0].photo_reference;
            }
            if (resultPlace.opening_hours != null)
            {
                data.OpenNow = resultPlace.opening_hours.open_now;

                foreach (var a in resultPlace.opening_hours.weekday_text)
                {
                    data.WeekdayText.Add(a.Value);
                }
            }
            data.Website            = resultPlace.website;
            data.User_ratings_total = resultPlace.user_ratings_total;
            data.Vicinity           = resultPlace.vicinity;
            data.Rating             = resultPlace.rating;
        }
        public async Task <GoogleDataObject> DistanceDurationBetweenLocations(GoogleDataObject latLngLocation1, GoogleDataObject latLngLocation2)
        {
            latLngLocation1.Latitude.IsNull();
            latLngLocation1.Longitude.IsNull();
            latLngLocation2.Latitude.IsNull();
            latLngLocation2.Longitude.IsNull();

            string responseBody = await GetStringAsync($"https://maps.googleapis.com/maps/api/distancematrix/json?origins={latLngLocation1.Latitude},{latLngLocation1.Longitude}&destinations={latLngLocation2.Latitude},{latLngLocation2.Longitude}");

            dynamic result = JsonConvert.DeserializeObject(responseBody);

            if (result.status != "OK")
            {
                throw new ArgumentException("An unexpected error occured while contacting google API");
            }

            string distance = result.rows[0].elements[0].distance.text;
            string duration = result.rows[0].elements[0].duration.text;

            return(new GoogleDataObject()
            {
                Distance = distance, Duration = duration
            });
        }
        public async Task <GoogleDataObject> LocationFromCoordinates(GoogleDataObject coordinates)
        {
            coordinates.Latitude.IsNull();
            coordinates.Longitude.IsNull();

            string responseBody = await GetStringAsync($"https://maps.googleapis.com/maps/api/geocode/json?latlng={coordinates.Latitude},{coordinates.Longitude}");

            dynamic result = JsonConvert.DeserializeObject(responseBody);

            if (result.status != "OK")
            {
                throw new ArgumentException("An unexpected error occured while contacting google API");
            }

            var data = new GoogleDataObject();

            foreach (var res in result.results)
            {
                if (data.City == null && res.types[0] == "locality")
                {
                    foreach (var address in res.address_components)
                    {
                        if (address.types[0] == "locality")
                        {
                            data.City = address.long_name;
                            break;
                        }
                    }
                }
                else if (data.City == null && data.CityAlt == null && res.types[0] == "administrative_area_level_1")
                {
                    foreach (var alt in res.address_components)
                    {
                        if (alt.types[0] == "administrative_area_level_1")
                        {
                            data.CityAlt = alt.long_name;
                            break;
                        }
                    }
                }
                else if (data.Country == null && res.types[0] == "country")
                {
                    data.Country     = res.address_components[0].long_name;
                    data.CountryCode = res.address_components[0].short_name;
                }

                if (data.City != null && data.Country != null)
                {
                    break;
                }
            }

            foreach (var type in result.results[0].types)
            {
                data.Types.Add((string)type);
            }

            data.Latitude  = result.results[0].geometry.location.lat;
            data.Longitude = result.results[0].geometry.location.lng;

            return(data);
        }
        private async Task <Tuple <GoogleDataObject, Users> > CheckIfAlreadyInWishlist(GoogleDataObject result)
        {
            using (var a = contextFactory.CreateDbContext())
            {
                var auth = httpContext.GetCurrentAuth();

                var id = await base.GetUserId(auth);

                var user = await a.Users.Where(x => x.Auth == auth).FirstOrDefaultAsync();

                var alreadyInWishlist = await a.Locations.Include(x => x.Wishlist).Where(x => x.Wishlist.UserId == id && x.PlaceId == result.PlaceId && x.TripId == null).FirstOrDefaultAsync();

                if (alreadyInWishlist != null)
                {
                    result.AlreadyInWishlist = true;
                }

                return(new Tuple <GoogleDataObject, Users>(result, user));
            }
        }