public async Task GeocodeAsync(SourceAddress source)
        {
            Uri geocodeRequest = new Uri(BuildUrlRequest(source));

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                var response = await client.GetAsync(geocodeRequest);

                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    var geocodeResult = JsonConvert.DeserializeObject <GoogleGeocodeResult>(content);

                    GeocodeResult <Result> bestResult = GetBestGeocodeResult(geocodeResult, source);

                    string freeformAddress = bestResult.Result == null ? "NULL" : bestResult.Result.FormattedAddress;
                    string resultType      = bestResult.Result == null ? "NULL" : bestResult.Result.Types[0];
                    ReportComparer.SaveAndDisplay(Path, $"Google Geocode;{source.Id};{source.Address};{source.Locality};{source.PostalCode};{source.Country};{resultType};{freeformAddress};{bestResult.Status};{geocodeResult.Results.Count}");
                }
                else
                {
                    //var error = await response.Content.ReadAsAsync<ErrorResponse>();
                    Console.WriteLine("Google HTTP Error");
                    ReportComparer.SaveAndDisplay(Path, $"Google Geocode;{source.Id};{source.Address};{source.Locality};{source.PostalCode};{source.Country};NULL;NULL;ZERO_RESULTS;0");
                }
            }
        }
Exemple #2
0
        public async Task GeocodeAsync(SourceAddress source)
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                var response = await client.GetAsync(BuildUrlRequest(source));

                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    ArcGisGeocodeResult       geocode    = JsonConvert.DeserializeObject <ArcGisGeocodeResult>(content);
                    GeocodeResult <Candidate> bestResult = GetBestGeocodeResult(geocode, source);

                    string freeformAddress = bestResult.Result == null ? "NULL" : bestResult.Result.Address;
                    string resultType      = bestResult.Result == null ? "NULL" : bestResult.Result.Attributes.AddrType;

                    ReportComparer.SaveAndDisplay(Path, $"ArcGis;{source.Id};{source.Address};{source.Locality};{source.PostalCode};{source.Country};{resultType};{freeformAddress};{bestResult.Status};{geocode.Candidates.Count};{CountByScore(geocode)}");
                }
                else
                {
                    //var error = await response.Content.ReadAsAsync<ErrorResponse>();
                    Console.WriteLine("ArcGis HTTP Error");
                    ReportComparer.SaveAndDisplay(Path, $"ArcGis;{source.Id};{source.Address};{source.Locality};{source.PostalCode};{source.Country};NULL;NULL;ZERO_RESULT;0");
                }
            }
        }
        private string BuildUrlRequest(SourceAddress source)
        {
            var result = default(string);


            string[] parameters =
            {
                source.Address.Replace(" ",  "+"),
                source.Locality.Replace(" ", "+"),
                source.PostalCode,           source.Country
            };

            switch (MethodType)
            {
            //if was processed with "AddressAndComponentsAll" use the next less strict method
            case GoogleGeocodeMethodType.AddressAndComponentsAll:
                result = string.Format(AddressAndComponentsWithPostalCodeGeocodeUrl, (parameters));
                break;

            //if was processed with "AddressAndComponentsWithPostalCode" use the next less strict method
            case GoogleGeocodeMethodType.AddressAndComponentsWithPostalCode:
                result = string.Format(OnlyAddressGeocodeUrl, (parameters));
                break;

            default:
                result = string.Format(AddressAndComponentsAllGeocodeUrl, (parameters));
                break;
            }

            result = $"{result}&key={GoogleMapsAPIKey}";

            return(result);
        }
        //TODO: Centralized this condition.
        private GoogleGeocodeResult ValidateCountryCodeAllowed(SourceAddress request)
        {
            const string COUNTRY_CODE_ALLOWED = "ES";
            var          result = new GoogleGeocodeResult();

            if (!request.Country.Equals(COUNTRY_CODE_ALLOWED))
            {
                result.Status = AddressStatusType.OTHER.ToString();
                return(result);
            }

            return(result);
        }
        public async Task GeocodeAsync(SourceAddress source)
        {
            var geocode = new CartociudadGeocodeResult();

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-javascript"));

                var uri = BuildCandidateEndPoint(source.FormattedAddress, source.Country);
                var responseCandidates = await client.GetAsync(uri);

                if (responseCandidates.IsSuccessStatusCode)
                {
                    string serialized = await responseCandidates.Content.ReadAsStringAsync();

                    serialized = serialized.Substring(9, serialized.Length - 9);
                    serialized = serialized.Substring(0, serialized.Length - 1);

                    List <CartociudadCandidatesResponse> candidates = JsonConvert.DeserializeObject <List <CartociudadCandidatesResponse> >(serialized);

                    if (candidates.Count > 0)
                    {
                        var bestCandidate = candidates.FirstOrDefault();

                        geocode = ValidateGeocodeCandidatesMatch(bestCandidate, source);

                        if (string.IsNullOrEmpty(geocode.Status))
                        {
                            var geocodeAddress = await SelectBestGeocodeAddressMatchAsync(bestCandidate);

                            geocode = CartociudadAddressToGeocodeAddressResponse(geocodeAddress, bestCandidate, source);
                        }
                    }


                    string freeformAddress = geocode.Results == null ? "NULL" : geocode.Results[0].FormattedAddress;
                    string resultType      = geocode.Results == null ? "NULL" : geocode.Results[0].Types[0];
                    string status          = geocode.Results == null ? "ZERO_RESULTS" : geocode.Status;
                    string results         = geocode.Results == null ? "0" : geocode.Results.Count.ToString();
                    ReportComparer.SaveAndDisplay(Path, $"Cartociudad Geocode;{source.Id};{source.Address};{source.Locality};{source.PostalCode};{source.Country};{resultType};{freeformAddress};{status};{results}");
                }
                else
                {
                    //var error = await response.Content.ReadAsAsync<ErrorResponse>();
                    Console.WriteLine("Cartociudad HTTP Error");

                    ReportComparer.SaveAndDisplay(Path, $"Cartociudad Geocode;{source.Id};{source.Address};{source.Locality};{source.PostalCode};{source.Country};NULL;NULL;ZERO_RESULTS;0");
                }
            }
        }
        private string BuildUrlRequest(SourceAddress source)
        {
            var result = default(string);

            switch (MethodType)
            {
            case BingMapsGeocodeMethodType.GeocodeFindLocationByQuery:
                result = string.Format("http://dev.virtualearth.net/REST/v1/Locations/?q={0}&key={1}", source.FormattedAddress, BingMapsAPIKey);
                break;

            default:
                break;
            }

            return(result);
        }
        private GeocodeResult <Result> GetBestGeocodeResult(GoogleGeocodeResult geocodeResult, SourceAddress source)
        {
            var result = new GeocodeResult <Result>();

            if (geocodeResult.Results.Count == 0)
            {
                result.Status = geocodeResult.Status;
                return(result);
            }

            var best = geocodeResult.Results[0]; //The best result

            var typeAllowed = best.Types.Contains(TypesAlloweds.FirstOrDefault(x => x.Equals(best.Types[0])));

            if (typeAllowed)
            {
                var postalCode = best.AddressComponents.Where(x => x.Types[0].Equals("postal_code")).FirstOrDefault();
                if (postalCode != null)
                {
                    result.Status = postalCode.LongName.Equals(source.PostalCode) && best.Geometry.LocationType.Equals("ROOFTOP") ? "OK" : "TO_CHECK";
                }
                else
                {
                    result.Status = "TO_CHECK";
                }
            }
            else
            {
                result.Status = "TO_CHECK";
            }

            result.Result = best;
            return(result);
        }
        private CartociudadGeocodeResult ValidateGeocodeCandidatesMatch(CartociudadCandidatesResponse candidates, SourceAddress request)
        {
            var result = new CartociudadGeocodeResult();

            if (candidates == null)
            {
                result.Status = AddressStatusType.ZERO_RESULTS.ToString();
                return(result);
            }

            if (candidates.State != CartociudadState.ValueOne)
            {
                result.Status = CartociudadToGeocodeStatusConverter.Convert(candidates.State).ToString();

                return(result);
            }

            //Check if portal number is ready
            if (candidates.PortalNumber.Equals(0))
            {
                result.Status = AddressStatusType.TO_CHECK.ToString();

                return(result);
            }

            if (!candidates.PostalCode.Equals(request.PostalCode))
            {
                result.Status = AddressStatusType.TO_CHECK.ToString();

                return(result);
            }

            return(result);
        }
        private List <AddressComponent> BuildAddressComponents(CartociudadFindResponse cartociudadFindResponse, CartociudadCandidatesResponse cartociudadCandidatesResponse, SourceAddress sourceAddress)
        {
            var result = new List <AddressComponent>();

            var component = cartociudadFindResponse.PortalNumber.ToString();

            result.Add(BuildAddressComponent <AddressComponent>(STREET_NUMBER, component, component));

            component = UpperCaseConverter.Convert(CartoCiudadRouteConverter.Convert(cartociudadFindResponse.Address ?? cartociudadCandidatesResponse.Address, cartociudadFindResponse.PortalNumber.ToString()));

            result.Add(BuildAddressComponent <AddressComponent>(ROUTE, component, component));

            component = UpperCaseConverter.Convert(cartociudadFindResponse.Locality ?? cartociudadCandidatesResponse.Locality);
            result.Add(BuildAddressComponent <AddressComponent>(LOCALITY, component, component));

            component = UpperCaseConverter.Convert(cartociudadFindResponse.Province ?? cartociudadCandidatesResponse.Province);
            result.Add(BuildAddressComponent <AddressComponent>(ADMINISTRATIVE_AREA_LEVEL_2, component, component));

            component = UpperCaseConverter.Convert(CartoCiudadToGeocodeCountryConverter.CountryConvert(cartociudadFindResponse.CountryCode ?? cartociudadCandidatesResponse.CountryCode));
            var shortComponent = CartoCiudadToGeocodeCountryConverter.CountryCodeConvert(cartociudadFindResponse.CountryCode ?? cartociudadCandidatesResponse.CountryCode);

            result.Add(BuildAddressComponent <AddressComponent>(COUNTRY, shortComponent, component));

            component = (cartociudadFindResponse.PostalCode == null ? sourceAddress.PostalCode : string.Empty).ToString();
            result.Add(BuildAddressComponent <AddressComponent>(POSTAL_CODE, component, component));

            return(result);
        }
        private CartociudadGeocodeResult CartociudadAddressToGeocodeAddressResponse(CartociudadFindResponse cartociudadFindResponse, CartociudadCandidatesResponse cartociudadCandidatesResponse, SourceAddress sourceAddress)
        {
            var result = new CartociudadGeocodeResult();

            var addressComponents = BuildAddressComponents(cartociudadFindResponse, cartociudadCandidatesResponse, sourceAddress);
            var formatedAddress   = BuildFormattedAddress(addressComponents);
            var placeId           = BuildPlaceId(cartociudadFindResponse);

            result.Results = new List <Result>()
            {
                new Result()
                {
                    AddressComponents = addressComponents,
                    FormattedAddress  = formatedAddress,
                    PlaceId           = placeId,
                    Types             = new List <string>()
                    {
                        STREET_ADDRESS
                    }
                }
            };

            result.Status = BuildStatus(cartociudadFindResponse);

            return(result);
        }
        private GeocodeResult <Resource> GetBestGeocodeResult(BingMapsGeocodeResult geocodeResult, SourceAddress source)
        {
            var result = new GeocodeResult <Resource>();


            if (geocodeResult.ResourceSets[0].Resources.Count == 0)
            {
                result.Status = "ZERO_RESULT";
                return(result);
            }

            var best = geocodeResult.ResourceSets[0].Resources[0]; //The best result

            if (!best.Address.CountryRegion.Equals("Spain"))
            {
                result.Status = "ZERO_RESULT";
                return(result);
            }

            /* EntityType:
             *
             *  Neighborhood:A section of a populated place that is typically well-known, but often with indistinct boundaries.
             *  Roadblock: Like Street
             *  Address: indicates a precise street address
             * Ref:https://docs.microsoft.com/en-us/bingmaps/rest-services/locations/location-data
             * Ref:https://docs.microsoft.com/en-us/bingmaps/spatial-data-services/public-data-sources/poi-entity-types
             */

            if (best.EntityType.Equals("Address") || best.EntityType.Equals("Roadblock"))
            {
                if (best.MatchCodes[0].Equals("Good") && (best.Confidence.Equals("High") || best.Confidence.Equals("Medium")))
                {
                    result.Status = best.Address.PostalCode.Equals(source.PostalCode) ? "OK" : "TO_CHECK";
                }
                else
                {
                    result.Status = "TO_CHECK";
                }
            }
            else
            {
                result.Status = "TO_CHECK";
            }

            result.Result = best;
            return(result);
        }
