user10150720
user10150720

Reputation:

Get City, State, Zip Code from Longitude & Latitude in Javascript

I want to get city, state, zip code of a user from longitude & latitude. I followed some tutorials from stackoverflow about google maps Reverse geocoding API, But It is returning sometime the array which has 2 to 3 length & something the length is 6 to 8. So i am not able to get exact in which index i can find the city,state & zip. Below is my code to get longitude & latitude of user.

  var longitude,latitude;

  if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    console.log("Geolocation is not supported by this browser.");
  } 
  function showPosition(position) {
   longitude = position.coords.longitude;
   latitude = position.coords.latitude;
  }

Thanks.

Upvotes: 1

Views: 2913

Answers (1)

user10045612
user10045612

Reputation:

Yes, You are Right,

You will get length of array of random numbers which is based on address. To get the country, state, city & zipcode, You will have to choose first array in the results array and in that choose address_components array, Here in this array, Last index of array is zipcode, Second last index of array is country, third last index of array is state & fourth last index of array is your city. Please have a look at the below image to understand structure of arrays.

Note: I tested it in india, Not sure about any other country.

attached image

Thanks.

Upvotes: 2

Related Questions