Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google maps API geocoding get address components [duplicate]

I'm working with google map API(geocoding) and I noticed the following. If I print the array for "x" address, it prints an array of objects of size 9. where the country is in the index 6. If I enter some other "y" address, sometimes the array of objects is less than 9 and the index to get the country is not 6 anymore. I have tried with different addresses as some of them have the size consistent as 9 some of them at 6 some of them 7 and so on. Is there a set way for me to access the country without having to check the size of the array and avoid this issue?

my code

     let place: google.maps.places.PlaceResult = autocomplete.getPlace();
     this.addressArray = place.address_components;
     if(this.addressArray.length === 9) {
        this.country = this.addressArray[6].short_name;
        this.zipcode = this.addressArray[7].short_name;
     } else {
        this.country = this.addressArray[5].short_name;
        this.zipcode = this.addressArray[6].short_name;
     }

I figured I can use place.formatted_address and access the last word which is always the country, but for zipcode and some other information on the address the order is not always the same. Below is an example of the structure of the array of objects I'm printing.

I thought about filtering the array to find the index of types that contains the word country,zipcode, etc and based on the index returned get the country or whatever I want to retrieve. I wonder if there's an easier way to accomplish this straight from the google API geocode.

This question How to get country from google maps api? talks about someone entering the address. My application uses google autocomplete. I thought the API was smarter to handle the missing data of people not entering a complete address. Also, the answer address in that question is part of my explanation of my question of me saying I knew I could filter the array

enter image description here

like image 875
Patricio Vargas Avatar asked Aug 02 '26 16:08

Patricio Vargas


1 Answers

related question: Wrong country code returned by Google Geocoder

You need to parse through the address_components array's types, looking for the entry with a type of country.

var country = '';
for (var i = 0; i < place.address_components.length; i++) {
  for (var j = 0; j < place.address_components[i].types.length; j++) {
    if (place.address_components[i].types[j] == "country") {
      country = place.address_components[i];
    }
  }
}
document.getElementById("country").innerHTML = country.long_name +" (" + country.short_name +")";

proof of concept fiddle

screenshot of resulting map

code snippet:

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: -33.8688,
      lng: 151.2195
    },
    zoom: 13
  });
  var input = document.getElementById('pac-input');
  var autocomplete = new google.maps.places.Autocomplete(input);

  autocomplete.bindTo('bounds', map);

  var infowindow = new google.maps.InfoWindow();
  var infowindowContent = document.getElementById('infowindow-content');
  infowindow.setContent(infowindowContent);
  var marker = new google.maps.Marker({
    map: map,
    anchorPoint: new google.maps.Point(0, -29)
  });

  autocomplete.addListener('place_changed', function() {
    infowindow.close();
    marker.setVisible(false);
    var place = autocomplete.getPlace();
    if (!place.geometry) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
      window.alert("No details available for input: '" + place.name + "'");
      return;
    }

    // If the place has a geometry, then present it on a map.
    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
      map.setZoom(17); // Why 17? Because it looks good.
    }
    marker.setPosition(place.geometry.location);
    marker.setVisible(true);
    var country = '';
    for (var i = 0; i < place.address_components.length; i++) {
      for (var j = 0; j < place.address_components[i].types.length; j++) {
        if (place.address_components[i].types[j] == "country") {
          country = place.address_components[i];
        }
      }
    }
    document.getElementById("country").innerHTML = country.long_name + " (" + country.short_name + ")";
    infowindowContent.children['place-icon'].src = place.icon;
    infowindowContent.children['place-name'].textContent = place.name;
    infowindowContent.children['place-address'].textContent = country.long_name;
    infowindow.open(map, marker);
  });
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

#description {
  font-family: Roboto;
  font-size: 30px;
  font-weight: 300;
}

#infowindow-content .title {
  font-weight: bold;
}

#infowindow-content {
  display: none;
}

#map #infowindow-content {
  display: inline;
}

.pac-card {
  margin: 10px 10px 0 0;
  border-radius: 2px 0 0 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  outline: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  background-color: #fff;
  font-family: Roboto;
}

#pac-container {
  padding-bottom: 12px;
  margin-right: 12px;
}

.pac-controls {
  display: inline-block;
  padding: 5px 11px;
}

.pac-controls label {
  font-family: Roboto;
  font-size: 13px;
  font-weight: 300;
}

#pac-input {
  background-color: #fff;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  margin-left: 12px;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 400px;
}

#pac-input:focus {
  border-color: #4d90fe;
}

#title {
  color: #fff;
  background-color: #4d90fe;
  font-size: 25px;
  font-weight: 500;
  padding: 6px 12px;
}
<div class="pac-card" id="pac-card">
  <div>
    <div id="type-selector" class="pac-controls">
    </div>
    <div id="pac-container">
      <input id="pac-input" type="text" placeholder="Enter a location">
    </div>
  </div>
</div>
<div id="country"></div>
<div id="map"></div>
<div id="infowindow-content">
  <img src="" width="16" height="16" id="place-icon">
  <span id="place-name" class="title"></span><br>
  <span id="place-address"></span>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" async defer></script>
like image 163
geocodezip Avatar answered Aug 07 '26 03:08

geocodezip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!