get city from geocoder results?

Viewed 85621

Having problems getting the different arrays content from geocoder results.

item.formatted_address works but not item.address_components.locality?

geocoder.geocode( {'address': request.term }, function(results, status) {

        response($.map(results, function(item) {

        alert(item.formatted_address+" "+item.address_components.locality)
    }            
}); 

// the array returned is;

 "results" : [
      {
         "address_components" : [
            {
               "long_name" : "London",
               "short_name" : "London",
               "types" : [ "locality", "political" ]
            } ],
          "formatted_address" : "Westminster, London, UK" // rest of array...

any help appreciated!

Dc

14 Answers

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',
}

This worked for me:

const localityObject = body.results[0].address_components.filter((obj) => {
  return obj.types.includes('locality');
})[0];
const city = localityObject.long_name;

or in one go:

const city = body.results[0].address_components.filter((obj) => {
  return obj.types.includes('locality');
)[0].long_name;

I'm doing this in Node, so this is okay. If you need to support IE you need to use a polyfill for Array.prototype.includes or find another way of doing it.

Well this worked for me if you want to get the city

var city = "";
function getPositionByLatLang(lat, lng) {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                //formatted address
                city = results[0].plus_code.compound_code;
                city = city.substr(0, city.indexOf(','));
                city = city.split(' ')[1];

                console.log("the name of city is: "+ city);
            }
        } else {
            // alert("Geocoder failed due to: " + status);
        }
    });
}

You can get the city without iterate, generally the city is located on the 2nd key of address_components object so the 2nd mean 1:

results[0].address_components[1].long_name
Related