// Finds the closest Addresses by calling a server-side Stored Procedure
        private HawkerDistance[] FindClosestAddresses(GeocodingResponse coordinates)
        {
            HawkerDistance[] fiveClosestAddresses = new HawkerDistance[5];
            int arrayIndex = 0;

            using (SqlConnection conn = new SqlConnection(_context.Database.GetDbConnection().ConnectionString)) {
                conn.Open();

                SqlCommand cmd = new SqlCommand("dbo.CLOSEST_HAWKERS", conn);
                cmd.CommandType = CommandType.StoredProcedure;

                double lat = coordinates.Results.First().Geometry.Location.Latitude;
                double lng = coordinates.Results.First().Geometry.Location.Longitude;
                AddSQLParameter(cmd, "@Lat", lat);
                AddSQLParameter(cmd, "@Lng", lng);

                // execute the command
                using (SqlDataReader dataReader = cmd.ExecuteReader()) {
                    // iterate through results, printing each to console
                    while (CanReadMore(arrayIndex, dataReader))
                    {
                        HawkerDistance distance = CreateDistance(dataReader.GetDouble(0),
                                                                 dataReader.GetInt32(1), dataReader.GetString(2), dataReader.GetString(3),
                                                                 dataReader.GetDouble(4), dataReader.GetDouble(5));
                        fiveClosestAddresses[arrayIndex++] = distance;
                    }
                    return(fiveClosestAddresses);
                }
            }
        }
        /// <summary>
        /// Execute the Command: collect the fields of the Model from the multi-converter in the View and set the values in the ViewModel
        /// </summary>
        /// <param name="parameter">parameters that were collected form the View usin</param>
        public async void Execute(object parameter)
        {
            var    values = (object[])parameter;
            Report report = new Report();

            report.name         = values[0].ToString();
            report.timeOfReport = DateTime.Parse(values[1].ToString());
            string address = values[2].ToString();

            try
            {
                GeocodingRequest geocodeRequest = new GeocodingRequest();
                geocodeRequest.Address = address;
                geocodeRequest.ApiKey  = googleMapsKey;
                GeocodingResponse geocode = await GoogleMaps.Geocode.QueryAsync(geocodeRequest);

                if (geocode.Status == Status.OK)
                {
                    IEnumerator <Result> iter = geocode.Results.GetEnumerator();
                    iter.MoveNext();
                    GM.Location tempLocation = iter.Current.Geometry.Location;
                    latitude  = tempLocation.Latitude;
                    longitude = tempLocation.Longitude;
                }
            }
            catch (Exception exception) { }

            report.Latitude          = latitude;  //coord.Latitude;
            report.Longitude         = longitude; //  coord.Longitude;
            report.numOfBombs        = int.Parse(values[3].ToString());
            report.cityName          = values[4].ToString();
            CurrentVM.incomingReport = report;
        }
Ejemplo n.º 3
0
        public void Geocode_Address_Many()
        {
            IEnumerable <GeocodingResponse> responses =
                MapsApi.Geocode(_context, "sofia, bulgaria", "plovdiv bulgaria", "varna, bulgaria");

            Assert.IsNotNull(responses);
            Assert.AreEqual(3, responses.Count());

            var expected = new LatLng[]
            {
                new LatLng(42.6977082, 23.3218675),
                new LatLng(42.1354079, 24.7452904),
                new LatLng(43.2140504, 27.9147333)
            };

            for (int i = 0; i < 3; i++)
            {
                GeocodingResponse response = responses.Skip(i).Take(1).FirstOrDefault();
                Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);

                LatLng actual = response.Results?[0].Geometry.Location;

                Assert.AreEqual(expected[i], actual);
            }
        }
        public IActionResult CloseHawkersAsync(string address)
        {
            List <HawkerDistance> distances = new List <HawkerDistance> ();
            string mapsMarkers = "";

            try {
                GeocodingResponse coordinates = GeocodeAddress(address);
                CheckForCoordinatesErrors(coordinates);
                distances   = FiveClosestDistancesToCoordinates(coordinates);
                mapsMarkers = CreateStringMarkers(distances);
                bool noMarkersAvailable = String.IsNullOrEmpty(mapsMarkers);
                if (noMarkersAvailable)
                {
                    return(RedirectToAction("Index"));
                }
                ViewBag.Markers       = mapsMarkers;
                ViewBag.SearchAddress = address;
                return(View("closehawkers"));
            } catch (System.Exception ex) {
                Console.WriteLine("An exception occurred in AddressController/CloseHawkers");
                Console.WriteLine($"Exception text: {ex.Message}");
                ViewBag.Exception = ex.Message;
                return(View("closehawkers"));
            }
        }
