public PointLatLng?GetPoint(string keywords, out GeoCoderStatusCode status, out float accuracy)
        {
            PointLatLng?coordinate = null;

            accuracy = 0f;

            var request = new GeocodingRequest
            {
                Address = keywords,
                Sensor  = false
            };

            var response = _geocodingService.GetResponse(request);

            status = GoogleMapWrapper.ToGeoCoderStatusCode(response.Status);

            if (response.Results.Any())
            {
                var geometry = response.Results[0].Geometry;
                coordinate = GoogleMapWrapper.ToPointLatLng(geometry.Location);
                accuracy   = GoogleMapWrapper.ToAccuracyValue(geometry.LocationType);
            }

            return(coordinate);
        }
Exemplo n.º 2
0
        public void GetGeocodingForCoordinates()
        {
            // expectations
            var expectedStatus      = ServiceResponseStatus.Ok;
            var expectedResultCount = 9;
            var expectedTypes       = new AddressType[] {
                AddressType.StreetAddress,
                AddressType.Locality,
                AddressType.PostalCode,
                AddressType.Sublocality,
                AddressType.AdministrativeAreaLevel2,
                AddressType.AdministrativeAreaLevel1,
                AddressType.Country,
                AddressType.Political
            };
            var expectedFormattedAddress = "277 Bedford Ave, Brooklyn, NY 11211, USA";
            var expectedComponentTypes   = new AddressType[] {
                AddressType.StreetNumber,
                AddressType.Route,
                AddressType.Locality,
                AddressType.AdministrativeAreaLevel1,
                AddressType.AdministrativeAreaLevel2,
                AddressType.Sublocality,
                AddressType.Country,
                AddressType.PostalCode,
                AddressType.Political
            };
            var expectedLatitude           = 40.7142330m;
            var expectedLongitude          = -73.9612910m;
            var expectedLocationType       = LocationType.Rooftop;
            var expectedSouthwestLatitude  = 40.7110854m;
            var expectedSouthwestLongitude = -73.9644386m;
            var expectedNortheastLatitude  = 40.7173806m;
            var expectedNortheastLongitude = -73.9581434m;

            // test
            var request = new GeocodingRequest();

            request.LatitudeLongitude = "40.714224,-73.961452";
            request.Sensor            = "false";
            var response = GeocodingService.GetResponse(request);

            // asserts
            Assert.AreEqual(expectedStatus, response.Status, "Status");
            Assert.AreEqual(expectedResultCount, response.Results.Length, "ResultCount");
            Assert.IsTrue(
                expectedTypes.OrderBy(x => x).SequenceEqual(
                    response.Results.SelectMany(y => y.Types).Distinct().OrderBy(z => z)));
            Assert.AreEqual(expectedFormattedAddress, response.Results.First().FormattedAddress, "FormattedAddress");
            Assert.IsTrue(
                expectedComponentTypes.OrderBy(x => x).SequenceEqual(
                    response.Results.First().Components.SelectMany(y => y.Types).Distinct().OrderBy(z => z)), "Types");
            Assert.AreEqual(expectedLatitude, response.Results.First().Geometry.Location.Latitude, "Latitude");
            Assert.AreEqual(expectedLongitude, response.Results.First().Geometry.Location.Longitude, "Longitude");
            Assert.AreEqual(expectedLocationType, response.Results.First().Geometry.LocationType, "LocationType");
            Assert.AreEqual(expectedSouthwestLatitude, response.Results.First().Geometry.Viewport.Southwest.Latitude, "Southwest.Latitude");
            Assert.AreEqual(expectedSouthwestLongitude, response.Results.First().Geometry.Viewport.Southwest.Longitude, "Southwest.Longitude");
            Assert.AreEqual(expectedNortheastLatitude, response.Results.First().Geometry.Viewport.Northeast.Latitude, "Northeast.Latitude");
            Assert.AreEqual(expectedNortheastLongitude, response.Results.First().Geometry.Viewport.Northeast.Longitude, "Northeast.Longitude");
        }
