Search code examples
javascriptgoogle-mapsgoogle-places-apigoogle-placesgoogle-places-autocomplete

Google Places API Dropdown does not show up


I am using Python Flask with Google Places API for Autocompleting Places. I want my website to autocomplete the place and then send it via fetch to the Flask server. For now, I just want to log the location to the console. However, when I implement the API using the Places API (https://developers.google.com/places/web-service/autocomplete), the dropdown doesn't even show up. Here is a relevant snippet of my code:

<div id="locationField">
  <input
    id="autocomplete"
    placeholder="Enter your address"
    onfocus="geolocate()"
    type="text"
  />
</div>
<script defer
    src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=initMap">
  let placeSearch;
  let autocomplete;
  function initAutocomplete() {
    // Create the autocomplete object, restricting the search predictions to
    // geographical location types.
    autocomplete = new google.maps.places.Autocomplete(
      document.getElementById("autocomplete"),
      { types: ["geocode"] }
    );
    // Avoid paying for data that you don't need by restricting the set of
    // place fields that are returned to just the address components.
    autocomplete.setFields(["address_component"]);
    // When the user selects an address from the drop-down, populate the
    // address fields in the form.
    autocomplete.addListener("place_changed", getAddress);
  }
  
  function getAddress() {
    console.log(autocomplete.getPlace());
  }
  
  function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      const geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      };
      const circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy,
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
</script>

Any help is appreciated. Thank You in advance!

EDIT: I checked the Dev Tools and found 2 JS Errors: submit:1 Uncaught (in promise) le and Uncaught ReferenceError: geolocate is not defined at HTMLInputElement.onfocus (submit:76)


Solution

  • Have a look at the script that loads Google Maps JavaScript API:

    <script defer
    src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=initMap">
    

    Note that it has the following parameter callback=initMap. That means that once Google Maps JavaScript API is completely loaded it will call function with name initMap().

    This function doesn't exist in your code. You have another one with name initAutocomplete(), so you should use this function name in the callback parameter:

    callback=initAutocomplete.

    EDIT:

    In addition you are not close properly tags. The script that loads Maps JavaScript API must be closed with </script> tag and followed by <script> for the part of code that defines your functions. Have a look at the code snippet that fixes your issues.

    <div id="locationField">
      <input
        id="autocomplete"
        placeholder="Enter your address"
        onfocus="geolocate()"
        type="text"
      />
    </div>
    <script defer
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=places&callback=initAutocomplete">
    </script>
    <script>
      let placeSearch;
      let autocomplete;
      function initAutocomplete() {
        // Create the autocomplete object, restricting the search predictions to
        // geographical location types.
        autocomplete = new google.maps.places.Autocomplete(
          document.getElementById("autocomplete"),
          { types: ["geocode"] }
        );
        // Avoid paying for data that you don't need by restricting the set of
        // place fields that are returned to just the address components.
        autocomplete.setFields(["address_component"]);
        // When the user selects an address from the drop-down, populate the
        // address fields in the form.
        autocomplete.addListener("place_changed", getAddress);
      }
      
      function getAddress() {
        console.log(autocomplete.getPlace());
      }
      
      function geolocate() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          const geolocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };
          const circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy,
          });
          autocomplete.setBounds(circle.getBounds());
        });
      }
    }
    </script>

    I hope this resolves your issue.