-2

I have autocomplete working great, i have included the library geometry,

<script defer src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry&key=xxaSyxxxxxxxx9xx&callback=initAutocomplete"></script>

Here is the html+js :

<input class="forminput" id="autocomplete" maxlength="30" type=text placeholder="Ex: street.."></input>  

let placeSearch;
let autocomplete;
const componentForm = {
  street_number: "short_name",
  route: "long_name",
  locality: "long_name",
  administrative_area_level_1: "short_name",
  country: "long_name",
  postal_code: "short_name",
};


function initAutocomplete() {

  autocomplete = new google.maps.places.Autocomplete(
    document.getElementById("autocomplete"),
    { types: ["geocode"] }
  );
  //address only
  autocomplete.setFields(["address_component"]);
  //populate
  autocomplete.addListener("place_changed", fillInAddress);
}

When i read the results, places has no geometry property :

function fillInAddress() {

  const place = autocomplete.getPlace();

  console.log(place); // is good
  console.log(place.geometry); // is undefined all the time

  for (const component of place.address_components) {
  const addressType = component.types[0];
  const val = component[componentForm[addressType]];
   alert(addressType + " " + val);   //  ****** this is good !!!
  }

How to get the geometry to work? i need the lat/log .

paul seems
  • 505
  • 4
  • 12

1 Answers1

0

To anyone who struggle, it was pretty simple,

  autocomplete.setFields(["address_component","geometry"]);

For some reason Google's docs almost hide it in their tutorial, but you must add it ALSO here to make it work.

This works also without including the geometry library.

paul seems
  • 505
  • 4
  • 12