Ejemplo n.º 5
0
        public void Issues_Issue13038()
        {
            GeocodingRequest  request  = new GeocodingRequest("Yonge and Finch Toronto Canada Ontario");
            GeocodingResponse response = request.GetResponse();

            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);
        }
Ejemplo n.º 6
0
        public void Geocoding_GoogleBuilidng_IsEqualCoordinates()
        {
            GeocodingResponse response = _geocodingClient.Geocoding(_addressStr);

            Assert.AreEqual(IsStatusOk(response.Status), true);
            Assert.AreEqual(IsCoordinatesFound(response.Results), true);
        }
Ejemplo n.º 7
0
        public void ReverseGeocoding_PlaceId_IsGoogleBuilding()
        {
            GeocodingResponse response = _geocodingClient.ReverseGeocoding(_placeId);

            Assert.AreEqual(IsStatusOk(response.Status), true);
            Assert.AreEqual(IsAddressFound(response.Results), true);
        }
Ejemplo n.º 8
0
        protected void btnTestar_Click(Object sender, EventArgs e)
        {
            var geocodingRequest = new GeocodingRequest {
                Location = new Location(-19.904356, -43.925691)
            };

            GeocodingResponse geocodingResponse = GoogleMaps.Geocode.Query(geocodingRequest);

            if (geocodingResponse != null && geocodingResponse.Status == Status.OK)
            {
                var drivingDirectionRequest = new DirectionsRequest
                {
                    Origin       = ObterEndereco(geocodingResponse),
                    Destination  = "Avenida Amazonas 7000, Belo Horizonte, MG, Brazil",
                    Sensor       = false,
                    Alternatives = false
                };

                DirectionsResponse drivingDirections = GoogleMaps.Directions.Query(drivingDirectionRequest);
                if (drivingDirections != null && drivingDirections.Status == DirectionsStatusCodes.OK)
                {
                    lblDistancia.Text = string.Format("Distância Total: {0} m.", ObterDistanciaTotal(drivingDirections).ToString());
                }
            }
        }
Ejemplo n.º 9
0
        public void Geocode_Location_Many()
        {
            var locations = new LatLng[]
            {
                new LatLng(42.6977082, 23.3218675),
                new LatLng(42.1354079, 24.7452904),
                new LatLng(43.2140504, 27.9147333)
            };
            IEnumerable <GeocodingResponse> responses = MapsApi.Geocode(_context, locations);

            Assert.IsNotNull(responses);
            Assert.AreEqual(3, responses.Count());

            var expected = new string[]
            {
                @"pl. ""Nezavisimost"", 1000 Sofia, Bulgaria",
                @"bul. ""Hristo Botev"" 56, 4000 Plovdiv, Bulgaria",
                @"bul. ""Tsar Osvoboditel"" 83, 9000 Varna, Bulgaria"
            };

            for (int i = 0; i < 3; i++)
            {
                GeocodingResponse response = responses.Skip(i).Take(1).FirstOrDefault();
                Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);

                string actual = response.Results?[0].FormattedAddress;

                Assert.AreEqual(expected[i], actual);
            }
        }
