Search code examples
google-mapsgoogle-maps-api-3geocodinggoogle-geocoding-api

Need to alter space from postal code in results array


Hi my requirement need to get postal code from

var address= results[0].formatted_address ;  

this formatted value. Because nether land address have "Danzigerkade 12,1013 AP Amsterdam,Netherlands" this kind of address. but i don't want postal code like this"1013 AP" . i need "1013AP" like this.

Please give me the solution. Thanks in advance.


Solution

  • I don't recommend parsing the formatted_address to get the postal code or any other specific address fields. Instead, you should scan through the address_components and check the types array of each one to find the address field you need. This is much more reliable than parsing the formatted string.

    Once you have the postal code, removing the space is trivial.

    To find the postal code for an entry in your results array (e.g. results[0]), you can use code like this:

    function getAddressComponent( result, type ) {
        var components = result.address_components;
        for( var i = 0;  i < components.length;  ++i ) {
            var component = components[i], types = component.types;
            for( var k = 0;  k < types.length;  ++k ) {
                if( types[k] == type ){
                    return component;
                }
            }
        }
        return {};
    }
    
    var component = getAddressComponent( results[0], 'postal_code' );
    var postalCode = component ? component.short_name : '';
    var postalCodeNoSpace = postalCode.replace( ' ', '' );
    console.log( postalCodeNoSpace );
    

    Update in reply to your comment:

    The code you're asking about with ? and : uses the conditional operator found in JavaScript and many other languages:

    var postalCode = component ? component.short_name : '';
    

    That works just like this longer form that should look more familiar:

    if( component )
        postalCode = component.short_name;
    else
        postalCode = '';
    

    The idea was to not try to reference component.short_name if component itself is null or undefined, because of course that would be an error. In other words, to protect the program from crashing if getAddressComponent() does not find a postal code.

    But interestingly enough, there's a bug in the way I was using it. Look at the last line of getAddressComponent():

        return {};
    

    Originally I was going to return null there - and then the code you asked about would have been correct - but for some reason I decided to return an empty object instead. So the code in question wasn't quite right with that change.

    One way to fix this would be to go back to what I originally meant to do, and change the last line of getAddressComponent() from this:

        return {};
    

    to:

        return null;