More efficient way to extract address components

前端 未结 9 1101
再見小時候
再見小時候 2020-12-15 10:23

Currenty, I\'m using the following code to get the country, postal code, locality and sub-locality:

var country, postal_code, locality, sublocality;
for (i =         


        
9条回答
  •  囚心锁ツ
    2020-12-15 10:46

    if (typeof Object.keys == 'function')
        var length = function(x) { return Object.keys(x).length; };
    else
        var length = function() {};
    
    var location = {};      
    for (i = 0; i < results[0].address_components.length; ++i)
    {
        var component = results[0].address_components[i];
        if (!location.country && component.types.indexOf("country") > -1)
            location.country = component.long_name;
        else if (!location.postal_code && component.types.indexOf("postal_code") > -1)
            location.postal_code = component.long_name;
        else if (location.locality && component.types.indexOf("locality") > -1)
            location.locality = component.long_name;
        else if (location.sublocality && component.types.indexOf("sublocality") > -1)
            location.sublocality = component.long_name;
    
        // nothing will happen here if `Object.keys` isn't supported!
        if (length(location) == 4)
            break;
    }
    

    This is the most suitable solution for me. It may help someone too.

提交回复
热议问题