Ejemplo n.º 10
0
        public void TestGetGeocodingResponse()
        {
            string            result    = "{\n   \"results\" : [\n      {\n         \"address_components\" : [\n            {\n               \"long_name\" : \"17852\",\n               \"short_name\" : \"17852\",\n               \"types\" : [ \"street_number\" ]\n            },\n            {\n               \"long_name\" : \"10 Mile Road\",\n               \"short_name\" : \"10 Mile Rd\",\n               \"types\" : [ \"route\" ]\n            },\n            {\n               \"long_name\" : \"Le Roy\",\n               \"short_name\" : \"Le Roy\",\n               \"types\" : [ \"locality\", \"political\" ]\n            },\n            {\n               \"long_name\" : \"Cedar Township\",\n               \"short_name\" : \"Cedar Township\",\n               \"types\" : [ \"administrative_area_level_3\", \"political\" ]\n            },\n            {\n               \"long_name\" : \"Osceola County\",\n               \"short_name\" : \"Osceola County\",\n               \"types\" : [ \"administrative_area_level_2\", \"political\" ]\n            },\n            {\n               \"long_name\" : \"Michigan\",\n               \"short_name\" : \"MI\",\n               \"types\" : [ \"administrative_area_level_1\", \"political\" ]\n            },\n            {\n               \"long_name\" : \"United States\",\n               \"short_name\" : \"US\",\n               \"types\" : [ \"country\", \"political\" ]\n            },\n            {\n               \"long_name\" : \"49655\",\n               \"short_name\" : \"49655\",\n               \"types\" : [ \"postal_code\" ]\n            },\n            {\n               \"long_name\" : \"8025\",\n               \"short_name\" : \"8025\",\n               \"types\" : [ \"postal_code_suffix\" ]\n            }\n         ],\n         \"formatted_address\" : \"17852 10 Mile Rd, Le Roy, MI 49655, USA\",\n         \"geometry\" : {\n            \"bounds\" : {\n               \"northeast\" : {\n                  \"lat\" : 43.9590503,\n                  \"lng\" : -85.44075119999999\n               },\n               \"southwest\" : {\n                  \"lat\" : 43.9590368,\n                  \"lng\" : -85.4407515\n               }\n            },\n            \"location\" : {\n               \"lat\" : 43.9590368,\n               \"lng\" : -85.44075119999999\n            },\n            \"location_type\" : \"RANGE_INTERPOLATED\",\n            \"viewport\" : {\n               \"northeast\" : {\n                  \"lat\" : 43.9603925302915,\n                  \"lng\" : -85.43940236970849\n               },\n               \"southwest\" : {\n                  \"lat\" : 43.9576945697085,\n                  \"lng\" : -85.44210033029151\n               }\n            }\n         },\n         \"place_id\" : \"EicxNzg1MiAxMCBNaWxlIFJkLCBMZSBSb3ksIE1JIDQ5NjU1LCBVU0E\",\n         \"types\" : [ \"street_address\" ]\n      }\n   ],\n   \"status\" : \"OK\"\n}\n";
            GeocodingResponse resultObj = _googleMapsClient.GetGeocodingResponseObject(result);

            Assert.IsNotNull(resultObj);
        }
Ejemplo n.º 11
0
        public void Issues_Issue11898()
        {
            GeocodingRequest  request  = new GeocodingRequest("4 Cassia Ct, Alice Springs, Northern Territory, 0870, Australia");
            GeocodingResponse response = request.GetResponse();

            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// If the response status indicates fail because of quota exceeded - mark test as inconclusive.
 /// </summary>
 public static void NotExceedQuota(GeocodingResponse response)
 {
     if (response?.Status == Entities.Geocoding.Response.Status.OVER_QUERY_LIMIT)
     {
         throw new InconclusiveException(QuotaExceedMessage);
     }
 }
Ejemplo n.º 13
0
        private GeocodingResponse GetGeocodeResponse(ILocation where)
        {
            var cacheKey  = where.Name.ToString() + "-geocoding";
            var cachedVal = FindInCache <GeocodingResponse>(cacheKey);

            if (cachedVal != null)
            {
                return(cachedVal);
            }

            GeocodingRequest geocodeRequest = new GeocodingRequest()
            {
                Address = where.Name,
            };

            geocodeRequest.ApiKey = this.apikey;

            var geocodingEngine = GoogleMaps.Geocode;

            GeocodingResponse geocode = geocodingEngine.Query(geocodeRequest);

            if (geocode.Status == Status.OK)
            {
                return(AddToCache(cacheKey, geocode));
            }

            return(null);
        }
Ejemplo n.º 14
0
        public void ReverseGeocoding_Coordinates_IsGoogleBuilding()
        {
            GeocodingResponse response = _geocodingClient.ReverseGeocoding(_locationCoordinates);

            Assert.AreEqual(IsStatusOk(response.Status), true);
            Assert.AreEqual(IsAddressFound(response.Results), true);
        }
Ejemplo n.º 15
0
        public void GetResponse_Result_Async()
        {
            GeocodingRequest  request  = new GeocodingRequest("plovdiv bulgaria");
            GeocodingResponse response = request.GetResponseAsync();

            Assert.IsNotNull(response);
            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);
        }
Ejemplo n.º 16
0
        public async Task GetResponse_Result_Async()
        {
            GeocodingRequest  request  = new GeocodingRequest("plovdiv bulgaria", _context);
            GeocodingResponse response = await request.GetResponseAsync();

            Assert.IsNotNull(response);
            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);
        }
