Get address from latitude and longitude using Bing map api


We can find address components Country, AddressLine, Postal code etc. from latitude and longitude using Bing map api.
For this Microsoft provide a Bing map rest api service. Call this service using HttpClient and get response in json format. To use Bing map rest api service BingMapKey required. Create Bing map key from the portal https://www.bingmapsportal.com/. To parse json we use JsonConvert class. Install Newtonsoft.Json reference from the Nuget packages.

using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
public void GetAddressFromLatLon(decimal Latitude, decimal Longitude)
{
    var apiURL = "http://dev.virtualearth.net/Rest/v1/Locations/";
    var searchRequest = Latitude + "," + Longitude + "?&key=BingMapKey";
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(apiURL);
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = client.GetAsync(searchRequest).Result;
    string Country = string.Empty;
    string Address = string.Empty;
    if (response.IsSuccessStatusCode)
    {
        var json = response.Content.ReadAsStringAsync().Result;
        var jsonObject = JsonConvert.DeserializeObject<RootObject>(json);
        if (jsonObject.resourceSets.Count > 0)
        {
            if (jsonObject.resourceSets[0].resources.Count > 0)
            {
                Country = jsonObject.resourceSets[0].resources[0].address.countryRegion;
                Address = jsonObject.resourceSets[0].resources[0].address.addressLine;
            }
        }
    }

}


Call the service by passing Latitude and Longitude.

Decimal Latitude = Convert.ToDecimal(50.95846878);
Decimal Longitude = Convert.ToDecimal(6.97181002);
GetAddressFromLatLon(Latitude, Longitude);