More efficient way to extract address components

前端 未结 9 1102
再見小時候
再見小時候 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.

    0 讨论(0)
  • 2020-12-15 10:48

    I really believe that user1429980 answer above deserves more recognition. It works really well. My answer is based on his function. I've added a few examples to better illustrate how to search the JSON object using the code user1429980 provided:

    //searches object for a given key and returns the key's value

    extractFromObject (object, key) { return object.filter((component) => component.types.indexOf(key) === 0).map((item)=>item.long_name).pop() || null; }


    Example 1: Google's reverseGeocode API with longitude and latitude set at 43.6532,79.3832 (Toronto, Ontario, Canada):

    var jsonData = {} //object contains data returned from reverseGeocode API

    var city = extractFromObject(jsonData.json.results[0].address_components, 'locality');

    console.log(city); //Output is Toronto


    Example 2: Google's Places API with place ID set to ChIJE9on3F3HwoAR9AhGJW_fL-I (Los Angeles, CA, USA):

    var jsonData = {} //object contains data returned from Google's Places API

    var city = extractFromObject(jsonData.json.result.address_components, 'locality');

    console.log(city); //Output is Los Angeles

    0 讨论(0)
  • 2020-12-15 10:49

    I made function before that extracts a list of values given a list of place types:

    const getValue = function(data, types=[]){
    /* used by results taken from Geocoder.geocode api */
    const values = data.reduce((values, address) => {
        return address.address_components.reduce((values2, component) => {
            if(component.types.reduce((result, type) => result || types.indexOf(type) > -1, false))
                values2.push(component.long_name);
            return values2
        }, []);
    
        if(buff.length)
            return [...values, ...buff];
        return values;
    }, []).filter(
        (value, index, self) => {
            return self.indexOf(value) === index;
        }
    );
    

    }

    0 讨论(0)
  • 2020-12-15 10:50

    You can shorten it to

    var country, postal_code, locality, sublocality;
    for (i = 0; i < results[0].address_components.length; ++i) {
        var component = results[0].address_components[i];
        if (!sublocality && component.types.indexOf("sublocality") > -1)
            sublocality = component.long_name;
        else if (!locality && component.types.indexOf("locality") > -1)
            locality = component.long_name;
        else if (!postal_code && component.types.indexOf("postal_code") > -1)
            postal_code = component.long_name;
        else if (!country && component.types.indexOf("country") > -1)
            country = component.long_name;
    }
    

    Or are you trying to get a better formatted result? Then please show us your query.

    0 讨论(0)
  • 2020-12-15 10:51

    My one-liner using a functional approach and map, filter, and ES2015:

    /**
     * Get the value for a given key in address_components
     * 
     * @param {Array} components address_components returned from Google maps autocomplete
     * @param type key for desired address component
     * @returns {String} value, if found, for given type (key)
     */
    function extractFromAddress(components, type) {
        return components.filter((component) => component.types.indexOf(type) === 0).map((item) => item.long_name).pop() || null;
    }
    

    Usage:

    const place = autocomplete.getPlace();
    const address_components = place["address_components"] || [];
    
    const postal_code = extractFromAddress(address_components, "postal_code");
    
    0 讨论(0)
  • 2020-12-15 10:57

    I did it like this:

    placeParser = function(place){
      result = {};
      for(var i = 0; i < place.address_components.length; i++){
        ac = place.address_components[i];
        result[ac.types[0]] = ac.long_name;
      }
      return result;
     };
    

    then i just use

    parsed = placeParser(place)
    parsed.route
    
    0 讨论(0)
提交回复
热议问题