Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!