Google地方信息自动完成无效

时间:2018-01-19 04:03:32

标签: javascript forms google-places-api

我有一个自动完整的搜索栏,用于谷歌地址的地址。问题是,它一次只出现在一个字段上。

我的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>

脚本

    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()));

第一个输入有效,第二个输入有效。当我更改第一个输入的ID时,第二个输入只能工作。我希望两个输入都有谷歌自动完成地址。

1 个答案:

答案 0 :(得分:2)

您需要单独注册两个文本框

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()));