get city from geocoder results?

后端 未结 13 1849
我寻月下人不归
我寻月下人不归 2020-12-02 14:07

Having problems getting the different arrays content from geocoder results.

item.formatted_address works but not item.address_components.locality?

ge         


        
相关标签:
13条回答
  • 2020-12-02 15:08

    I created this function to get the main info of geocoder results:

    const getDataFromGeoCoderResult = (geoCoderResponse) => {
      const geoCoderResponseHead = geoCoderResponse[0];
      const geoCoderData = geoCoderResponseHead.address_components;
      const isEmptyData = !geoCoderResponseHead || !geoCoderData;
    
      if (isEmptyData) return {};
    
      return geoCoderData.reduce((acc, { types, long_name: value }) => {
        const type = types[0];
    
        switch (type) {
          case 'route':
            return { ...acc, route: value };
          case 'locality':
            return { ...acc, locality: value };
          case 'country':
            return { ...acc, country: value };
          case 'postal_code_prefix':
            return { ...acc, postalCodePrefix: value };
          case 'street_number':
            return { ...acc, streetNumber: value };
          default:
            return acc;
        }
      }, {});
    };
    

    So, you can use it like this:

    const geoCoderResponse = await geocodeByAddress(value);
    const geoCoderData = getDataFromGeoCoderResult(geoCoderResponse);
    

    let's say that you are going search Santiago Bernabéu Stadium, so, the result will be:

    {
      country: 'Spain',
      locality: 'Madrid',
      route: 'Avenida de Concha Espina',
      streetNumber: '1',
    }
    
    0 讨论(0)
提交回复
热议问题