Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
How to always get city from google geocoding api

I'm using the google geocoding API and I'm trying to get the city. This is I'm getting the info.

const city = data.results[0].address_components[3].long_name

The issue with this is that the response will be different depending on the address the user gives. In some, it will be in address_components[2] instead of 3. The city is in the response but in a different array.

Is there a way to always get the city regardless of where in the array it is?

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Sure there is a way. In order to achieve this you shouldn't rely on the exact position in the address components array.

Instead you have to apply filter by the "types" field to find out the corresponding address component of the city.

The following array methods can be used:

  • Array.prototype.filter()

  • Array.prototype.includes()

The code snapshot is the following

const addressComponents = data.results[0].address_components;
const filteredArray = addressComponents.filter(
    address_component => address_component.types.includes("locality")
); 
const city = filteredArray.length ? filteredArray[0].long_name : "City not found";
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda