Travis M.
Travis M.

Reputation: 11257

c# grabbing google maps api address_components

I'm having trouble pulling individual address components from google map's api results.

Here are the results received from this url:

http://maps.googleapis.com/maps/api/geocode/json?address=jobing.com+glendale+arizona&sensor=false

This url is in the "uri" variable. Here's the code I'm using to try and retrieve the address_component by type. Take into consideration that I'm a bit new at c#.

String Output = client.DownloadString(uri);
Dictionary<String, Object> RinkData = JsonConvert.DeserializeObject<Dictionary<String, Object>>(Output);
Dictionary<String, Object> RinkDataResults = (Dictionary<String, Object>) RinkData["results"];
if (RinkDataResults.ContainsKey("formatted_address"))
{
  Route = GetAddressComponentByType(RinkDataResults["address_components"], "route");
}

And here is the function I'm using "GetAddressComponentByType"

protected String GetAddressComponentByType(Object AddressComponents, String AddressType)
{
  Boolean MatchFound = false;
  String MatchingLongName = "";
  Dictionary<String, Object> AddressComponentsDict = (Dictionary<String, Object>)AddressComponents;
  foreach (KeyValuePair<String, Object> ac in AddressComponentsDict)
  {
    Dictionary<String, Object> acDict = (Dictionary<String, Object>) ac.Value;
    ArrayList acTypes = (ArrayList) acDict["types"];
    foreach (String acType in acTypes)
    {
      if (acType == AddressType)
      {
        MatchFound = true;
        break;
      }
    }
    if (MatchFound)
    {
      MatchingLongName = (String) acDict["long_name"];
    }
  }
  return MatchingLongName;
}

The problem is, it doesn't even get to my component retrieval function. It bombs converting RinkData["results"] to a Dictionary saying it's an invalid conversion.

Does anyone see what I'm doing wrong? Or maybe someone has a custom object I can read google maps geocode results into that works?

Upvotes: 1

Views: 1694

Answers (1)

Travis M.
Travis M.

Reputation: 11257

Ah, nevermind. I can extract address components easily if I start with this object

  dynamic googleResults = new Uri(uri).GetDynamicJsonObject();
  foreach (var result in googleResults.results)
  {
    foreach (var addressComp in result.address_components)
    {
      Literal1.Text += "<br />" + addressComp.long_name;
    }
  }

It's an extension class for JSON.NET found here. From L.B.'s answer to this question.

Upvotes: 2

Related Questions