javascripthtmljquerygoogle-places-apireact-google-places-autocomplete

google places automplete only suggestions with stress number


I am working with googles api places for address autocomplete suggestions. This is my simple working code:

<!DOCTYPE html>
<html>
<body>

<form>
   <input id="customerAddress" name="customerAddress" required autocomplete="off" />
   <input id="zip" name="zip" required readonly />
   <input id="city" name="city" required readonly />
</form>

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

        let autocomplete;
        
        function initAutocomplete() {
         
          autocomplete = new google.maps.places.Autocomplete(document.querySelector("#customerAddress"), {
            componentRestrictions: { country: ["de", "DE"] },
            fields: ["address_components", "geometry"],
            types: ["address"],
          });
          autocomplete.addListener("place_changed", fillInAddress);
        }
        
        function fillInAddress() {
          
          const place = autocomplete.getPlace();
          var address = ""
          var streetNumber = ""
        
          
          for (const component of place.address_components) {
            const componentType = component.types[0];
            
            switch (componentType) {

              case "route": {
                address = component.long_name;
                break;
              }
              
              case "street_number": {
                  streetNumber = component.long_name
                  break;
                }
        
              case "postal_code": {
                document.querySelector("#zip").value = component.long_name;
                break;
              }
        

              case "locality":
                document.querySelector("#city").value = component.long_name;
                break;

            }
          }
        
        document.querySelector("#customerAddress").value = address +" "+streetNumber
                  
          
        }
    </script>
  </body>
</html>

Now I would realize the following situation:


Solution

  • Well, I think the best solution would be to have separate hidden input where you would put selected address which you would run validation against, if it is not defined you simply return error.

    As for having street number you can also run the validation of selected Place. If it has selected type street_number it is valid, if not it's not.

    I am not sure if you can disable Google to restricts search results to only addresses with street number.