Home > Uncategorized > Get a country code from an address in c#

Get a country code from an address in c#

atlas-18

If you have a partial address, or just a town / city name and you’d like to get the country code (ISO3166) then you can use Google’s geocode API from c# as follows;

The Google API key is not strictly necessary, but it’s recommended, as they will probably throttle use for unauthenticated calls.

public static string GetCountryFromAddress(string address)
{

try
{
// API key is recommended, but not required
const string strGoogleApiKey = “….”;
var strUrl = “https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}”;
strUrl = string.Format(strUrl, address, strGoogleApiKey);
var wc = new WebClient();
var strJson = wc.DownloadString(strUrl);
var json = JObject.Parse(strJson);
var jResult = json[“results”][0];
var jAddressComponents = jResult[“address_components”];
foreach (var jAddressComponent in jAddressComponents)
{
var jTypes = jAddressComponent[“types”];
if (jTypes.Any(t => t.ToString() == “country”))
{
return jAddressComponent[“short_name”].ToString();
}
}
return null;
}
catch
{
return null;
}
}

Advertisements
Categories: Uncategorized
  1. August 11, 2017 at 8:56 am

    PS: This requires the Newtonsoft.Json nuget package

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: