2

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).

2
  • I did this recently, let me find it. Commented May 10, 2011 at 15:21
  • I figured someone had to of. Thanks Chad. Commented May 10, 2011 at 15:22

1 Answer 1

1
//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.

Sign up to request clarification or add additional context in comments.

3 Comments

This works most of the time, however we have been getting, for one specific lat/long location, an undefined city, but the right state. Is there a case where this would happen, and a workaround?
The results object returned from the geocoding does not always have all of the parts. Its not a problem with this code, but instead just that the geocoder did not find that information.
Yeah I saw sublocality is another one. So I guess I'll modify your method to use that if it doesn't find locality

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.