Ejemplo n.º 17
0
        public string ObterEndereco(GeocodingResponse response)
        {
            if (response.Results != null)
            {
                return(response.Results.FirstOrDefault().FormattedAddress);
            }

            return(String.Empty);
        }
 private List <HawkerDistance> FiveClosestDistancesToCoordinates(GeocodingResponse coordinates)
 {
     try {
         HawkerDistance[] closestAddresses = FindClosestAddresses(coordinates);
         var distances = new List <HawkerDistance> ();
         distances.AddRange(closestAddresses);
         return(distances);
     } catch (System.Exception ex) {
         throw new Exception($"An exception occurred in FiveClosestDistancesToCoordinates.  The exception text says: {ex.Message} ");
     }
 }
Ejemplo n.º 19
0
        protected virtual bool IsValidGeocodingResponse(GeocodingResponse result)
        {
            if (result.Status != GeocodingStatusCode.Ok || result.Results == null)
            {
                return(false);
            }

            var location = result.Results.FirstOrDefault();

            return(location != null && location.Geometry != null && location.Geometry.Location != null);
        }
Ejemplo n.º 20
0
        //---GEOCODING REQUESTS---

        public async Task <ApiResult <GeocodingResponse> > SearchAddressAsync(string searchString, CancellationToken token = default(CancellationToken))
        {
            string urlString = $"{DefaultGeocodingRequestUrl}" +
                               $"search?text={searchString}" +
                               $"&boundary.rect.min_lat={GeocodingConstants.BoundaryRectMinLat.ToString(NumberFormatInfo.InvariantInfo)}" +
                               $"&boundary.rect.max_lat={GeocodingConstants.BoundaryRectMaxLat.ToString(NumberFormatInfo.InvariantInfo)}" +
                               $"&boundary.rect.min_lon={GeocodingConstants.BoundaryRectMinLon.ToString(NumberFormatInfo.InvariantInfo)}" +
                               $"&boundary.rect.max_lon={GeocodingConstants.BoundaryRectMaxLon.ToString(NumberFormatInfo.InvariantInfo)}" +
                               $"&focus.point.lat={GeocodingConstants.FocusPointLat.ToString(NumberFormatInfo.InvariantInfo)}" +
                               $"&focus.point.lon={GeocodingConstants.FocusPointLon.ToString(NumberFormatInfo.InvariantInfo)}" +
                               $"&lang={_settingsService.CurrentLanguage.Substring(0, 2)}";
            Uri uri = new Uri(urlString);

            try
            {
                var response = await _networkClient.GetAsync(uri, token);

                if (response == null || !response.IsSuccessStatusCode)
                {
                    LogHttpFailure(response).DoNotAwait();
                    if (response?.StatusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        return(ApiResult <GeocodingResponse> .FailWithReason(FailureReason.ServerDown));
                    }
                    else
                    {
                        return(ApiResult <GeocodingResponse> .Fail);
                    }
                }

                GeocodingResponse geoResponse = (await response.Content.ReadAsInputStreamAsync())
                                                .AsStreamForRead()
                                                .DeseriaizeJsonFromStream <GeocodingResponse>();

                if (!geoResponse.Features.Any())
                {
                    return(ApiResult <GeocodingResponse> .FailWithReason(FailureReason.NoResults));
                }

                return(new ApiResult <GeocodingResponse>(geoResponse));
            }
            catch (Exception ex) when(ex is COMException || ex is HttpRequestException || ex is OperationCanceledException)
            {
                if (ex is OperationCanceledException)
                {
                    return(ApiResult <GeocodingResponse> .FailWithReason(FailureReason.Canceled));
                }
                else
                {
                    LogException(ex);
                    return(ApiResult <GeocodingResponse> .FailWithReason(FailureReason.NoConnection));
                }
            }
        }
Ejemplo n.º 21
0
        public void Geocode_Address()
        {
            GeocodingResponse response = MapsApi.Geocode(_context, "plovdiv bulgaria");

            Assert.IsNotNull(response);
            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);

            var expected = new LatLng(42.1354079, 24.7452904);
            var actual   = response.Results?[0].Geometry.Location;

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 22
0
        public void Geocode_Location()
        {
            GeocodingResponse response = MapsApi.Geocode(_context, new LatLng(42.1354079, 24.7452904));

            Assert.IsNotNull(response);
            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);

            string expected = @"bul. ""Hristo Botev"" 56, 4000 Plovdiv, Bulgaria";
            string actual   = response.Results?[0].FormattedAddress;

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 23
0
        private bool IsFoundAddress(GeoCoordinates location)
        {
            GeocodingResponse response = FindAddress(location);
            bool is_found = IsStatusOk(response.Status);

            if (!is_found)
            {
                Console.WriteLine($"Address of location: {location.ToString()} is not found: {response.Status}");
            }

            return(is_found);
        }
