slandau
slandau

Reputation: 24102

Loop through Google Maps result in Javascript

So reverse geocoding, the result looks like this:

results[0].formatted_address: "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
results[1].formatted_address: "Williamsburg, NY, USA",
results[2].formatted_address: "New York 11211, USA",
results[3].formatted_address: "Kings, New York, USA",
results[4].formatted_address: "Brooklyn, New York, USA",
results[5].formatted_address: "New York, New York, USA",
results[6].formatted_address: "New York, USA",
results[7].formatted_address: "United States"

It's an array of addresses, one less detailed then the next. I need to loop through this list and get the address that ONLY contains the city/state. How would I do this?

It's not always a specific element (thanks Google).

Upvotes: 2

Views: 671

Answers (1)

Chad
Chad

Reputation: 19619

//store the most specific address for easy access
var a = results[0].address_components;

var city = null, state = null;
for(i = 0; i < a.length; ++i)
{
   var t = a[i].types;
   if(compIsType(t, 'administrative_area_level_1'))
      state = a[i].long_name; //store the state
   else if(compIsType(t, 'locality'))
      city = a[i].long_name; //store the city

   //we can break early if we find both
   if(state != null && city != null) break;
}

function compIsType(t, s) { 
   for(z = 0; z < t.length; ++z) 
      if(t[z] == s)
         return true;

   return false;
}

Basically what happens is you loop throught he address components, each has 'types' associated with it. You can use these to determine what that component represents. Nearly 100% of the time (in the USA) 'administrative_area_level_1' is the state, and 'locality' is the city. More Info: Types, JSON Output.

I apologize for my poor variable naming, if you have any questions let me know.

Upvotes: 1

Related Questions