kk_nou
kk_nou

Reputation: 103

Google geocode with address returns one result

Geocoder with an existing address as a parameter returns only the street_address as a result. Why? The address is valid. It has been tested at https://google-developers.appspot.com/maps/documentation/utils/geocoder/

My call:

   checkAddress(street, strNo, post_code, area, function (results) {
        if (results) { 
     $.each(results, function (i, address) {
    if (address.types[0] == "street_address") {
        itemStreetNo = address.address_components[0].long_name;
        itemStreet = address.address_components[1].long_name;
    }

    if (address.types[0] == "route") {
        itemStreet = address.address_components[0].long_name;
    }

    if (address.types[0] == "postal_code") {
        itemPostalCode = address.address_components[0].long_name;
    }

    if (address.types[0] == "country") {
        itemCountry = address.address_components[0].long_name;
    }

    if (address.types[0] == "locality") {
        itemRegion = address.address_components[0].long_name;
    }
  }
 });

My function is:

function checkAddress(address, number, zipcode, area, callback) {

    var geocoder = new google.maps.Geocoder;

    var addr = address + ' ' + number + ' ' + zipcode + ' ' + area;

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

        if (status === google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                callback(results);
            }
            else {
                callback(null);
            }
        }
        else {
            callback(null);
        }
    });
}

Upvotes: 0

Views: 447

Answers (1)

Emmanuel Delay
Emmanuel Delay

Reputation: 3679

You only search in 1 component (address.address_components[0]), so you only get 1 result.

address.address_components[0] contains a component, for example "route". Then address.address_components[1] contains another component, for example "locality", then address.address_components[2] ... As far as I remember the order of the components is random.

So what you need, is to iterate. For every component you check the type, that lets you know where the value is supposed to go.

I wrote a function for a different Stack Overflow question that does this iteration, that goes "fishing" for whatever component.

See if it works for you; let me know.

Google API Address Components

Upvotes: 2

Related Questions