Ejemplo n.º 24
0
        public void GetResponse_Result_ByAddress()
        {
            GeocodingRequest  request  = new GeocodingRequest("plovdiv bulgaria", _context);
            GeocodingResponse response = request.GetResponse();

            Assert.IsNotNull(response);
            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);

            LatLng actual   = response.Results?[0].Geometry.Location;
            LatLng expected = new LatLng(42.1354079, 24.7452904);

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 25
0
        public void GetResponse_Result_ByLocationPair()
        {
            GeocodingRequest  request  = new GeocodingRequest(42.1354079, 24.7452904, _context);
            GeocodingResponse response = request.GetResponse();

            Assert.IsNotNull(response);
            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);

            string actual   = response.Results?[0].FormattedAddress;
            string expected = @"bul. ""Hristo Botev"" 56, 4000 Plovdiv, Bulgaria";

            Assert.AreEqual(expected, actual);
        }
Ejemplo n.º 26
0
        public void SetGeocode(string address)
        {
            GeocodingRequest geocodeRequest = new GeocodingRequest()
            {
                Address    = address,
                ApiKey     = Utilities.APIs.MapsKey,
                SigningKey = "Lew Vine"
            };
            var geoCodingEngine       = GoogleMaps.Geocode;
            GeocodingResponse geocode = geoCodingEngine.Query(geocodeRequest);

            this.LatAddress  = geocode.Results.First().Geometry.Location.Latitude;
            this.LongAddress = geocode.Results.First().Geometry.Location.Longitude;
        }
Ejemplo n.º 27
0
        public void GetResponse_Result_ByStreetAddress()
        {
            GeocodingRequest  request  = new GeocodingRequest("Alice Springs, Northern Territory, 0870, Australia", _context);
            GeocodingResponse response = request.GetResponse();

            Assert.IsNotNull(response);
            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);

            request.Address = "4 Cassia Ct, Alice Springs, Northern Territory, 0870, Australia";
            response        = request.GetResponse();

            Assert.IsNotNull(response);
            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);
        }
        private static void CheckForCoordinatesErrors(GeocodingResponse coordinates)
        {
            bool incorrectStatus = coordinates.Status != Status.OK;

            if (incorrectStatus)
            {
                throw new Exception($"Cannot proceed - Geocoding Response gave invalid status: {coordinates.Status}");
            }
            bool wrongNumberOfCoordinates = coordinates.Results.Count() != 1;

            if (wrongNumberOfCoordinates)
            {
                throw new Exception($"Cannot proceed - Geocoding Response gave incorrect number of coordinates.  Count: {coordinates.Results.Count()}");
            }
        }
Ejemplo n.º 29
0
        public void Geocode_Address_Async()
        {
            GeocodingResponse response = MapsApi.GeocodeAsync(MapsApiContext.Default, "plovdiv bulgaria");

            Assert.IsNotNull(response);
            Assert.AreEqual(GeocodingResponseStatus.OK, response.Status);

            LatLng expected = new LatLng(42.1354079, 24.7452904);
            LatLng actual   = response.Results
                              .Select(x => x.Geometry)
                              .Select(x => x.Location)
                              .FirstOrDefault();

            Assert.AreEqual(expected, actual);
        }
        // Lat, Lng

        private async Task <double[]> GetGeoCode(ConfirmLocation location)
        {
            // hard code for now, API calls will eventually be service
            var geoCodingEngine             = GoogleMaps.Geocode;
            GeocodingRequest geocodeRequest = new()
            {
                Address = $"{location.Street}, {location.City}, {location.State} {location.Zipcode}",
                ApiKey  = Secrets.GOOGLE_API_KEY,
            };
            GeocodingResponse geocode = await geoCodingEngine.QueryAsync(geocodeRequest);

            double lat = geocode.Results.First().Geometry.Location.Latitude;
            double lng = geocode.Results.First().Geometry.Location.Longitude;

            return(new double[] { lat, lng });
        }