public void PitchCityState() { GeocoderSourceDummy dummy = new GeocoderSourceDummy(_config, "DummyProcessorWithConfig"); _typeSelector = new Processors.MatchTypeSelectorProcessor(_config, "MatchTypeSelectorProcessorTest"); _zero = new GeocodeCandidate { MatchType = "US_Zip4" }; _one = new GeocodeCandidate { MatchType = "US_CityState" }; _two = new GeocodeCandidate { MatchType = "US_RoofTops" }; _three = new GeocodeCandidate { MatchType = "US_RoofTops" }; List<GeocodeCandidate> candidates = new List<GeocodeCandidate> { _zero, _one, _two, _three }; _response = new GeocodeResponse(candidates, dummy); _typeSelector.ProcessResponse(_response); Assert.AreEqual(3, _response.Count); Assert.Contains(_zero, _response.Candidates); Assert.Contains(_two, _response.Candidates); Assert.Contains(_three, _response.Candidates); }
public void ProcessResponse(GeocodeResponse response) { if (response.HasCandidates) { response.Candidates.RemoveAll(IsNotAllowedByMatchType); } }
/// <summary> /// Implementations of this method will be used to process a geocode response, to /// weed out low-scoring candidates, for example. /// </summary> /// <param name="response">The response object to be modified.</param> public void ProcessResponse(GeocodeResponse response) { foreach (GeocodeCandidate candidate in response.Candidates) { string fieldVal = (string) _replaceField.GetValue(candidate, null) ?? ""; string thisReplacer = _replaceWith; string[] sourceFieldData = new string[_sourceFields.Length]; for (int i = 0; i < _sourceFields.Length; i++) { sourceFieldData[i] = (string) _sourceFields[i].GetValue(candidate, null); } int l = 0; for (int i = 0; l >= 0; i++ ) { l = thisReplacer.IndexOf('{', l); if (l == -1) { break; } thisReplacer = thisReplacer.Remove(l + 1, thisReplacer.IndexOf('}', l) - l - 1); thisReplacer = thisReplacer.Insert(l + 1, i.ToString()); l++; } thisReplacer = String.Format(thisReplacer, sourceFieldData); fieldVal = Regex.Replace(fieldVal, _matchRegex, thisReplacer); _replaceField.SetValue(candidate, fieldVal, null); } }
/// <exclude/> public static void OutputGeocodeResponses(GeocodeResponse gr) { Console.WriteLine("**************Begin Response*************"); if (gr.HasCandidates) { foreach (GeocodeCandidate gc in gr.Candidates) { Console.WriteLine("Standardized Address: " + gc.StandardizedAddress); Console.WriteLine("Address: " + gc.Address); Console.WriteLine("City: " + gc.City); Console.WriteLine("State: " + gc.State); Console.WriteLine("PostalCode: " + gc.PostalCode); Console.WriteLine("Match Score: " + gc.MatchScore); Console.WriteLine("Match Type: " + gc.MatchType); Console.WriteLine("X,Y: " + gc.Longitude + ", " + gc.Latitude); Console.WriteLine("Additional Data: " + gc.RawData); Regex parsableAddressParts = new Regex(@"^((?<address>\d{1,}(\D|\s1/2)?(?:\s?-\s?\d{1,})*\s(?>[^#,]+)(?>#\s*.+)?),)?\s*((?<zip>\d{5}(-\d{4})?)\s*,)?\s*(?<city>[^,]+)\s*,(\s*(Town Of)\s*,)?\s*(?<state>[A-Z]{2})(\s+(?<zip2>\d{5}(-\d{4})?))?", RegexOptions.IgnoreCase); string address = gc.StandardizedAddress; if (!string.IsNullOrEmpty(address) && parsableAddressParts.IsMatch(address)) { Match m = parsableAddressParts.Match(address); GroupCollection groups = m.Groups; Console.WriteLine("\t" + groups["address"].Value.Trim()); Console.WriteLine("\t" + groups["city"].Value.Trim()); Console.WriteLine("\t" + groups["state"].Value.Trim()); Console.WriteLine("\t" + groups["zip"].Value.Trim()); } Console.WriteLine("**********"); Console.WriteLine(""); } } else { Console.WriteLine("No Responses Received"); } Console.WriteLine("**************End Response*************"); }
public IHttpActionResult PostAlert(Alert alert) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Create new Geocoder and pass GOOGLE_MAPS_API_KEY(in this example it's stored in .config) IGeocoder geocoder = new Geocoder("AIzaSyCyrwDBZYm83nLY6Eg8_ECHRCF-aNQ91eQ"); // Get GeocodeResponse C# object from address or from Latitude Longitude(reverse geocoding) GeocodeResponse reversGeocoderesponse = geocoder.ReverseGeocode(alert.Latitude, alert.Longitude); // You can then query the response to get what you need string address = reversGeocoderesponse.Results[1].FormattedAddress; alert.Address = address; db.Alerts.Add(alert); db.SaveChanges(); return(CreatedAtRoute("DefaultApi", new { id = alert.Id }, alert)); }
public GeocodeLatLng GetLatLng(string location) { string url = string.Format(urltemplategeocodelocation, _key, location); string pagebody = ""; GetWebPage(url, hostgeocode, ref pagebody); GeocodeResponse g = Newtonsoft.Json.JsonConvert.DeserializeObject <GeocodeResponse>(pagebody); GeocodeLatLng latlng = new GeocodeLatLng(); if (g != null && g.results != null && g.results.Length > 0 && g.results[0].locations != null && g.results[0].locations.Length > 0 && g.results[0].locations[0].latLng != null) { latlng = g.results[0].locations[0].latLng; } return(latlng); }
public Geo GetClienteLocalizacao() { try { IGeocoder geocoder = new Geocoder(ChaveGoogle); ObjUsuario.Id = ObjGeo.IdUsr; ObjUsuario = new ManterUsuarioDAO(ObjUsuario).ConsultaUsuarioByIdDAO(); GeocodeResponse response = geocoder.Geocode(ObjUsuario.Endereco); ObjGeo.NomeUsuario = ObjUsuario.Nome; ObjGeo.Endereco = ObjUsuario.Endereco; ObjGeo.Latitude = response.Results[0].Geometry.Location.Lat.ToString().Replace(",", "."); ObjGeo.Longitude = response.Results[0].Geometry.Location.Lng.ToString().Replace(",", "."); return(ObjGeo); } catch (Exception) { throw; } }
private GeocodeResponse GeoCodeData(string address) { try { GeocodeRequest request = new GeocodeRequest(); request.Credentials = new GeocodeService.Credentials(); request.Credentials.ApplicationId = getConfig("BingApiKey"); request.Query = address; ConfidenceFilter[] filters = new ConfidenceFilter[1]; filters[0] = new ConfidenceFilter(); filters[0].MinimumConfidence = GeocodeService.Confidence.High; GeocodeOptions geocodeOptions = new GeocodeOptions(); geocodeOptions.Filters = filters; request.Options = geocodeOptions; GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); GeocodeResponse response = geocodeService.Geocode(request); if (response.Results.Length > 0) { return(response); } } catch { } return(null); }
[InlineData(-33.996379, 18.537121, "South Africa")] // Cape Point public void RandomCoordinate_Next_ShouldGenerateValidCoordinate(double lat, double lng, string country) { Coordinate coordinate = RandomCoordinate.Next(new Coordinate(lat, lng), 1000); Assert.True(coordinate.Latitude >= -90 && coordinate.Latitude <= 90); Assert.True(coordinate.Longitude >= -180 && coordinate.Longitude <= 180); string requestUri = $"https://eu1.locationiq.com/v1/reverse.php" + $"?key={TestSettings.LocationIqKey}" + $"&lat={coordinate.Latitude.ToString(CultureInfo.InvariantCulture)}" + $"&lon={coordinate.Longitude.ToString(CultureInfo.InvariantCulture)}" + $"&format=json"; RestClient client = new(); RestRequest request = new(requestUri, DataFormat.Json); IRestResponse <GeocodeResponse> response = client.Get <GeocodeResponse>(request); GeocodeResponse responseData = response.Data; if (responseData.Address != null) { Assert.True(responseData.Address.Country == country); } }
public PointLatLng Coordenadas(IEndereco IEndereco) { string Logradouro = !string.IsNullOrEmpty(IEndereco.LOGRADOURO) ? string.Format("{0}", IEndereco.LOGRADOURO.TrimStart().TrimEnd().Replace(" ", "+")) : string.Empty; string Numero = !string.IsNullOrEmpty(IEndereco.NUMERO) ? string.Format(",+{0}+", IEndereco.NUMERO.Trim()) : string.Empty; string Bairro = !string.IsNullOrEmpty(IEndereco.BAIRRO) ? string.Format("-+{0}", IEndereco.BAIRRO.TrimStart().TrimEnd().Replace(" ", "+")) : string.Empty; string Municipio = !string.IsNullOrEmpty(IEndereco.MUNICIPIO) ? string.Format(",+{0}+", IEndereco.MUNICIPIO.Replace(" ", "+")) : string.Empty; string UF = !string.IsNullOrEmpty(IEndereco.UF) ? UF = string.Format("-+{0}", IEndereco.UF) : string.Empty; string ADDRESS = Logradouro + Numero + Bairro + Municipio + UF; string url = string.Format("https://maps.googleapis.com/maps/api/geocode/xml?address={0}&key={1}", ADDRESS, "AIzaSyDSDWEGxqXsPOcVbeR8sSts1FJL0j7Fk8w"); GeocodeResponse Response = (GeocodeResponse)CarregaXML_STR(XElement.Load(url).ToString(), typeof(GeocodeResponse)); if (Response.Status == "OK") { return(new PointLatLng() { Lat = Response.Result.Geometry.Location.Lat, Lng = Response.Result.Geometry.Location.Lng, }); } else { return(new PointLatLng()); } }
public Message Buscar(Message msg) { ForwardGeocodeRequest FGR = new ForwardGeocodeRequest(); GeocodeResponse request = new GeocodeResponse(); try { FGR.City = msg.ciudad; FGR.Country = msg.pais; FGR.StreetAddress = msg.calle + " " + msg.numero.ToString(); FGR.County = msg.provincia; ForwardGeocoder FG = new ForwardGeocoder(); Task <GeocodeResponse[]> response = FG.Geocode(FGR); request = response.Result[0]; msg.latitud = request.Latitude; msg.longitud = request.Longitude; } catch (Exception ex) { var error = ex.Message; } return(msg); }
public void PitchCityState() { GeocoderSourceDummy dummy = new GeocoderSourceDummy(_config, "DummyProcessorWithConfig"); _typeSelector = new Processors.MatchTypeSelectorProcessor(_config, "MatchTypeSelectorProcessorTest"); _zero = new GeocodeCandidate { MatchType = "US_Zip4" }; _one = new GeocodeCandidate { MatchType = "US_CityState" }; _two = new GeocodeCandidate { MatchType = "US_RoofTops" }; _three = new GeocodeCandidate { MatchType = "US_RoofTops" }; List <GeocodeCandidate> candidates = new List <GeocodeCandidate> { _zero, _one, _two, _three }; _response = new GeocodeResponse(candidates, dummy); _typeSelector.ProcessResponse(_response); Assert.AreEqual(3, _response.Count); Assert.Contains(_zero, _response.Candidates); Assert.Contains(_two, _response.Candidates); Assert.Contains(_three, _response.Candidates); }
private static List <int> GetRegionId(UserMobileModel value, ref double latitude, ref double longitude) { List <int> listRegiones = new List <int>(); try { string URL = Settings.GoogleMapsAPIURL; string urlParameters = $"?address={value.Address}, Suncheles, Santa Fe, Argentina&sensor=false&key={Settings.GoogleMapsAPIKey}"; HttpClient client = new HttpClient { BaseAddress = new Uri(URL) }; // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); // List data response. HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs. if (response.IsSuccessStatusCode) { XmlSerializer serializer = new XmlSerializer(typeof(GeocodeResponse)); GeocodeResponse resultingMessage = (GeocodeResponse)serializer.Deserialize(new XmlTextReader(response.Content.ReadAsStreamAsync().Result)); if (Settings.IsDev) { latitude = double.Parse(resultingMessage.Result.Geometry.Location.Lat.Replace('.', ',')); longitude = double.Parse(resultingMessage.Result.Geometry.Location.Lng.Replace('.', ',')); } else { latitude = double.Parse(resultingMessage.Result.Geometry.Location.Lat); longitude = double.Parse(resultingMessage.Result.Geometry.Location.Lng); } if (latitude == Settings.ExcludeLatitude && longitude == Settings.ExcludeLongitude) { listRegiones.Clear(); listRegiones.Add(0); return(listRegiones); } //Consulta a la API de AVL la región a la que pertenecen las coordenadas AvlSoapClient avlClient = new AvlSoapClient(); var avlResponse = avlClient.ObtenerRegionesActualesPorCoordenada(6, latitude, longitude); if (avlResponse.Rows.Count > 0) { foreach (DataRow item in avlResponse.Rows) { if (int.TryParse(item.ItemArray[0].ToString(), out int regionId)) { if (item.ItemArray[1].ToString().ToUpper().Contains("RECOLECCI")) { regionId = regionId * 10000; } } listRegiones.Add(regionId); } } } else { listRegiones.Clear(); listRegiones.Add(0); return(listRegiones); } client.Dispose(); } catch (Exception ex) { listRegiones.Clear(); listRegiones.Add(0); return(listRegiones); } return(listRegiones); }
public async Task <WeatherResponse> GetWeatherByCoordinates(double latitude, double longitude, string placeName = "") { using (HttpClient client = new HttpClient()) { client.BaseAddress = _baseUri; string requestUri = CreateRequestUri(latitude, longitude); Forecast forecast = null; try { var result = await client.GetAsync(requestUri); string jsonResult = await result.Content.ReadAsStringAsync(); forecast = JsonConvert.DeserializeObject <Forecast>(jsonResult); } catch (HttpRequestException ex) { Log.Error(ex, "Http request failed"); } // If we don't have the place name, we get it from the mapbox api if (string.IsNullOrWhiteSpace(placeName)) { string apiKey = Environment.GetEnvironmentVariable("MapBoxApiKey"); GeocodingService geocodingService = new GeocodingService(apiKey); GeocodeResponse geocodeResponse = await geocodingService.ReverseGeocodeAsync(latitude, longitude); placeName = geocodeResponse.Features.First().PlaceName; } // Map the values to our own viewmodel, so we can format the values here instead of the browser WeatherResponse response = new WeatherResponse() { Currently = new CurrentlyViewModel() { Location = placeName, Icon = forecast.Currently.Icon.ToString(), Temperature = Math.Round(forecast.Currently.Temperature.Value, 1), Humidity = Math.Round(forecast.Currently.Humidity.Value * 100), DailyHigh = Math.Round(forecast.Daily.Data.First().TemperatureHigh.Value, 1), DailyLow = Math.Round(forecast.Daily.Data.First().TemperatureLow.Value, 1), Summary = forecast.Hourly.Data.First().Summary, TemperatureUnit = 'C' // In the future we might want to allow the user to switch units } }; List <DailyViewModel> mappedDailyForecasts = new List <DailyViewModel>(); // Map the daily forecasts forecast.Daily.Data.ForEach((daily) => { mappedDailyForecasts.Add(new DailyViewModel { Date = daily.DateTime.DateTime, FormattedDateString = daily.DateTime.DateTime.ToString("ddd d MMMM", CultureInfo.InvariantCulture), DailyHigh = Math.Round(daily.TemperatureHigh.Value, 1), DailyLow = Math.Round(daily.TemperatureLow.Value, 1), Humidity = Math.Round(daily.Humidity.Value * 100), Summary = daily.Summary }); }); response.Daily = mappedDailyForecasts; return(response); } }
private ProcessPoint ProcessingRequestResult(ProcessPoint p, GeocodeResponse message) { GoogleEngineStatus status = (GoogleEngineStatus)Enum.Parse(typeof(GoogleEngineStatus), message.status); p.SearchEngine = SearchEngine.Google; Coordinate GeoPoint = null; string formatted_address = string.Empty; if (status == GoogleEngineStatus.OK) { if (message.result.Count() == 1) { GeoPoint = new Coordinate( message.result[0].geometry[0].location[0].lat, message.result[0].geometry[0].location[0].lng); formatted_address = message.result[0].formatted_address; } else { status = GoogleEngineStatus.MORE_ONE_POINT; } } /* Перевизначення точки */ p = new ProcessPoint( p.PointId, p.CardId, p.CrmCustomerId, GeoPoint, p.SourceAddress, formatted_address); p.Type = PointType.CustomerEpicentrK; /* Визначення загального статусу */ switch (status) { case GoogleEngineStatus.INVALID_REQUEST: { p.PStatus = ProcessStatus.ERROR; break; } case GoogleEngineStatus.MORE_ONE_POINT: { p.PStatus = ProcessStatus.MORE_ONE_POINT; break; } case GoogleEngineStatus.OK: { p.PStatus = ProcessStatus.OK; break; } case GoogleEngineStatus.OVER_QUERY_LIMIT: { p.PStatus = ProcessStatus.OVER_QUERY_LIMIT; break; } case GoogleEngineStatus.REQUEST_DENIED: { p.PStatus = ProcessStatus.ERROR; break; } case GoogleEngineStatus.UNKNOWN_ERROR: { p.PStatus = ProcessStatus.ERROR; break; } case GoogleEngineStatus.ZERO_RESULTS: { p.PStatus = ProcessStatus.EMPTY; break; } } /* Запис відповіді пошукової машини */ XmlSerializer serializer = new XmlSerializer(typeof(GeocodeResponse)); using (StringWriter textWriter = new StringWriter()) { serializer.Serialize(textWriter, message); p.Xml = textWriter.ToString(); } return(p); }
public static async Task <LocationInformation> ResolveLocationAsync(double latitude, double longitude) { LocationInformation location = null; GeocodeServiceClient geocodeClient = Helpers.BindingManager.GetGeocodeClient(); ReverseGeocodeRequest geocodeRequest = new ReverseGeocodeRequest(); // Set the credentials using a valid Bing Maps key geocodeRequest.Credentials = new GeocodeService.Credentials(); geocodeRequest.Credentials.ApplicationId = Core.Common.CoreConstants.BingLocationApiKey; // Set the full address query geocodeRequest.Location = new GeocodeService.Location() { Latitude = latitude, Longitude = longitude, }; // Set the options to only return high confidence results List <FilterBase> filters = new List <FilterBase>(); filters.Add(new ConfidenceFilter() { MinimumConfidence = GeocodeService.Confidence.High, }); GeocodeOptions geocodeOptions = new GeocodeOptions(); geocodeOptions.Filters = filters; GeocodeResponse geocodeResponse = await geocodeClient.ReverseGeocodeAsync(geocodeRequest); var result = geocodeResponse.Results.FirstOrDefault(); GeocodeService.Address foundAddress = null; GeocodeService.Location foundLocation = null; if (result != null) { foundAddress = result.Address; foundLocation = result.Locations.FirstOrDefault(); if (foundAddress != null) { location = new LocationInformation() { DisplayName = foundAddress.FormattedAddress, StreetAddress = foundAddress.AddressLine, City = foundAddress.Locality, PostalCode = foundAddress.PostalCode, State = foundAddress.AdminDistrict, County = foundAddress.District, Latitude = (foundLocation == null) ? 0.0 : foundLocation.Latitude, Longitude = (foundLocation == null) ? 0.0 : foundLocation.Longitude, }; } } return(location); }
private void ProcessResponse(GeocodeResponse res) { StringBuilder buffer = new StringBuilder(); int i = 0; IEnumerator enumer = res.GetEnumerator(); while (enumer.MoveNext()) { AddressCandidates responses = (AddressCandidates)enumer.Current; System.Collections.IEnumerator respEnumer = responses.GetEnumerator(); while (respEnumer.MoveNext()) { i +=1; buffer.Append("**** Candidate " + i + " ****\n"); CandidateAddress geoAddr = (CandidateAddress)respEnumer.Current; Address addr = geoAddr.Address; ProcessAddress(addr, buffer); buffer.Append("Coordinates: " + geoAddr.Point.X + " , " + geoAddr.Point.Y); buffer.Append("\n"); buffer.Append("ResponseCode/Match Type :" + geoAddr.GeocodeMatchCode.ResultCode); buffer.Append("\n\n"); } } if (buffer.Length != 0) rtbResults.Text = buffer.ToString(); else rtbResults.Text = "No candidates returned"; }
public ActionResult <FirstAid> SaveForm(FirstAidDTO dto) { FirstAid firstAid = dto; ReverseGeocoder y = new ReverseGeocoder(); var t = new ReverseGeocodeRequest { Latitude = firstAid.latitude, Longitude = firstAid.longitude, PreferredLanguages = "en", }; Task <GeocodeResponse> r2 = y.ReverseGeocode(t); GeocodeResponse resp = r2.Result; firstAid.country = resp.Address.Country; firstAid.NullToDefault(); _context.FirstAid.Add(firstAid); _context.SaveChanges(); var id = _context.FirstAid.OrderByDescending(x => x.id).FirstOrDefault().id; if (id == null) { return(NotFound()); } if (dto.injury != null && dto.injury.Count() > 0) { var injuries = _context.Injury.ToList(); foreach (var injury in dto.injury) { var inj = injuries.FirstOrDefault(x => x.name.Equals(injury)); if (inj != null) { _context.Add(new Fainjury((int)id, inj.id)); } } } if (dto.assistance != null && dto.assistance.Count() > 0) { var assistances = _context.Assistance.ToList(); foreach (var assistance in dto.assistance) { var ass = assistances.FirstOrDefault(x => x.name.Equals(assistance)); if (ass != null) { _context.Add(new Faassistance((int)id, ass.id)); } } } if (dto.phType != null && dto.phType.Count() > 0) { var phTypes = _context.PhType.ToList(); foreach (var phType in dto.phType) { var ph = phTypes.FirstOrDefault(x => x.name.Equals(phType)); if (ph != null) { _context.Add(new FaphType((int)id, ph.id)); } } } _context.SaveChanges(); return(firstAid); }
public static string ToJson(this GeocodeResponse self) => JsonConvert.SerializeObject(self, Converter.Settings);
private static void ObterCoordenadasGeograficas(RegistroOcorrenciaModel item, GeocodeResponse coordenadas) { try { if (coordenadas.status == "OK") { item.Registro.Latitude = coordenadas.result.geometry.location.lat; item.Registro.Latitude = coordenadas.result.geometry.location.lng; } } catch (Exception ex) { item.Registro.Latitude = null; item.Registro.Longitude = null; } }
public void GetGeocodingForAddress2() { // expectations GeocodeResponse expected = new GeocodeResponse() { Status = ServiceResponseStatus.Ok, Results = new Result[] { new Result() { AddressComponents = new AddressComponent[] { MakeAddressComponent("11", "11", AddressType.StreetNumber) , MakeAddressComponent("Wall St", "Wall Street", AddressType.Route) , MakeAddressComponent("Lower Manhattan", "Lower Manhattan", AddressType.Neighborhood, AddressType.Political) , MakeAddressComponent("Manhattan", "Manhattan", AddressType.Sublocality, AddressType.Political) , MakeAddressComponent("New York", "New York", AddressType.Locality, AddressType.Political) , MakeAddressComponent("New York", "New York", AddressType.AdministrativeAreaLevel2, AddressType.Political) , MakeAddressComponent("NY", "New York", AddressType.AdministrativeAreaLevel1, AddressType.Political) , MakeAddressComponent("US", "United States", AddressType.Country, AddressType.Political) } , FormattedAddress = "11 Wall Street, New York, NY 10005, USA" , Geometry = MakeGeometry(LocationType.Rooftop, 40.7068599, -74.0111281 //location , 40.7055109, -74.0124771 //swBound , 40.7082089, -74.0097791) //neBound , Types = new AddressType[] { AddressType.StreetAddress } } } }; // test var request = new GeocodingRequest(); request.Address = "11 Wall Street New York NY 10005"; request.Sensor = false; var actual = new GeocodingService().GetResponse(request); // asserts Assert.AreEqual(expected.Status, actual.Status, "Status"); Assert.AreEqual(expected.Results.Length, actual.Results.Length, "ResultCount"); var expectedResult = expected.Results.First(); var actualResult = actual.Results.First(); Assert.AreEqual(expectedResult.Types, actualResult.Types, "Result.First().Types"); Assert.AreEqual(expectedResult.FormattedAddress, actualResult.FormattedAddress, "Resut.First().FormattedAddress"); //Assert.That(expectedResult.AddressComponents, Is.EquivalentTo(actualResult.AddressComponents)); //Assert.IsTrue( // expectedComponentTypes.OrderBy(x => x).SequenceEqual( // response.Results.Single().AddressComponents.SelectMany(y => y.Types).Distinct().OrderBy(z => z)), "Types"); //tolerance needed when testing doubles //http://stackoverflow.com/questions/4787125/evaluate-if-two-doubles-are-equal-based-on-a-given-precision-not-within-a-certa //double tolerance = GetTolerance(expectedResult.Geometry.Viewport.Southwest.Latitude, 7); //Assert.That(expectedResult.Geometry.Viewport.Southwest, Is.EqualTo(actualResult.Geometry.Viewport.Southwest).Within(latlngTolerance)); //Assert.That(expectedResult.Geometry.Viewport.Southwest, Is.EqualTo(actualResult.Geometry.Viewport.Southwest).Within(0.0000001d)); //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"); }
public void SetUp() { _config = new Config("../../Tests/TestConfig.config", "TestConfig"); GeocoderSourceDummy dummy = new GeocoderSourceDummy(_config, "DummyProcessorWithConfig"); _normalizer = new Processors.ScoreNormalizer(_config, "ScoreNormalizerTest"); _zero = new GeocodeCandidate { MatchType = "Locator0" }; _one = new GeocodeCandidate { MatchType = "Locator1" }; _two = new GeocodeCandidate { MatchType = "Locator2" }; List<GeocodeCandidate> candidates = new List<GeocodeCandidate>{_zero, _one, _two}; _response = new GeocodeResponse(candidates, dummy); }
public void ProcessResponse(GeocodeResponse response) { if (_scoreModifiers.Count > 0 && response.HasCandidates) { DistributeScores(response.Candidates); NormalizeCandidates(response.Candidates); } }
void backgroundWorkerGeocode_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Result is Exception) { propertyGridGeocode.SelectedObject = e.Result; } else { Tuple <GeocodeResponse, DirectionsResponse> result = (Tuple <GeocodeResponse, DirectionsResponse>)e.Result; GeocodeResponse geocode = result.Item1; DirectionsResponse directions = result.Item2; propertyGridGeocode.SelectedObject = geocode; propertyGridDirections.SelectedObject = directions; if (geocode.Results.Count > 0) { Map map = new Map(geocode.Results[0].Geometry.Location.ToString(), zoom: 20); map.Width = pictureBoxMap.Width; map.Height = pictureBoxMap.Height; map.Features.Add(new Marker(geocode.Results[0].Geometry.Location)); Path area = new Path(fillColor: FeatureColor.white, weight: 0); area.Points.Add(geocode.Results[0].Geometry.Bounds.SouthWest); area.Points.Add(geocode.Results[0].Geometry.Bounds.SouthEast); area.Points.Add(geocode.Results[0].Geometry.Bounds.NorthEast); area.Points.Add(geocode.Results[0].Geometry.Bounds.NorthWest); area.Geodesic = true; map.Features.Add(area); Path route = new Path(); if (directions.Routes.Count > 0) { route.Points.Add(directions.Routes[0].Legs[0].StartLocation); foreach (Leg leg in directions.Routes[0].Legs) { foreach (Step step in leg.Steps) { route.Points.Add(step.EndLocation); } } } map.Features.Add(route); map.VisiblePlaces.Add(geocode.Results[0].Geometry.Bounds.SouthWest); map.VisiblePlaces.Add(geocode.Results[0].Geometry.Bounds.NorthEast); map.Generate(); propertyGridMap.SelectedObject = map; pictureBoxMap.Image = map.Image; } treeViewDirections.Nodes.Clear(); foreach (Route route in directions.Routes) { TreeNode nodeRoute = new TreeNode(route.Summary); treeViewDirections.Nodes.Add(nodeRoute); foreach (Leg leg in route.Legs) { TreeNode nodeLeg = new TreeNode("Leg"); nodeRoute.Nodes.Add(nodeLeg); nodeLeg.Nodes.Add(string.Format("{0}({1})", leg.Distance.Text, leg.Distance.Value)); nodeLeg.Nodes.Add(string.Format("{0}({1})", leg.Duration.Text, leg.Duration.Value)); foreach (Step step in leg.Steps) { TreeNode nodeStep = new TreeNode(step.Instructions); nodeLeg.Nodes.Add(nodeStep); nodeStep.Nodes.Add(string.Format("{0}({1})", step.Distance.Text, step.Distance.Value)); nodeStep.Nodes.Add(string.Format("{0}({1})", step.Duration.Text, step.Duration.Value)); } } } } }
/// <summary> /// Retrieve geocode address using Google Api /// </summary> /// <param name="pluginExecutionContext">Execution context</param> /// <param name="organizationService">Organization service</param> /// <param name="tracingService">Tracing service</param> /// <param name="notificationService">Notification service</param> public void ExecuteGeocodeAddress(IPluginExecutionContext pluginExecutionContext, IOrganizationService organizationService, ITracingService tracingService) { //Contains 5 fields (string) for individual parts of an address ParameterCollection InputParameters = pluginExecutionContext.InputParameters; // Contains 2 fields (double) for resultant geolocation ParameterCollection OutputParameters = pluginExecutionContext.OutputParameters; //Contains 1 field (int) for status of previous and this plugin ParameterCollection SharedVariables = pluginExecutionContext.SharedVariables; tracingService.Trace("ExecuteGeocodeAddress started. InputParameters = {0}, OutputParameters = {1}", InputParameters.Count().ToString(), OutputParameters.Count().ToString()); try { // If a plugin earlier in the pipeline has already geocoded successfully, quit if ((double)OutputParameters[LatitudeKey] != 0d || (double)OutputParameters[LongitudeKey] != 0d) { return; } // Get user Lcid if request did not include it int Lcid = (int)InputParameters[LcidKey]; string _address = string.Empty; if (Lcid == 0) { var userSettingsQuery = new QueryExpression("usersettings"); userSettingsQuery.ColumnSet.AddColumns("uilanguageid", "systemuserid"); userSettingsQuery.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, pluginExecutionContext.InitiatingUserId); var userSettings = organizationService.RetrieveMultiple(userSettingsQuery); if (userSettings.Entities.Count > 0) { Lcid = (int)userSettings.Entities[0]["uilanguageid"]; } } // Arrange the address components in a single comma-separated string, according to LCID _address = GisUtility.FormatInternationalAddress(Lcid, (string)InputParameters[Address1Key], (string)InputParameters[PostalCodeKey], (string)InputParameters[CityKey], (string)InputParameters[StateKey], (string)InputParameters[CountryKey]); // Make Geocoding call to Google API WebClient client = new WebClient(); var url = $"https://{GoogleConstants.GoogleApiServer}{GoogleConstants.GoogleGeocodePath}/json?address={_address}&key={GoogleConstants.GoogleApiKey}"; tracingService.Trace($"Calling {url}\n"); string response = client.DownloadString(url); // Post ... tracingService.Trace("Parsing response ...\n"); DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(GeocodeResponse)); // Deserialize response json object objResponse = jsonSerializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(response))); // Get response as an object GeocodeResponse geocodeResponse = objResponse as GeocodeResponse; // Unbox into our data contracted class for response tracingService.Trace("Response Status = " + geocodeResponse.Status + "\n"); if (geocodeResponse.Status != "OK") { throw new ApplicationException($"Server {GoogleConstants.GoogleApiServer} application error (Status {geocodeResponse.Status})."); } tracingService.Trace("Checking geocodeResponse.Result...\n"); if (geocodeResponse.Results != null) { if (geocodeResponse.Results.Count() == 1) { tracingService.Trace("Checking geocodeResponse.Result.Geometry.Location...\n"); if (geocodeResponse.Results.First()?.Geometry?.Location != null) { tracingService.Trace("Setting Latitude, Longitude in OutputParameters...\n"); // update output parameters OutputParameters[LatitudeKey] = geocodeResponse.Results.First().Geometry.Location.Lat; OutputParameters[LongitudeKey] = geocodeResponse.Results.First().Geometry.Location.Lng; } else { throw new ApplicationException($"Server {GoogleConstants.GoogleApiServer} application error (missing Results[0].Geometry.Location)"); } } else { throw new ApplicationException($"Server {GoogleConstants.GoogleApiServer} application error (more than 1 result returned)"); } } else { throw new ApplicationException($"Server {GoogleConstants.GoogleApiServer} application error (missing Results)"); } } catch (Exception ex) { // Signal to subsequent plugins in this message pipeline that geocoding failed here. OutputParameters[LatitudeKey] = 0d; OutputParameters[LongitudeKey] = 0d; //TODO: You may need to decide which caught exceptions will rethrow and which ones will simply signal geocoding did not complete. throw new InvalidPluginExecutionException(string.Format("Geocoding failed at {0} with exception -- {1}: {2}" , GoogleConstants.GoogleApiServer, ex.GetType().ToString(), ex.Message), ex); } }