使用JavaScript实施Google API时出错

时间:2018-10-16 07:16:36

标签: javascript google-maps

使用JavaScript实现google MAP API时出现以下错误。

错误:

**auto.html:14 Uncaught ReferenceError: google is not defined
    at auto.html:14
(anonymous) @ auto.html:14**

我正在提供以下代码。

auto.html:

<!DOCTYPE html>
<html>
<head>
    <title>Parent-Child Communication</title>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initService" async defer></script>
</head>
<body>
   <input id="searchTextField" type="text" size="50">
   <script type="text/javascript">
    function init() {
        var input = document.getElementById('searchTextField');
        var autocomplete = new google.maps.places.Autocomplete(input);
    }
    google.maps.event.addDomListener(window, 'load', init);
   </script>
</body>
</html>

我的要求是,当用户输入要自动建议的地名名称时,但在我的情况下会引发错误。

1 个答案:

答案 0 :(得分:0)

删除google.maps.event.addDomListener(window, 'load', init);,然后从以下位置更改脚本包括:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initService" async defer></script>

to(因此调用您的init函数):

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=init" async defer></script>

工作代码段:

<title>Parent-Child Communication</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=init" async defer></script>
<input id="searchTextField" type="text" size="50">
<script type="text/javascript">
  function init() {
    var input = document.getElementById('searchTextField');
    var autocomplete = new google.maps.places.Autocomplete(input);
  }
</script>