Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda