More efficient way to extract address components

前端 未结 9 1103
再見小時候
再見小時候 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 11:01

    Visitors using underscore.js can easily convert the address_components array in the geocode response into an object literal:

    var obj = _.object( 
        _.map(results[0].address_components, function(c){ 
            return  [c.types[0], c.short_name] 
        })
    );
    
    0 讨论(0)
  • 2020-12-15 11:05

    You could use the following function to extract any address component:

    function extractFromAdress(components, type){
        for (var i=0; i<components.length; i++)
            for (var j=0; j<components[i].types.length; j++)
                if (components[i].types[j]==type) return components[i].long_name;
        return "";
    }
    

    To extract the info you call:

    var postCode = extractFromAdress(results[0].address_components, "postal_code");
    var street = extractFromAdress(results[0].address_components, "route");
    var town = extractFromAdress(results[0].address_components, "locality");
    var country = extractFromAdress(results[0].address_components, "country");
    

    etc...

    0 讨论(0)
  • 2020-12-15 11:05

    Using lodash

    const result = _.chain(json.results[0].address_components)
      .keyBy('types[0]')
      .mapValues('short_name')
      .value()
    
    0 讨论(0)
提交回复
热议问题