Google 地图外的地图搜索框不起作用

Google maps search box outside map not function

我一直在研究如何制作类似于 google 字段搜索图的字段搜索框。我找到了正确的答案 here which answered by @MrUpsidown. This is jsfiddle answer by @MrUpsidown jsfiddle,而且效果很好。然后我尝试将它实现到我的项目中,但是它不起作用。

这里是我的代码:

<!DOCTYPE html>
<html>
<head>
 <title>
   Search Box Map
 </title>
 <style>
   #autocomplete {
     width:300px;
   }
 </style>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyB1Z4LA0_Q-qH3Sfq-vIr3lShYnIwS1KUw&libraries=places" ></script>
 <script>

  function initialize() {

   new google.maps.places.Autocomplete(
   (document.getElementById('autocomplete')), {
      types: ['geocode']
   });
  }

  initialize();

 </script>
</head>

<body>

<input id="autocomplete" placeholder="Enter your address" type="text"></input>


</body>
</html>

我正在遵循代码,但仍然无法正常工作。我是不是哪里漏了?

您需要在 呈现 DOM 之后调用 initialize 。当前,您在 <input> 元素存在之前在文档的头部调用它。

<input> html 元素定义在文档中或在onload 事件上调用它(你引用的fiddle 是运行 JavaScript 在 onload 函数中)。

<style>
  #autocomplete {
    width: 300px;
  }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyB1Z4LA0_Q-qH3Sfq-vIr3lShYnIwS1KUw&libraries=places"></script>
<script>
  function initialize() {

    new google.maps.places.Autocomplete(
      (document.getElementById('autocomplete')), {
        types: ['geocode']
      });
  }
</script>

<input id="autocomplete" placeholder="Enter your address" type="text"></input>
<script>
  initialize();
</script>