google-mapsgeocodingstreet-addresscity

get city from geocoder results?


Having problems getting the different arrays content from geocoder results.

item.formatted_address works but not item.address_components.locality?

geocoder.geocode( {'address': request.term }, function(results, status) {

        response($.map(results, function(item) {

        alert(item.formatted_address+" "+item.address_components.locality)
    }            
}); 

// the array returned is;

 "results" : [
      {
         "address_components" : [
            {
               "long_name" : "London",
               "short_name" : "London",
               "types" : [ "locality", "political" ]
            } ],
          "formatted_address" : "Westminster, London, UK" // rest of array...

any help appreciated!

Dc


Solution

  • Got this working in the end using:

    var arrAddress = item.address_components;
    var itemRoute='';
    var itemLocality='';
    var itemCountry='';
    var itemPc='';
    var itemSnumber='';
    
    // iterate through address_component array
    $.each(arrAddress, function (i, address_component) {
        console.log('address_component:'+i);
    
        if (address_component.types[0] == "route"){
            console.log(i+": route:"+address_component.long_name);
            itemRoute = address_component.long_name;
        }
    
        if (address_component.types[0] == "locality"){
            console.log("town:"+address_component.long_name);
            itemLocality = address_component.long_name;
        }
    
        if (address_component.types[0] == "country"){ 
            console.log("country:"+address_component.long_name); 
            itemCountry = address_component.long_name;
        }
    
        if (address_component.types[0] == "postal_code_prefix"){ 
            console.log("pc:"+address_component.long_name);  
            itemPc = address_component.long_name;
        }
    
        if (address_component.types[0] == "street_number"){ 
            console.log("street_number:"+address_component.long_name);  
            itemSnumber = address_component.long_name;
        }
        //return false; // break the loop   
    });