Dil Marc
Dil Marc

Reputation: 103

Google Places AutoComplete Not working

I got an auto complete search bar for addresses with google places. problem is, it only appears on only ONE field at a time.

My HTML

<input type="text" id="google" name="pick" placeholder="Pick up location" required/>
<input type="text" id="google" name="drop" placeholder="Drop off location" required/>
<script src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&libraries=places"></script>

Script

    const options = {
    types: ['address'],
    componentRestrictions: {
    country: 'sg'
      }
     };

let autocomplete = new google.maps.places.Autocomplete(document.getElementById('google'), options);
autocomplete.addListener('place_changed', () => console.log(autocomplete.getPlace()));

The first input works, the second doesnt. When I change the ID on the first input, the second one works only. I want both inputs to have the google autocomplete address.

Upvotes: 0

Views: 3682

Answers (1)

programtreasures
programtreasures

Reputation: 4298

You need to register both text boxes separately

Html

<input type="text" id="google1" name="pick" placeholder="Pick up location" required/>
<input type="text" id="google2" name="drop" placeholder="Drop off location" required/>

Javascript

 const options = {
    types: ['address'],
    componentRestrictions: {
    country: 'sg'
      }
     };

let autocomplete1 = new google.maps.places.Autocomplete(document.getElementById('google1'), options);
autocomplete1.addListener('place_changed', () => console.log(autocomplete1.getPlace()));

let autocomplete2 = new google.maps.places.Autocomplete(document.getElementById('google2'), options);
autocomplete2.addListener('place_changed', () => console.log(autocomplete2.getPlace()));

Upvotes: 2

Related Questions