/// <summary> /// Processes a geocode request to set /// </summary> /// <param name="request">The response object to be modified</param> public GeocodeRequest ProcessRequest(GeocodeRequest request) { GeocodeRequest modifiedRequest = new GeocodeRequest(request); const string leader = "default"; foreach (string key in _configParams.Keys) { if (key.ToLower().StartsWith(leader)) { string name = key.Substring(leader.Length); FieldInfo fi = typeof(GeocodeRequest).GetField(name); if (fi != null) { fi.SetValue(modifiedRequest, _configParams[key]); continue; } PropertyInfo pi = typeof(GeocodeRequest).GetProperty(name); if (pi != null) { pi.SetValue(modifiedRequest, _configParams[key], null); continue; } } } return(modifiedRequest); }
public void TestReplacement() { XmlDocument doc = new XmlDocument(); doc.LoadXml(@" <components> <component name='Geocoder'> <parameter name='DummyGeocoder' value='Azavea.Open.Geocoding.Tests.GeocoderSourceDummy,Azavea.Open.Geocoding' /> </component> <component name='DummyGeocoder'> <parameter name='CandidateTextReplacer' value='Azavea.Open.Geocoding.Processors.CandidateTextReplacer,Azavea.Open.Geocoding' /> </component> <component name='CandidateTextReplacer'> <parameter name='ReplaceField' value='Address' /> <parameter name='Find' value='340' /> <parameter name='ReplaceWith' value='680' /> </component> </components> "); Config gcCfg = new Config("GcConfig", doc); Geocoder gc = new Geocoder(gcCfg, "Geocoder"); GeocodeRequest gReq = new GeocodeRequest(); gReq.Address = "340 N 12th St"; IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates; Assert.AreEqual(1, candidates.Count); Assert.AreEqual("680 N 12th St", candidates[0].Address); }
private GeocodeServices.Location GeocodeAddress(string address) { GeocodeRequest geocodeRequest = new GeocodeRequest(); // Set the credentials using a valid Bing Maps Key geocodeRequest.Credentials = new GeocodeServices.Credentials(); geocodeRequest.Credentials.ApplicationId = "AhjlMbKnHDlgTASkyk750YRs5wR3_1gN2hEz6pahnE7Iiurq_DzrE4hDUgBxrtfN"; // Set the full address query geocodeRequest.Query = address; // Set the options to only return high confidence results ConfidenceFilter[] filters = new ConfidenceFilter[1]; filters[0] = new ConfidenceFilter(); filters[0].MinimumConfidence = GeocodeServices.Confidence.High; GeocodeOptions geocodeOptions = new GeocodeOptions(); geocodeOptions.Filters = filters; geocodeRequest.Options = geocodeOptions; // Make the geocode request GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest); if (geocodeResponse.Results.Length > 0) { if (geocodeResponse.Results[0].Locations.Length > 0) { return(geocodeResponse.Results[0].Locations[0]); } } return(null); }
public static async Task <MEPModel.Location> geocode(String address) { BingMapsRESTToolkit.Location result = null; GeocodeRequest request = new GeocodeRequest() { Query = address, IncludeIso2 = true, IncludeNeighborhood = true, MaxResults = 25, BingMapsKey = Settings1.Default.BingKey }; var response = await ServiceManager.GetResponseAsync(request); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location; //this.searchlocation = //var b = searchlocation.BoundingBox; //myMap.SetView(new Microsoft.Maps.MapControl.WPF.LocationRect(b[0], b[1], b[2], b[3])); } return(new MEPModel.Location(result.Point.Coordinates[0], result.Point.Coordinates[1], result.Address.AddressLine, result.Address.PostalCode, result.Address.Locality, result.Address.CountryRegion)); }
/// <summary> /// Makes the geocode request. /// </summary> /// <param name="a">A.</param> public void MakeGeocodeRequest(Address a) { try { // Set a Bing Maps key before making a request const string KEY = "AkRhgqPR6aujo-xib-KiR8Lt20wsn89GY4R9SP0RA6h4w7QT9mS3kKwYKKxjklfV"; // Set the credentials using a valid Bing Maps key // Set the point to use to find a matching address var geocodeRequest = new GeocodeRequest { Credentials = new Credentials { ApplicationId = KEY }, Address = a, UserProfile = new UserProfile { DeviceType = DeviceType.Mobile } }; // Make the reverse geocode request var geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); geocodeService.GeocodeCompleted += geocodeService_GeocodeCompleted; geocodeService.GeocodeAsync(geocodeRequest); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private static Point GetLocation(string address) { var request = new GeocodeRequest() { Query = address, IncludeIso2 = true, IncludeNeighborhood = true, MaxResults = 5, BingMapsKey = Environment.GetEnvironmentVariable("BingMapsKey") }; var response = request.Execute().Result; if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { var result = response.ResourceSets[0].Resources[0] as Location; return(new Point(result.Point.Coordinates[0], result.Point.Coordinates[1])); } return(new Point(0, 0)); }
public ValidatedAddress ValidateAddress(GeoQuery query) { var request = new GeocodeRequest { BingMapsKey = Startup.BingKey, Query = query.ToString() }; var result = request.Execute().Result; if (result.ResourceSets.Length > 0) { var location = (Location)result.ResourceSets[0].Resources[0]; if (location.Address.Locality.IsNullOrWhiteSpace() || location.Address.AddressLine.IsNullOrWhiteSpace()) { return(new ValidatedAddress { ConfidenceLevel = ConfidenceLevel.None }); } else { return(_mapper.Map <ValidatedAddress>(location)); } } return(new ValidatedAddress { ConfidenceLevel = ConfidenceLevel.None }); }
public void TestRemoval() { XmlDocument doc = new XmlDocument(); doc.LoadXml(@" <components> <component name='Geocoder'> <parameter name='DummyGeocoder' value='Azavea.Open.Geocoding.Tests.GeocoderSourceDummy,Azavea.Open.Geocoding' /> </component> <component name='DummyGeocoder'> <parameter name='SpecialCharacterRemover' value='Azavea.Open.Geocoding.Processors.SpecialCharacterRemover,Azavea.Open.Geocoding' /> </component> <component name='SpecialCharacterRemover'> </component> </components> "); Config gcCfg = new Config("GcConfig", doc); SpecialCharacterRemover remover = new SpecialCharacterRemover(gcCfg, "SpecialCharacterRemoverTest"); GeocodeRequest gReq = new GeocodeRequest(); gReq.Address = "230 No%rtheast @1st$ St."; gReq.City = "O*klahoma? (City)"; gReq.PostalCode = "[73104]"; gReq.State = "OK!"; gReq.Country = "US@"; GeocodeRequest processed = remover.ProcessRequest(gReq); Assert.AreEqual("Oklahoma City", processed.City); Assert.AreEqual("230 Northeast 1st St.", processed.Address); Assert.AreEqual("73104", processed.PostalCode); Assert.AreEqual("OK", processed.State); Assert.AreEqual("US", processed.Country); }
private void GeocodeButton_Click(object sender, RoutedEventArgs e) { GeocodeRequest request = new GeocodeRequest(); request.Query = this.InputBox.Text; this.geocodeProvider.GeocodeAsync(request); }
private async Task <GeocodeResult> GeocodeAddress(string address) { GeocodeResult result = null; using (GeocodeServiceClient client = new GeocodeServiceClient("CustomBinding_IGeocodeService")) { GeocodeRequest request = new GeocodeRequest(); request.Credentials = new Credentials() { ApplicationId = Resources.BingApiKey }; request.Query = address; try { result = client.Geocode(request).Results[0]; } catch (Exception) { await this.interactionService.ShowMessageBox("Sorry", $"Could not find: {this.From}"); } } return(result); }
public static GeocodeRequest CreateReverseGeocodeRequest(string query, string credentials) { var request = new GeocodeRequest(); request.Query = query; request.Credentials = new Microsoft.Maps.MapControl.Credentials() { Token = credentials }; return request; }
public async Task <double[]> GetCoords(Models.Address addressToCode) { //Create a request. var request = new GeocodeRequest() { Address = new SimpleAddress() { AddressLine = addressToCode.Street, Locality = addressToCode.City, AdminDistrict = addressToCode.State, PostalCode = addressToCode.Zip }, BingMapsKey = API_Keys.Bing }; // I Want to check the response, but it appears to be skipping over the steps below. //Process the request by using the ServiceManager. double[] coords = new double[2]; var response = await ServiceManager.GetResponseAsync(request); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { var result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location; coords[0] = result.Point.Coordinates[0]; coords[1] = result.Point.Coordinates[1]; } return(coords); }
private async void ADD_button_ClickAsync(object sender, EventArgs e) { if (querybox.Text != String.Empty) { //получение координат введённой точки var request = new GeocodeRequest() { Query = querybox.Text, IncludeIso2 = true, IncludeNeighborhood = true, MaxResults = 25, BingMapsKey = "AvNYCSU2MmF9vSmTbV_ha_WPAxMroM9r_efIFraDGMZZPqWNjS5Xm7sb_qaVuEJc" }; var response = await ServiceManager.GetResponseAsync(request); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { var longt = (response.ResourceSets[0].Resources[0] as Location).GeocodePoints[0].Coordinates[1]; var lat = (response.ResourceSets[0].Resources[0] as Location).GeocodePoints[0].Coordinates[0]; path.Add(new SimpleWaypoint(lat, longt)); latitudes.Add(lat); longtitudes.Add(longt); pushpins.Add(new ImageryPushpin { Location = new Coordinate(lat, longt) }); inserted.Text += Convert.ToString(lat) + " " + Convert.ToString(longt) + "\n"; querybox.Text = ""; } } }
/// <summary> /// Calls bing maps api to geocode address specified in string parametr. /// </summary> /// <param name="address"></param> /// <param name="handler"></param> public void GeocodeAddress(string address, EventHandler<GeocodeCompletedEventArgs> handler) { //if no address was specified, ignore it if (address == null || address == String.Empty) { return; } GeocodeRequest geocodeRequest = new GeocodeRequest(); // Set the credentials using a valid Bing Maps key geocodeRequest.Credentials = new Credentials(); geocodeRequest.Credentials.ApplicationId = _applicationID; // Set the full address query geocodeRequest.Query = address; // Set the options to only return high confidence results ConfidenceFilter filter = new ConfidenceFilter(); filter.MinimumConfidence = GeocodeService.Confidence.High; ObservableCollection<FilterBase> filtersCol = new ObservableCollection<FilterBase>(); filtersCol.Add(filter); // Add the filters to the options GeocodeOptions geocodeOptions = new GeocodeOptions(); geocodeOptions.Filters = filtersCol; geocodeRequest.Options = geocodeOptions; // Make the geocode request GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); geocodeService.GeocodeCompleted += handler; geocodeService.GeocodeAsync(geocodeRequest); }
public async Task RealCaseJSONGeocodeTest() { ICreateRequestService <GeocodeRequest> requestService = new CreateBasicRequestService <GeocodeRequest>(); requestService.BaseRequest = @"http://maps.googleapis.com/maps/api/geocode/json?"; requestService.Equal = "="; requestService.Separator = "&"; IClientService clientService = new ClientRequestService(); ISerializeService <IntegrationTest.Classes.JSONClasses.GeocodeResponse> serializeService = new SerializeJsonService <IntegrationTest.Classes.JSONClasses.GeocodeResponse>(); IRestService <GeocodeRequest, IntegrationTest.Classes.JSONClasses.GeocodeResponse> restService = new RestService <GeocodeRequest, IntegrationTest.Classes.JSONClasses.GeocodeResponse>( requestService, clientService, serializeService); GeocodeRequest request = new GeocodeRequest() { Address = "Valladolid", Language = "es", Region = "es", Sensor = "false" }; var response = await restService.Get(request); Assert.AreEqual("OK", response.Status); Assert.IsTrue(response.Geocode[0].Geometry.Location.Latitude > 0f); Assert.IsTrue(response.Geocode[0].Geometry.Location.Longitude < 0f); }
// returns a BingMapsRESTToolkit.Coordinate for a address from Bing Geocode. // if no coordinates is found, it returns null private async Task <Coordinate> getLocationFromAddress(string address) { Coordinate addressCoordinates = null; // geocode request helps in coordinates of an address var geocodeRequest = new GeocodeRequest() { Query = address, BingMapsKey = StaticVariables.bingMapSessionKey, IncludeIso2 = true, IncludeNeighborhood = true, }; // BingMapsRestToolkit service manager for rest api call as per request. The response contains the desired information var geocodeLoc = await getBingRESTResponseRequest <BingMapsRESTToolkit.Location>(geocodeRequest); if (geocodeLoc != null && geocodeLoc.Point != null && geocodeLoc.Point.Coordinates != null && geocodeLoc.Point.Coordinates.Length > 0) { addressCoordinates = new Coordinate(geocodeLoc.Point.Coordinates[0], geocodeLoc.Point.Coordinates[1]); } else { setSystemWarningMessagesToSpeechLabel(string.Format(SystemMessages.NOLOCATION_MESSAGE, address)); } return(addressCoordinates); }
/// <summary> /// This is where actual source-specific geocoding happens. It is called internal because /// clients use <code>Geocode</code> which sandwiches this call between pre- and post-processing. /// </summary> /// <param name="geocodeRequest">The request to be geocoded.</param> /// <returns>A <code>GeocodeResponse</code> describing the results of the geocode.</returns> protected override GeocodeResponse InternalGeocode(GeocodeRequest geocodeRequest) { const string baseGoogleGeocodeUrl = @"https://maps.googleapis.com/maps/api/geocode/xml"; // For the address, either use the address field or the text string, // depending on which one has a value. Then, add each following address // part, one by one, if it has a value. string address = (!String.IsNullOrEmpty(geocodeRequest.TextString) ? geocodeRequest.TextString : geocodeRequest.Address) + (!String.IsNullOrEmpty(geocodeRequest.City) ? (", " + geocodeRequest.City) : "") + (!String.IsNullOrEmpty(geocodeRequest.State) ? (", " + geocodeRequest.State) : "") + (!String.IsNullOrEmpty(geocodeRequest.PostalCode) ? (" " + geocodeRequest.PostalCode) : "") + (!String.IsNullOrEmpty(geocodeRequest.Country) ? (", " + geocodeRequest.Country) : ""); // add oe=utf-8 here for returning valid utf-8, not iso-8859-1 string googleGeocodeUrl = baseGoogleGeocodeUrl + "?address=" + HttpUtility.UrlEncode(address) + "&sensor=false" + "&key=" + _authKey; string response = InternetSourceUtil.GetRawHTMLFromURL(googleGeocodeUrl); var responseList = XMLList2GeocodeCandidates(response); return(new GeocodeResponse(responseList, this)); }
public void TestReplacementWithExpansion() { XmlDocument doc = new XmlDocument(); doc.LoadXml(@" <components> <component name='Geocoder'> <parameter name='DummyGeocoder' value='Azavea.Open.Geocoding.Tests.GeocoderSourceDummy,Azavea.Open.Geocoding' /> </component> <component name='DummyGeocoder'> <parameter name='CandidateTextReplacer' value='Azavea.Open.Geocoding.Processors.CandidateTextReplacer,Azavea.Open.Geocoding' /> </component> <component name='CandidateTextReplacer'> <parameter name='ReplaceField' value='StandardizedAddress' /> <parameter name='Find' value='^' /> <parameter name='ReplaceWith' value='{Address}, {PostalCode}, {Country}' /> </component> </components> "); Config gcCfg = new Config("GcConfig", doc); Geocoder gc = new Geocoder(gcCfg, "Geocoder"); GeocodeRequest gReq = new GeocodeRequest(); gReq.Address = "340 N 12th St"; IList <GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates; Assert.AreEqual(1, candidates.Count); Assert.AreEqual("340 N 12th St, 19107, USA", candidates[0].StandardizedAddress); }
public async void SearchAddressMap(String query) { var request = new GeocodeRequest() { Query = query, IncludeIso2 = true, IncludeNeighborhood = true, MaxResults = 25, BingMapsKey = "Akg1Bxeo9S0_umkUKYCmip6n0g37vn12fuoNW8ZKJfbGbBYaW8ngs1HCEzcVRs83" }; //Process the request by using the ServiceManager. var response = await ServiceManager.GetResponseAsync(request); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { var result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location; AddPin(new Microsoft.Maps.MapControl.WPF.Location(result.Point.GetCoordinate().Latitude, result.Point.GetCoordinate().Longitude), "", Colors.Blue); } }
public void TestRemovalWithConfig() { XmlDocument doc = new XmlDocument(); doc.LoadXml(@" <components> <component name='Geocoder'> <parameter name='DummyGeocoder' value='Azavea.Open.Geocoding.Tests.GeocoderSourceDummy,Azavea.Open.Geocoding' /> </component> <component name='DummyGeocoder'> <parameter name='SpecialCharacterRemover' value='Azavea.Open.Geocoding.Processors.SpecialCharacterRemover,Azavea.Open.Geocoding' /> </component> <component name='SpecialCharacterRemover'> <parameter name='CharactersToRemove' value='|' /> </component> </components> "); Config gcCfg = new Config("GcConfig", doc); SpecialCharacterRemover remover = new SpecialCharacterRemover(gcCfg, "SpecialCharacterRemover"); GeocodeRequest gReq = new GeocodeRequest(); gReq.TextString = "14th @ Impossible | Philadelphia | PA | 19107"; GeocodeRequest processed = remover.ProcessRequest(gReq); Assert.AreEqual("14th @ Impossible Philadelphia PA 19107", processed.TextString); }
private static Coordinates GeocodeLocation(string address) { Coordinates coordinates = new Coordinates(); IGeocodeRequest geocodeRequest = new GeocodeRequest(address); GoogleGeocoderV3 geocodeService = new GoogleGeocoderV3(); var geocodeResponse = geocodeService.Geocode(geocodeRequest); Thread.Sleep(500); if (geocodeResponse.Success) { coordinates.Latitude = (float)geocodeResponse.Lat; coordinates.Longitude = (float)geocodeResponse.Long; coordinates.StatusMessage = String.Format("Successfully geocoded {0}", address); coordinates.GeocodeSuccess = true; return(coordinates); } else { coordinates.GeocodeSuccess = false; coordinates.StatusMessage = String.Format("FAILED to geocode {0}. Response: {1}", address, geocodeResponse.ErrorMessage); return(coordinates); } }
// convert address to lat/lon public MyWaypoint Geocode(string address) { GeocodeRequest locationRequest = new GeocodeRequest(); // Set the credentials using a valid Bing Maps key locationRequest.Credentials = new BingGeocodeService.Credentials(); locationRequest.Credentials.ApplicationId = m_bingMapKey; locationRequest.Query = address; // Make the calculate route request GeocodeServiceClient geocodeService = new BingGeocodeService.GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); GeocodeResponse geocodeResponse = geocodeService.Geocode(locationRequest); MyWaypoint returnPoint = new MyWaypoint(); if (geocodeResponse.Results.Length > 0) { returnPoint.Latitude = geocodeResponse.Results[0].Locations[0].Latitude; returnPoint.Longitude = geocodeResponse.Results[0].Locations[0].Longitude; //returnPoint.Altitude = GetAltitude(returnPoint.Latitude, returnPoint.Longitude); returnPoint.Altitude = 0.0; } return(returnPoint); }
public Location GeocodeAddress(string address) { address = "Av. Brigadeiro Faria Lima, 2170 São José dos Campos SP 12227-000"; var bingMapApiKey = ConfigurationManager.AppSettings["BingMapCredentials"]; if (!string.IsNullOrEmpty(bingMapApiKey)) { var geocodeRequest = new GeocodeRequest { Credentials = new Credentials { ApplicationId = bingMapApiKey }, Query = address }; // Set the options to only return high confidence results //var filters = new ConfidenceFilter[1]; //filters[0] = new ConfidenceFilter { MinimumConfidence = Confidence.High }; //var geocodeOptions = new GeocodeOptions { Filters = filters }; //geocodeRequest.Options = geocodeOptions; // Make the geocode request var binding = new BasicHttpBinding(); var endpointAddress = new EndpointAddress( "http://dev.virtualearth.net/webservices/v1/geocodeservice/GeocodeService.svc?wsdl"); //var geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); var geocodeService = new GeocodeServiceClient(binding, endpointAddress); var geocodeResponse = geocodeService.Geocode(geocodeRequest); if (geocodeResponse.Results.Length > 0) { if (geocodeResponse.Results[0].Locations.Length > 0) { return geocodeResponse.Results[0].Locations[0]; } } } return null; }
private async void aser(GeocodeRequest request) { //Process the request by using the ServiceManager. var response = await ServiceManager.GetResponseAsync(request); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { var result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location; Microsoft.Maps.MapControl.WPF.Location location = new Microsoft.Maps.MapControl.WPF.Location(); location.Longitude = result.Point.Coordinates[1]; location.Latitude = result.Point.Coordinates[0]; Pushpin pushpin = new Pushpin(); pushpin.Location = location; mMap.Children.Add(pushpin); ////mMap.SetView(location, 14); } }
/// <summary> /// This is where actual source-specific geocoding happens. It is called internal because /// clients use <code>Geocode</code> which sandwiches this call between pre- and post-processing. /// </summary> /// <param name="request">The request to be geocoded.</param> /// <returns>A <code>GeocodeResponse</code> describing the results of the geocode.</returns> protected override GeocodeResponse InternalGeocode(GeocodeRequest request) { string geocodeURL; if (_username.Length > 0) //authenticated access { geocodeURL = "http://" + _username + ":" + _password + "@geocoder.us/member/service/namedcsv/geocode?address="; } else //non-authenticated access { geocodeURL = "http://geocoder.us/service/namedcsv/geocode?address="; } string queryString; if (!string.IsNullOrEmpty(request.TextString)) { queryString = request.TextString; } else { queryString = request.Address + ", " + request.City + ", " + request.State + " " + request.PostalCode + ", " + request.Country; } //Geocoder US doesn't understand '&' queryString = queryString.Replace("&", " and "); queryString = HttpUtility.UrlEncode(queryString); string response = InternetSourceUtil.GetRawTextFromURL(geocodeURL + queryString); IList <GeocodeCandidate> responseList = CSVList2GeocodeCandidates(response); return(new GeocodeResponse(responseList, this)); }
public void LocationForAddress(string addressString, GeoCoordinate searchNearLocation, object callerState) { GeocodeRequest request = new GeocodeRequest(); request.Credentials = new dev.virtualearth.net.webservices.v1.common.Credentials() { ApplicationId = bingMapsApiKey }; request.Query = addressString; request.UserProfile = new UserProfile() { CurrentLocation = new UserLocation() { Latitude = searchNearLocation.Latitude, Longitude = searchNearLocation.Longitude }, DistanceUnit = DistanceUnit.Mile, DeviceType = DeviceType.Mobile, ScreenSize = new SizeOfint() { Width = 480, Height = 700 } }; GeocodeState state = new GeocodeState() { Query = addressString, SearchNearLocation = searchNearLocation, CallerState = callerState }; geocodeService.GeocodeAsync(request, state); }
//Gebaseerd op adres, stad en postcode returned deze methode een SimpleWaypoint van die plek in longtitude en latitude public async Task <SimpleWaypoint> AdressToCoor(string street, int houseNumber, string city, string postalCode) { GeocodeRequest geocode = new GeocodeRequest(); SimpleAddress address = new SimpleAddress(); address.AddressLine = street + houseNumber; address.Locality = city; address.PostalCode = postalCode; geocode.Address = address; geocode.BingMapsKey = bingMapKey; var response = await geocode.Execute(); if (response != null && response.ResourceSets != null && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources != null && response.ResourceSets[0].Resources.Length > 0) { Location result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location; SimpleWaypoint waypoint = new SimpleWaypoint(result.GeocodePoints[1].Coordinates[0], result.GeocodePoints[1].Coordinates[1]); return(waypoint); } return(null); }
public async Task <GeoInfo> QueryGeoInfoByLocation(string location) { GeoInfo info = null; var request = new GeocodeRequest() { Query = location, IncludeIso2 = false, IncludeNeighborhood = false, MaxResults = 1, BingMapsKey = _bingMapKey }; var response = await BingMapsRESTToolkit.ServiceManager.GetResponseAsync(request); if (response.StatusCode == 200 && response.ResourceSets.Length > 0 && response.ResourceSets[0].Resources.Length > 0) { info = new GeoInfo { Location = location, Latitude = 0, Longitude = 0 }; var result = response.ResourceSets[0].Resources[0] as Location; if (result.Point.Coordinates.Length >= 2) { info.Latitude = result.Point.Coordinates[0]; info.Longitude = result.Point.Coordinates[1]; } } return(info); }
private GeocodeServices.Location GeocodeAddress(string address) { GeocodeRequest geocodeRequest = new GeocodeRequest(); // Set the credentials using a valid Bing Maps Key geocodeRequest.Credentials = new GeocodeServices.Credentials(); geocodeRequest.Credentials.ApplicationId = "7Xe5dWLJW6JIhH6jDYR7~6wrgqqAAstaYhxwKEyAB6g~AhB0MhPMBgrTWhG-cxBqbFxaJe92xk7oGVnJPfBckupM4wWTauJQIMkjs5Fs_Z5u"; // Set the full address query geocodeRequest.Query = address; // Set the options to only return high confidence results ConfidenceFilter[] filters = new ConfidenceFilter[1]; filters[0] = new ConfidenceFilter(); filters[0].MinimumConfidence = GeocodeServices.Confidence.High; GeocodeOptions geocodeOptions = new GeocodeOptions(); geocodeOptions.Filters = filters; geocodeRequest.Options = geocodeOptions; // Make the geocode request GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest); if (geocodeResponse.Results.Length > 0) { if (geocodeResponse.Results[0].Locations.Length > 0) { return(geocodeResponse.Results[0].Locations[0]); } } return(null); }
public async Task Test_SerializationAsync() { // Get the client. IGeocodingClient client = Fixture.GetRequiredService <IGeocodingClient>(); // Set up the request. var request = new GeocodeRequest( "1600 Pennsylvania Avenue, Washington D.C., United States" ); // Make the request. var results = await client .GeocodeAsync(request, default) .ConfigureAwait(false); // Create the container. var expected = new Container <GeocodeResponse> { Value = results }; // Serialize to a string. string json = JsonSerializer.Serialize(expected); // Serialize again. var actual = JsonSerializer.Deserialize <Container <GeocodeResponse> >(json); // Compare. Assert.Equal(expected.Value.Status, actual.Value.Status); Assert.Equal(expected.Value.Results.Count, actual.Value.Results.Count); }
private GeocodeService.Location GeocodeAddress(string address) { GeocodeRequest geocodeRequest = new GeocodeRequest(); // Set the credentials using a valid Bing Maps Key geocodeRequest.Credentials = new GeocodeService.Credentials(); geocodeRequest.Credentials.ApplicationId = "AjKX5fPclkvH3YTYhLImWMour1KISHMrcFVBrXzVsjqwMLiWobOq83esCN1ra0Q0"; // Set the full address query geocodeRequest.Query = address; // Set the options to only return high confidence results ConfidenceFilter[] filters = new ConfidenceFilter[1]; filters[0] = new ConfidenceFilter(); filters[0].MinimumConfidence = GeocodeService.Confidence.High; GeocodeOptions geocodeOptions = new GeocodeOptions(); geocodeOptions.Filters = filters; geocodeRequest.Options = geocodeOptions; // Make the geocode request GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest); if (geocodeResponse.Results.Length > 0) { if (geocodeResponse.Results[0].Locations.Length > 0) { return(geocodeResponse.Results[0].Locations[0]); } } return(null); }
// UPDATED (old method left commented out below updated method) // convert Bing address to lat/lon public MyWaypoint Geocode(string address) { //MessageBox.Show($"Geocode method called for !! {address} "); // FOR DEBUGGING PURPOSES // create the Geocode request GeocodeRequest locationRequest = new GeocodeRequest { BingMapsKey = m_bingMapKey, MaxResults = 1, IncludeNeighborhood = true, IncludeIso2 = true, Query = address }; //MessageBox.Show("About to execute location request!");// FOR DEBUGGING PURPOSES // execute the response // this call can also use await, but then method would have to be made async Response geocodeResponse = locationRequest.Execute().Result; //MessageBox.Show("Executed location Request!");// FOR DEBUGGING PURPOSES // set lat/lon/altitude of waypoint and return waypoint MyWaypoint returnPoint = new MyWaypoint(); if (geocodeResponse.ResourceSets.Length > 0) { var result = geocodeResponse.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location; returnPoint.Latitude = result.Point.Coordinates[0]; returnPoint.Longitude = result.Point.Coordinates[1]; returnPoint.Altitude = 0.0; } //MessageBox.Show("Geocode method done!");// FOR DEBUGGING PURPOSES return(returnPoint); }
public string GetLocation(string address) { string results = String.Empty; string key = "AjRSkj6c-Oa0lhoApMZyta1qOzss1RFEgXKFaCfwvXAaKoqzbKMWmiTE9z6-S-Xa"; string uri = "http://dev.virtualearth.net/REST/v1/Locations?query=" + address + "&key=" + key; var request = new GeocodeRequest { BingMapsKey = key, Query = address }; Response response = Task.Run(() => ServiceManager.GetResponseAsync(request)).Result; Location location = response.ResourceSets[0].Resources.FirstOrDefault() as Location; if (location != null) { var coor = location.GeocodePoints.FirstOrDefault().GetCoordinate(); results = String.Format("Success: {0}:{1}", coor.Latitude, coor.Longitude); } else { results = "No Results Found"; } return(results); }
/// <summary> /// Запрос на получения координаты кинотеатра /// </summary> /// <param name="address"></param> private async void GetAddress(string address) { using (GeocodeServiceClient client = new GeocodeServiceClient("CustomBinding_IGeocodeService")) { var request = new GeocodeRequest { Credentials = new Credentials() { ApplicationId = (App.Current.Resources["MyCredentials"] as ApplicationIdCredentialsProvider).ApplicationId }, Culture = "ru", Query = AddressCinema, }; var filters = new ConfidenceFilter[1]; filters[0] = new ConfidenceFilter { MinimumConfidence = Confidence.High }; var geocodeOptions = new GeocodeOptions { Filters = filters }; request.Options = geocodeOptions; GeocodeResponse = await client.GeocodeAsync(request); } }
public GeoLocation.BusinessEntities.Location GeoLocate(GeoLocation.BusinessEntities.Address address) { GeoLocation.BusinessEntities.Location result = new GeoLocation.BusinessEntities.Location(); GeocodeRequest innerRequest = new GeocodeRequest(); innerRequest.Address = new Address() { AddressLine = address.AddressLine, AdminDistrict = address.AdminDistrict, CountryRegion = address.CountryRegion, District = address.District, FormattedAddress = address.FormattedAddress, Locality = address.Locality, PostalCode = address.PostalCode, PostalTown = address.PostalTown }; GeocodeRequest1 request = new GeocodeRequest1(innerRequest); GeocodeResponse1 response = this.proxy.Geocode(request); GeocodeResponse innerResponse = response.GeocodeResult; if (innerResponse.Results != null && innerResponse.Results.Count > 0 && innerResponse.Results[0].Locations != null && innerResponse.Results[0].Locations.Count > 0) { result.Latitude = (decimal)innerResponse.Results[0].Locations[0].Latitude; result.Longitude = (decimal)innerResponse.Results[0].Locations[0].Longitude; } return result; }
public void TestGeocoderUSIntersection() { Console.WriteLine("Test - Geocoder US geocoder, Intersection"); GeocodeRequest gr = new GeocodeRequest(); gr.TextString = "Main & N. Winooski, Burlington, VT"; GeocodeResponse gRes = _geocoderUS.Geocode(gr); TestUtils.OutputGeocodeResponses(gRes); }
public void TestGeocoderUSAmbiguousAddress() { Console.WriteLine("Test - Geocoder US geocoder, Ambiguous Address"); GeocodeRequest gr = new GeocodeRequest(); gr.TextString = "340 12th St., Philadelphia,PA, 19107"; GeocodeResponse gRes = _geocoderUS.Geocode(gr); TestUtils.OutputGeocodeResponses(gRes); }
public void TestGoogleGeocoderAmbiguousAddress() { Console.WriteLine("Test - Google Geocoder, Ambiguous Address"); GeocodeRequest gr = new GeocodeRequest(); gr.TextString = "212 1st ave, Philadelphia, PA"; GeocodeResponse gRes = _googleGeocoder.Geocode(gr); TestUtils.OutputGeocodeResponses(gRes); }
public void TestGoogleGeocoderAmpersandInAddress() { GeocodeRequest gr = new GeocodeRequest(); gr.TextString = "15th & Tasker Sts, Philadelphia, PA"; GeocodeResponse gRes = _googleGeocoder.Geocode(gr); TestUtils.OutputGeocodeResponses(gRes); Assert.AreEqual(1, gRes.Candidates.Count); Assert.AreEqual("Tasker St & S 15th St, Philadelphia, PA 19146, USA", gRes.Candidates[0].StandardizedAddress, "Geocoder found wrong intersection"); }
public void TestGoogleGeocoderAmpersandInAddress2() { GeocodeRequest gr = new GeocodeRequest(); gr.TextString = "21st & Cherry Sts, Philadelphia, PA"; GeocodeResponse gRes = _googleGeocoder.Geocode(gr); TestUtils.OutputGeocodeResponses(gRes); Assert.AreEqual(1, gRes.Candidates.Count); Assert.AreEqual("North 21st Street & Cherry Street, Philadelphia, PA 19103, USA", gRes.Candidates[0].StandardizedAddress, "Geocoder found wrong intersection"); }
/// <summary> /// Implementations of this method will be used to process a geocode request, to /// chunk a text address into its individua parts, for example. /// </summary> /// <param name="request">The response object to be modified.</param> public GeocodeRequest ProcessRequest(GeocodeRequest request) { // If the country list doesn't have this request's country, return an empty request if (request.Country != null && !_myCountries.Contains(request.Country.ToUpper())) { return new GeocodeRequest(); } // Else return the original request for geocoding return request; }
public void TestLoadDummyGeocoder() { Config dummyConfig = new Config("../../Tests/TestConfig.config", "TestConfig"); Geocoder gc = new Geocoder(dummyConfig); GeocodeRequest gReq = new GeocodeRequest(); gReq.Address = "340 N 12th St"; IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates; Assert.AreEqual(1, candidates.Count); }
public void TestLoadDummyGeocoderWithProcessorWithConfig() { Config dummyConfig = new Config("../../Tests/TestConfig.config", "TestConfig"); Geocoder gc = new Geocoder(dummyConfig, "GeocoderSourcesWithProcessorsWithConfigs"); GeocodeRequest gReq = new GeocodeRequest(); gReq.Address = "tS ht21 N 043"; IList<GeocodeCandidate> candidates = gc.Geocode(gReq).Candidates; Assert.AreEqual(1, candidates.Count); }
/// <summary> /// This prcoess will remove the desired characters from the address /// fields of a GeocodeRequest. /// </summary> public GeocodeRequest ProcessRequest(GeocodeRequest request) { GeocodeRequest copy = new GeocodeRequest(request); copy.TextString = RemoveSpecialCharacters(copy.TextString); copy.Address = RemoveSpecialCharacters(copy.Address); copy.City = RemoveSpecialCharacters(copy.City); copy.State = RemoveSpecialCharacters(copy.State); copy.PostalCode = RemoveSpecialCharacters(copy.PostalCode); copy.Country = RemoveSpecialCharacters(copy.Country); return copy; }
public void TestGeocoderUSInvoke() { Console.WriteLine("Test - GeocoderUS Invoke"); GeocodeRequest gr = new GeocodeRequest(); gr.Address = "1 Main st."; gr.City = "Burlington"; gr.State = "VT"; gr.PostalCode = "05401"; GeocodeResponse gRes = _geocoderUS.Geocode(gr); TestUtils.OutputGeocodeResponses(gRes); Assert.IsTrue(gRes.HasCandidates, "Geocoder US geocoder returned no responses"); }
/// <exclude/> protected override GeocodeResponse InternalGeocode(GeocodeRequest request) { if (request.Address == "340 N 12th St") { GeocodeCandidate c = new GeocodeCandidate(); c.Latitude = 238554; c.Longitude = 2694727; c.Address = request.Address; c.PostalCode = "19107"; c.Country = "USA"; return new GeocodeResponse(new[] {c}, this); } return new GeocodeResponse(new GeocodeCandidate[] {}, this); }
/// <exclude /> public GeocodeRequest ProcessRequest(GeocodeRequest request) { GeocodeRequest modifiedRequest = new GeocodeRequest(request); // This dummy preprocessor just reverses the address text. Very sneaky. StringBuilder sb = new StringBuilder(); for (int i = request.Address.Length - 1; i >= 0; i--) { sb.Append(request.Address[i]); } modifiedRequest.Address = sb.ToString(); return modifiedRequest; }
private BitmapImage GetMap(string address) { var geocodeClient = ServiceLocator.Current.GetInstance<IGeocodeService>(); var geocodeRequest = new GeocodeRequest() { Credentials = new Bing.Maps.GeocodeService.Credentials() { ApplicationId = Settings.Default.BingMapsKey }, Query = address }; var geocodeResponse = geocodeClient.Geocode(geocodeRequest); var imageryClient = ServiceLocator.Current.GetInstance<IImageryService>(); var imageryRequest = new MapUriRequest() { Credentials = new Bing.Maps.ImageryService.Credentials() { ApplicationId = Settings.Default.BingMapsKey }, Center = new Bing.Maps.ImageryService.Location() { Latitude = geocodeResponse.Results[0].Locations[0].Latitude, Longitude = geocodeResponse.Results[0].Locations[0].Longitude }, Options = new MapUriOptions() { Style = MapStyle.AerialWithLabels, ZoomLevel = 17, ImageSize = new Bing.Maps.ImageryService.SizeOfint() { Height = 512, Width = 512 } } }; var mapUriResponse = imageryClient.GetMapUri(imageryRequest); return new BitmapImage(new Uri(mapUriResponse.Uri), new RequestCachePolicy(RequestCacheLevel.BypassCache)); }
public string GeocodeAddress( string address ) { try { string results = ""; string key = "AplxUm9o3hkw6qCXBbp61H7HYlDrz-qz8ldgKLJ8Udjd8MFNJAfxxy2IWrfd4bw8"; GeocodeRequest geocodeRequest = new GeocodeRequest(); // Set the credentials using a valid Bing Maps key geocodeRequest.Credentials = new GeocodeService.Credentials(); geocodeRequest.Credentials.ApplicationId = key; // Set the full address query geocodeRequest.Query = address; // Set the options to only return high confidence results ConfidenceFilter[] filters = new ConfidenceFilter[1]; filters[0] = new ConfidenceFilter(); filters[0].MinimumConfidence = GeocodeService.Confidence.Medium; // Add the filters to the options GeocodeOptions geocodeOptions = new GeocodeOptions(); geocodeOptions.Filters = filters; geocodeRequest.Options = geocodeOptions; // Make the geocode request GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest); if (geocodeResponse.Results.Length > 0) { Latitude = geocodeResponse.Results[0].Locations[0].Latitude; Longitude = geocodeResponse.Results[0].Locations[0].Longitude; results = String.Format("Latitude: {0}\nLongitude: {1}", Latitude, Longitude); } else { results = "No Results Found"; } return results; } catch (Exception ex) { return ex.Message; } }
public static geoResponse geocodeAddress(string address) { geoResponse results = new geoResponse(); results.message = "No Results Found"; results.status = "fail"; if (!string.IsNullOrEmpty(address.Trim())) { // get key from configuration string key = "ApjKKP3xo-UePHYy4EWVj7kzRUAx40rbKSGGCzw-E_jK2YAtyhs5Na0_PunRgr2Y"; GeocodeRequest geocodeRequest = new GeocodeRequest(); // Set the credentials using a valid Bing Maps key geocodeRequest.Credentials = new bingMapGeocodeService.Credentials(); geocodeRequest.Credentials.ApplicationId = key; // Set the full address query geocodeRequest.Query = address; // Set the options to only return high confidence results ConfidenceFilter[] filters = new ConfidenceFilter[1]; filters[0] = new ConfidenceFilter(); filters[0].MinimumConfidence = bingMapGeocodeService.Confidence.High; // Add the filters to the options GeocodeOptions geocodeOptions = new GeocodeOptions(); geocodeOptions.Filters = filters; geocodeRequest.Options = geocodeOptions; // Make the geocode request GeocodeServiceClient geocodeService = new GeocodeServiceClient(); GeocodeResponse geocodeResponse = geocodeService.Geocode(geocodeRequest); if (geocodeResponse.Results.Length > 0) { results.latitude = geocodeResponse.Results[0].Locations[0].Latitude.ToString(); results.longitude = geocodeResponse.Results[0].Locations[0].Longitude.ToString(); results.status = "ok"; } } return results; }
public void SplitCrossStreets1() { const string address = "12th St and Callowhill St, Philadelphia, PA, USA"; GeocodeRequest req = new GeocodeRequest(); req.TextString = address; Config config = new Config("../../Tests/TestConfig.config", "TestConfig"); Processors.AddressSplitter splitter = new Processors.AddressSplitter(config, "AddressSplitterTest"); req = splitter.ProcessRequest(req); Assert.AreEqual("12th St & Callowhill St", req.Address, "Test address doesn't match."); Assert.AreEqual("Philadelphia", req.City, "Test city doesn't match."); Assert.AreEqual("PA", req.State, "Test state doesn't match."); Assert.AreEqual("USA", req.Country, "Test country doesn't match."); }
/// <summary> /// Verifie les coordonnées géographiques d'un rendez-vous du Calendrier /// </summary> /// <param name="appointment">Rendez-vous</param> /// <remarks>Abonnez vous d'abord à l'évènement LocationChecked avant l'appel de cette méthode</remarks> public void CheckLocationAsync(Appointment appointment) { //Procédure de connexion et préparation de la requete GeocodeRequest request = new GeocodeRequest() { Credentials = new Credentials { ApplicationId = BingMapCredential.CREDENTIAL } }; if (appointment.Location == null) return; request.Query = appointment.Location; GeocodeServiceClient service = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); //Lorsque bing map nous envoie une réponse service.GeocodeCompleted += (o, e) => { Appointment a = e.UserState as Appointment; LocationCheckedEventArgs eventToSend = new LocationCheckedEventArgs(); //Construction du Meeting qui sera envoyé en résultat Meeting m = new Meeting(); m.Subject = a.Subject; m.DateTime = a.StartTime; m.Duration = (a.EndTime - a.StartTime).TotalMinutes; m.Address = a.Location; m.IsLocationFail = true; //Si dans le service bing map a trouvé les latitude et longitude de la requete if (e.Result != null) { if (e.Result.Results.Any(obj => obj.Locations != null && obj.Locations.Any()) && e.Result.Results.Count > 0) { if (e.Result.Results.FirstOrDefault().Confidence == Confidence.High && !String.IsNullOrEmpty(e.Result.Results.FirstOrDefault().Address.Locality)) { m.IsLocationFail = false; m.Location.Latitude = e.Result.Results.FirstOrDefault().Locations.FirstOrDefault().Latitude; m.Location.Longitude = e.Result.Results.FirstOrDefault().Locations.FirstOrDefault().Longitude; m.City = e.Result.Results.FirstOrDefault().Address.Locality; } } } eventToSend.Meeting = m; //On notifie l'observateur (dans ce cas, la méthode GetAllMeetingsAsync) LocationChecked(this, eventToSend); }; service.GeocodeAsync(request, appointment); }
public string GetLocation(string address) { string results = string.Empty; string key = "AsPcip7ChAzloBDBmSBoyyrjUgPL4PPigzM8-1rCIWLS5H5WGUJZyXZ971zqXACO"; try { //Create the geocode request, set the access key and the address to query GeocodeRequest geocodeRequest = new GeocodeRequest(); geocodeRequest.Credentials = new LocationChecker.GeocodeService.Credentials(); geocodeRequest.Credentials.ApplicationId = key; geocodeRequest.Query = address; //Create a filter to return only high confidence results ConfidenceFilter[] filters = new ConfidenceFilter[1]; filters[0] = new ConfidenceFilter(); filters[0].MinimumConfidence = Confidence.High; //Apply the filter to the request GeocodeOptions options = new GeocodeOptions(); //options.Filters = filters; geocodeRequest.Options = options; //Make the request GeocodeServiceClient client = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); GeocodeResponse response = client.Geocode(geocodeRequest); if (response.Results.Length > 0) { results = String.Format("Success:{0}:{1}:{2}", response.Results[0].Locations[0].Latitude, response.Results[0].Locations[0].Longitude, response.Results[0].Locations[0].Altitude); } else { results = "No Results Found"; } } catch (Exception e) { results = "Geocoding Error: " + e.Message; } return results; }
public void Find(string location, EventHandler onResults) { if (IsInitialized) { var geocodeRequest = new GeocodeRequest { Credentials = new Credentials {Token = token}, Query = location }; var geocodeService = new GeocodeServiceClient(); geocodeService.GeocodeCompleted += (o, e) => { GeocodeResponse geocodeResponse = e.Result; onResults(this, new GeocodeResultArgs {Results = geocodeResponse.Results}); }; geocodeService.GeocodeAsync(geocodeRequest); } }
/// <summary> /// Verifie les coordonnées géographiques d'un rendez-vous du Calendrier /// </summary> /// <param name="appointment">Rendez-vous</param> /// <remarks>Abonnez vous d'abord à l'évènement LocationChecked avant l'appel de cette méthode</remarks> public void CheckLocationAsync(Appointment appointment) { //Procédure de connexion et préparation de la requete GeocodeRequest request = new GeocodeRequest() { Credentials = new Credentials { ApplicationId = BingMapCredential.CREDENTIAL } }; if (appointment.Location == null) return; request.Query = appointment.Location; GeocodeServiceClient service = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); //Lorsque bing map nous envoie une réponse service.GeocodeCompleted += (o, e) => { //Construction du Meeting qui sera envoyé en résultat Meeting m = new Meeting(); m.Subject = appointment.Subject; m.DateTime = appointment.StartTime; m.Duration = (appointment.EndTime - appointment.StartTime).TotalMinutes; //Si dans le service bing map a trouvé les latitude et longitude de la requete if (e.Result == null || e.Result.Results.Count < 0 || e.Result.Results.Any(obj => obj.Locations == null && obj.Locations.Any())) { throw new Exception("Pas de géolocalisation possible"); } m.IsLocationFail = true; if (e.Result.Results.FirstOrDefault().Confidence == Confidence.High) { m.IsLocationFail = false; m.Location.Latitude = e.Result.Results.FirstOrDefault().Locations.FirstOrDefault().Latitude; m.Location.Longitude = e.Result.Results.FirstOrDefault().Locations.FirstOrDefault().Longitude; } LocationCheckedEventArgs eventToSend = new LocationCheckedEventArgs(); eventToSend.Meeting = m; //On notifie l'observateur (dans ce cas, la méthode GetAllMeetingsAsync) LocationChecked(this, eventToSend); }; service.GeocodeAsync(request); }
public bool QueryLocation(string queryString, out double lat, out double lng) { lat = 0; lng = 0; GeocodeRequest geocodeRequest = new GeocodeRequest(); geocodeRequest.Query = queryString; geocodeRequest.Options = new GeocodeOptions() { Filters = new FilterBase[] { new ConfidenceFilter() { MinimumConfidence = Confidence.High } }, Count = 1 }; geocodeRequest.Credentials = creds; GeocodeServiceClient geocodeServiceClient = new GeocodeServiceClient("CustomBinding_IGeocodeService"); GeocodeResponse geocodeResponse = geocodeServiceClient.Geocode(geocodeRequest); bool locationFound = geocodeResponse.Results.Count() > 0; if (locationFound) { lat = geocodeResponse.Results[0].Locations[0].Latitude; lng = geocodeResponse.Results[0].Locations[0].Longitude; } return locationFound; }
private void button1_Click(object sender, EventArgs e) { CommonService tokenService = new CommonService(); tokenService.Credentials = new System.Net.NetworkCredential("137871", "Mugga25."); TokenSpecification tokenSpecs = new TokenSpecification(); tokenSpecs.ClientIPAddress = "0.0.0.0 "; tokenSpecs.TokenValidityDurationMinutes = 60; string token = tokenService.GetClientToken(tokenSpecs); textBox1.AppendText(token + Environment.NewLine); GeocodeRequest request = new GeocodeRequest(); request.Credentials = new Credentials(); request.Credentials.Token = token; request.Query = "1234"; GeocodeOptions options = new GeocodeOptions(); ConfidenceFilter[] filters = new ConfidenceFilter[] { new ConfidenceFilter() { MinimumConfidence = Confidence.Low } }; options.Filters = filters; request.Options = options; GeocodeServiceClient geoCoder = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); GeocodeResponse response = geoCoder.Geocode(request); foreach (var result in response.Results) { textBox1.AppendText("Display Name: " + result.DisplayName + Environment.NewLine); textBox1.AppendText("Confidence: " + result.Confidence.ToString() + Environment.NewLine); textBox1.AppendText("Entity Type: " + result.EntityType + Environment.NewLine); foreach (var location in result.Locations) { textBox1.AppendText("Longitude: " + location.Longitude + Environment.NewLine); textBox1.AppendText("Latitude: " + location.Latitude + Environment.NewLine); textBox1.AppendText("Altitude: " + location.Altitude + Environment.NewLine); } } //LiveMapsTokenService.CommonServiceSoapClient tokenService = new LiveMapsTest.LiveMapsTokenService.CommonServiceSoapClient("CommonServiceSoap"); //GetClientTokenRequest tokenRequest = new GetClientTokenRequest(); //tokenService.ClientCredentials.UserName.UserName = "******"; //tokenService.ClientCredentials.UserName.Password = "******"; }