Having problems getting the different arrays content from geocoder results.
item.formatted_address works but not item.address_components.locality?
ge
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',
}