Exemple #12
0
        private string BuildUrlRequest(SourceAddress source)
        {
            string result = $"https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?f=json&singleLine={source.FormattedAddress}&outFields=Match_addr,Addr_type,postal,country";

            return(result);
        }
Exemple #13
0
        private GeocodeResult <Candidate> GetBestGeocodeResult(ArcGisGeocodeResult geocodeResult, SourceAddress source)
        {
            var result = new GeocodeResult <Candidate>();

            if (geocodeResult.Candidates.Count == 0)
            {
                result.Status = "ZERO_RESULTS";
                return(result);
            }

            var best = geocodeResult.Candidates[0]; //The best result

            if (string.IsNullOrEmpty(best.Attributes.Country))
            {
                result.Status = "ZERO_RESULT";
                return(result);
            }

            if (!best.Attributes.Country.Equals("ESP"))
            {
                result.Status = "ZERO_RESULT";
                return(result);
            }

            var typeAllowed = best.Attributes.AddrType.Equals(TypesAlloweds.FirstOrDefault(x => x.Equals(best.Attributes.AddrType)) ?? string.Empty);

            if (typeAllowed)
            {
                result.Status = best.Attributes.Postal.Equals(source.PostalCode) ? "OK" : "TO_CHECK";
            }
            else
            {
                result.Status = "TO_CHECK";
            }

            result.Result = best;
            return(result);
        }