Exemplo n.º 3
0
        // the private function that does all the 'hard work' for querying address
        private string getAddressPartByType(string i_Address, AddressType i_AddressType)
        {
            string addressPart = string.Empty;
            var    request     = new GeocodingRequest();

            request.Address = i_Address;
            request.Sensor  = "false";
            var response = GeocodingService.GetResponse(request);

            if (response.Status == ServiceResponseStatus.Ok)
            {
                var components = response.Results[0].Components;
                foreach (AddressComponent addressComponent in components)
                {
                    foreach (AddressType addressType in addressComponent.Types)
                    {
                        if (addressType == i_AddressType)
                        {
                            addressPart = addressComponent.LongName;
                        }
                    }
                }
            }

            return(addressPart);
        }
        /// <summary>
        /// sends a geocode request and returns the response
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        private GeocodingResponse geocodeRequest(string address)
        {
            var request = new GeocodingRequest();

            request.Address = address;
            request.Sensor  = "false";
            return(GeocodingService.GetResponse(request));

            //XmlDocument a = Geocode(addressSearchText.Text);
            //MessageBox.Show(a.ToString());
        }
Exemplo n.º 5
0
        private void searchButton_Click(object sender, RoutedEventArgs e)
        {
            var request = new GeocodingRequest();

            request.Address = searchTextBox.Text;
            request.Sensor  = "false";
            var response = GeocodingService.GetResponse(request);

            if (response.Status == ServiceResponseStatus.Ok)
            {
                resultsTreeView.ItemsSource = response.Results.ToTree();
            }
        }
