Google API自动填充搜索框 - HTML / JavaScript

时间:2017-03-27 09:13:58

标签: javascript html5 google-maps-api-3 google-api google-api-java-client

我对HTML / JavaScript的了解非常有限,并且只是成功设法在我的网站上实施了Google Place Autocomplete Searchbox(没有地图)。

我需要两个使用Google Place Autocomplete的输入,但我使用的以下代码不显示两个输入字段,只显示第二个输入字段(searchTextField2)。

任何人都可以提供一些建议,或者指出我在这个代码出错的地方吗?

非常感谢任何帮助。

<!DOCTYPE html>
<html>
<head>
<title> </title>

<style>
#searchTextField {
position: absolute;
box-sizing: border-box;
z-index: 4;
height: 40px;
width: 360px;
left: 0px;
top: 0px;
border: 1px solid rgb(189, 189, 189);
background-color: rgb(255, 255, 255);
border-radius: 3px;
font-family: Roboto;
font-size: 18px;
font-weight: 500;
color: rgb(85, 85, 85);
padding: 0px 4px;
transition: border-color 200ms ease, box-shadow 200ms ease;
box-shadow: none;
  }

#searchTextField2 {
position: absolute;
box-sizing: border-box;
z-index: 4;
height: 40px;
width: 360px;
left: 0px;
top: 0px;
border: 1px solid rgb(189, 189, 189);
background-color: rgb(255, 255, 255);
border-radius: 3px;
font-family: Roboto;
font-size: 18px;
font-weight: 500;
color: rgb(85, 85, 85);
padding: 0px 4px;
transition: border-color 200ms ease, box-shadow 200ms ease;
box-shadow: none;
  }
</style>

</head>

<body>
<input id="searchTextField" type="text" size="50" placeholder="Pick-up Address" tabindex=2><br>
<input id="searchTextField2" type="text" size="50" placeholder="Destination" tabindex=3>


<script type="text/javascript">
function initMap() {
var input = document.getElementById('searchTextField');
var input = document.getElementById('searchTextField2');
var options = {
   // types: ['(cities)'],
   componentRestrictions: {country: 'uk'}//UK
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
}
</script>

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

</body>
</html>

1 个答案:

答案 0 :(得分:0)

您要在当前代码中重新声明var input

function initMap() {
var input = document.getElementById('searchTextField');
var input2 = document.getElementById('searchTextField2');
var options = {
   // types: ['(cities)'],
   componentRestrictions: {country: 'uk'}//UK
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
var autocomplete2 = new google.maps.places.Autocomplete(input2,options);
}