Exemplo n.º 6
0
        public static GeographicPosition BuscarCoordenadas(string cep, string endereco, string cidade, string estado)
        {
            try
            {
                bool achouCEP  = false;
                var  estrutura = new EstruturaCEP();

                if (!string.IsNullOrEmpty(cep))
                {
                    try
                    {
                        estrutura = BuscarCEP.GetEnderecoEstruturado(cep);
                        achouCEP  = true;
                    }
                    catch (Exception)
                    { }
                }

                if (!achouCEP)
                {
                    if (endereco.Contains("-"))
                    {
                        string[] enderecos = endereco.Split('-');
                        estrutura.Rua = enderecos[0];
                    }
                    else
                    {
                        estrutura.Rua    = endereco;
                        estrutura.Cidade = cidade;
                        estrutura.Estado = estado;
                    }
                }

                var request = new GeocodingRequest();
                request.Address = FormatarEstrutra(estrutura);
                request.Sensor  = "false";
                var response = GeocodingService.GetResponse(request);

                if (response.Status != Google.Api.Maps.Service.ServiceResponseStatus.Ok)
                {
                    throw new Exception("Não foi possível encontrar a sua localização a partir do CEP digitado.");
                }

                return(response.Results[0].Geometry.Location);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 7
0
        public void GetGeocodingWithoutParameters()
        {
            // expectations
            var expectedStatus      = ServiceResponseStatus.RequestDenied;
            var expectedResultCount = 0;

            // test
            var request  = new GeocodingRequest();
            var response = GeocodingService.GetResponse(request);

            // asserts
            Assert.AreEqual(expectedStatus, response.Status);
            Assert.AreEqual(expectedResultCount, response.Results.Count());
        }
Exemplo n.º 8
0
        public void GetGeocodingForAddress()
        {
            // expectations
            var expectedStatus           = ServiceResponseStatus.Ok;
            var expectedResultCount      = 1;
            var expectedType             = AddressType.StreetAddress;
            var expectedFormattedAddress = "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA";
            var expectedComponentTypes   = new AddressType[] {
                AddressType.StreetNumber,
                AddressType.Route,
                AddressType.Locality,
                AddressType.AdministrativeAreaLevel1,
                AddressType.AdministrativeAreaLevel2,
                AddressType.AdministrativeAreaLevel3,
                AddressType.Country,
                AddressType.PostalCode,
                AddressType.Political
            };
            var expectedLatitude           = 37.4230180m;
            var expectedLongitude          = -122.0818530m;
            var expectedLocationType       = LocationType.Rooftop;
            var expectedSouthwestLatitude  = 37.4188514m;
            var expectedSouthwestLongitude = -122.0874526m;
            var expectedNortheastLatitude  = 37.4251466m;
            var expectedNortheastLongitude = -122.0811574m;

            // test
            var request = new GeocodingRequest();

            request.Address = "1600 Amphitheatre Parkway, Mountain View, CA";
            request.Sensor  = "false";
            var response = GeocodingService.GetResponse(request);

            // asserts
            Assert.AreEqual(expectedStatus, response.Status, "Status");
            Assert.AreEqual(expectedResultCount, response.Results.Length, "ResultCount");
            Assert.AreEqual(expectedType, response.Results.Single().Types.First(), "Type");
            Assert.AreEqual(expectedFormattedAddress, response.Results.Single().FormattedAddress, "FormattedAddress");
            Assert.IsTrue(
                expectedComponentTypes.OrderBy(x => x).SequenceEqual(
                    response.Results.Single().Components.SelectMany(y => y.Types).Distinct().OrderBy(z => z)), "Types");
            Assert.AreEqual(expectedLatitude, response.Results.Single().Geometry.Location.Latitude, "Latitude");
            Assert.AreEqual(expectedLongitude, response.Results.Single().Geometry.Location.Longitude, "Longitude");
            Assert.AreEqual(expectedLocationType, response.Results.Single().Geometry.LocationType, "LocationType");
            Assert.AreEqual(expectedSouthwestLatitude, response.Results.Single().Geometry.Viewport.Southwest.Latitude, "Southwest.Latitude");
            Assert.AreEqual(expectedSouthwestLongitude, response.Results.Single().Geometry.Viewport.Southwest.Longitude, "Southwest.Longitude");
            Assert.AreEqual(expectedNortheastLatitude, response.Results.Single().Geometry.Viewport.Northeast.Latitude, "Northeast.Latitude");
            Assert.AreEqual(expectedNortheastLongitude, response.Results.Single().Geometry.Viewport.Northeast.Longitude, "Northeast.Longitude");
        }
Exemplo n.º 9
0
        private void btnSearch_Click(object sender, EventArgs e)
        {
            var request = new GeocodingRequest();

            request.Address = textLocation.Text;
            request.Sensor  = "false";

            var response = GeocodingService.GetResponse(request);

            if (response.Status == ServiceResponseStatus.Ok)
            {
                currentSelectedLocation = response.Results.First();
            }
            updateMap();
        }
Exemplo n.º 10
0
        public static GeographicPosition BuscarCoordenadas(string cep)
        {
            var estrutura = BuscarCEP.GetEnderecoEstruturado(cep);

            var request = new GeocodingRequest();

            request.Address = FormatarEstrutra(estrutura);
            request.Sensor  = "false";
            var response = GeocodingService.GetResponse(request);

            if (response.Status != Google.Api.Maps.Service.ServiceResponseStatus.Ok)
            {
                throw new Exception("Não foi possível encontrar a sua localização a partir do CEP digitado.");
            }

            return(response.Results[0].Geometry.Location);
        }
Exemplo n.º 11
0
        public GeographicPosition GetGeographicPosition(string address)
        {
            var request = new GeocodingRequest();

            request.Address = address;
            request.Sensor  = "false";
            var response = GeocodingService.GetResponse(request);

            if (response != null)
            {
                var result = response.Results.FirstOrDefault();
                if (result != null)
                {
                    return(result.Geometry.Location);
                }
            }
            return(null);
        }
Exemplo n.º 12
0
        public static dynamic GetLatitudeLongitude(string addess)
        {
            Geometry geometry = new Geometry();
            var      request  = new GeocodingRequest();

            request.Address = addess;
            request.Sensor  = "false";
            var response = GeocodingService.GetResponse(request);

            if (response.Status == ServiceResponseStatus.Ok)
            {
                GeocodingResult[] geo = response.Results;
                if (response.Results.Length == 1)
                {
                    geometry = geo[0].Geometry;
                }
            }
            return(geometry);
        }
Exemplo n.º 13
0
        private static Coordinates <double> GetCoordinatesGoogle(string zip)
        {
            if (_googleSearchCountry.Length == 0)
            {
                throw new ArgumentException("Country is empty!", nameof(_googleSearchCountry));
            }

            var request = new GeocodingRequest();

            request.Address = $"{zip}, {_googleSearchCountry}";

            GeocodingService geocodingService = new GeocodingService();
            var response = geocodingService.GetResponse(request);

            if (response.Status != ServiceResponseStatus.Ok)
            {
                return(null);
            }

            if (response.Results.Length != 1)
            {
                return(null);
            }

            var firstResult = response.Results[0];
            var lat         = firstResult.Geometry.Location.Latitude;
            var lng         = firstResult.Geometry.Location.Longitude;

            if (lat < Thresholds.minLat || lat > Thresholds.maxLat ||
                lng < Thresholds.minLng || lng > Thresholds.maxLng)
            {
                Log.WriteLine($"Throwing away {lat}, {lng} because it is not inside of the Threshold");
                return(null);
            }

            var result = new Coordinates <double>
            {
                Lat = lat,
                Lng = lng
            };

            return(result);
        }
Exemplo n.º 14
0
        public GeoLocation GetLatLong(string address)
        {
            GeocodingRequest request = new GeocodingRequest();

            request.Address = address;
            request.Sensor  = false;
            GeocodingService svc = new GeocodingService();
            var response         = svc.GetResponse(request);
            var result           = response.Results.First();

            var longitude = result.Geometry.Location.Longitude;
            var latitude  = result.Geometry.Location.Latitude;
            var addr      = result.FormattedAddress;

            Logger.Debug("Full Address: " + addr);   // "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA"
            Logger.Debug("Latitude: " + latitude);   // 37.4230180
            Logger.Debug("Longitude: " + longitude); // -122.0818530
            var loc = new GeoLocation(longitude, latitude, addr);

            return(loc);
        }
Exemplo n.º 15
0
        private void btnSearch_Click(object sender, EventArgs e)
        {
            //var request = new GeocodingRequest();
            //SpeechRecognizer recognizer = new SpeechRecognizer();
            //recognizer.SpeechRecognized +=
            // new EventHandler<SpeechRecognizedEventArgs>(sre_SpeechRecognized);


            //request.Address = textLocation.Text;
            //request.Address=


            //var response = GeocodingService.GetResponse(request);
            //if (response.Status == ServiceResponseStatus.Ok) {
            //    currentSelectedLocation = response.Results.First();

            //}
            //updateMap();

            var request = new GeocodingRequest();

            //request.Address = list

            //foreach (String lists in list)
            //{
            //    request.Address = lists;
            //    //textLocation.AppendText(" " + lists);
            //}
            request.Address = textLocation.Text;
            request.Sensor  = "false";

            var response = GeocodingService.GetResponse(request);

            if (response.Status == ServiceResponseStatus.Ok)
            {
                currentSelectedLocation = response.Results.First();
            }
            updateMap();
        }
Exemplo n.º 16
0
        public static GeographicPosition BuscarCoordenadas(string cep, string endereco, string cidade, string estado)
        {
            try
            {
                LogUtil.Info(string.Format("##RoboAtzSite.BuscarCoordenadas.Initialize## CEP: {0}", cep));

                var achouCEP  = false;
                var estrutura = new EstruturaCEP();

                if (!string.IsNullOrEmpty(cep))
                {
                    try
                    {
                        LogUtil.Debug(string.Format("##RoboAtzSite.BuscarCoordenadas.IniciandoGetEnderecoEstruturado##"));
                        estrutura = BuscarCEP.GetEnderecoEstruturado(cep);
                        achouCEP  = true;
                    }
                    catch (Exception ex)
                    {
                        LogUtil.Error(string.Format("##RoboAtzSite.BuscarCoordenadas.EXCEPTION## MSG: {0}", ex.Message), ex);
                    }
                }

                if (!achouCEP)
                {
                    if (endereco.Contains("-"))
                    {
                        var enderecos = endereco.Split('-');
                        estrutura.Rua = enderecos[0];
                    }
                    else
                    {
                        estrutura.Rua    = endereco;
                        estrutura.Cidade = cidade;
                        estrutura.Estado = estado;
                    }
                }

                var request = new GeocodingRequest {
                    Address = FormatarEstrutra(estrutura), Sensor = "false"
                };

                LogUtil.Info(string.Format("##RoboAtzSite.BuscarCoordenadas## ENDEREÇO_FORMATADO: {0}, LATITUDE/LONGITUDE: {1}", request.Address, request.LatitudeLongitude));

                var response = GeocodingService.GetResponse(request);

                LogUtil.Info(string.Format("##RoboAtzSite.BuscarCoordenadas## RESPONSE_STATUS_GEOCODING_SERVICE: {0}", response.Status));

                if (response.Status != ServiceResponseStatus.Ok)
                {
                    LogUtil.Info(string.Format("##RoboAtzSite.BuscarCoordenadas.ERROR## MSG: {0}", "Não foi possível encontrar a sua localização a partir do CEP digitado"));
                    throw new Exception("Não foi possível encontrar a sua localização a partir do CEP digitado.");
                }

                LogUtil.Info(string.Format("##RoboAtzSite.BuscarCoordenadas.SUCCESS##"));

                return(response.Results[0].Geometry.Location);
            }
            catch (Exception ex)
            {
                LogUtil.Error(string.Format("##RoboAtzSite.BuscarCoordenadas.EXCEPTION## MSG: {0}", ex.Message), ex);
                return(null);
            }
        }
Exemplo n.º 17
0
        public override IRow Operate(IRow row)
        {
            var query   = row[_input].ToString();
            var request = new GeocodingRequest {
                Components = _componentFilter
            };

            if (query.Contains(" "))
            {
                request.Address = query;
            }
            else
            {
                request.PlaceId = query;
            }

            try {
                var response = _service.GetResponse(request);

                switch (response.Status)
                {
                case ServiceResponseStatus.Ok:
                    var first = response.Results.First();
                    foreach (var field in _output)
                    {
                        switch (field.Name.ToLower())
                        {
                        case "route":
                            var route = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.Route)));
                            if (route != null)
                            {
                                row[field] = route.ShortName;
                            }
                            break;

                        case "streetnumber":
                            var streetNumber = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.StreetNumber)));
                            if (streetNumber != null)
                            {
                                row[field] = streetNumber.ShortName;
                            }
                            break;

                        case "streetaddress":
                            var streetAddress = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.StreetAddress)));
                            if (streetAddress != null)
                            {
                                row[field] = streetAddress.ShortName;
                            }
                            break;

                        case "premise":
                            var premise = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.Premise)));
                            if (premise != null)
                            {
                                row[field] = premise.ShortName;
                            }
                            break;

                        case "subpremise":
                            var subPremise = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.Subpremise)));
                            if (subPremise != null)
                            {
                                row[field] = subPremise.ShortName;
                            }
                            break;

                        case "floor":
                            var floor = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.Floor)));
                            if (floor != null)
                            {
                                row[field] = floor.ShortName;
                            }
                            break;

                        case "room":
                            var room = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.Room)));
                            if (room != null)
                            {
                                row[field] = room.ShortName;
                            }
                            break;

                        case "neighborhood":
                            var neighborhood = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.Neighborhood)));
                            if (neighborhood != null)
                            {
                                row[field] = neighborhood.ShortName;
                            }
                            break;

                        case "partialmatch":
                            row[field] = first.PartialMatch;
                            break;

                        case "lat":
                        case "latitude":
                            row[field] = first.Geometry.Location.Latitude;
                            break;

                        case "type":
                        case "locationtype":
                            row[field] = first.Geometry.LocationType.ToString();
                            break;

                        case "place":
                        case "placeid":
                            row[field] = first.PlaceId;
                            break;

                        case "locality":
                            var locality = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.Locality)));
                            if (locality != null)
                            {
                                row[field] = locality.ShortName;
                            }
                            break;

                        case "political":
                            var political = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.Political)));
                            if (political != null)
                            {
                                row[field] = political.ShortName;
                            }
                            break;

                        case "state":
                        case "administrative_area_level_1":
                            var state = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.AdministrativeAreaLevel1)));
                            if (state != null)
                            {
                                row[field] = state.ShortName;
                            }
                            break;

                        case "county":
                        case "administrative_area_level_2":
                            var county = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.AdministrativeAreaLevel2)));
                            if (county != null)
                            {
                                row[field] = county.ShortName;
                            }
                            break;

                        case "country":
                            var country = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.Country)));
                            if (country != null)
                            {
                                row[field] = country.ShortName;
                            }
                            break;

                        case "zip":
                        case "zipcode":
                        case "postalcode":
                            var zip = first.AddressComponents.FirstOrDefault(ac => ac.Types.Any(t => t.Equals(AddressType.PostalCode)));
                            if (zip != null)
                            {
                                row[field] = zip.ShortName;
                            }
                            break;

                        case "lon":
                        case "long":
                        case "longitude":
                            row[field] = first.Geometry.Location.Longitude;
                            break;

                        case "address":
                        case "formattedaddress":
                            if (field.Equals(_input))
                            {
                                break;
                            }
                            row[field] = first.FormattedAddress;
                            Context.Debug(() => first.FormattedAddress);
                            break;
                        }
                    }
                    break;

                default:
                    Context.Error("Error from Google MAPS API: " + response.Status);
                    break;
                }
            } catch (Exception ex) {
                Context.Error(ex.Message);
            }

            return(row);
        }