【问题标题】:Uncaught ReferenceError: google is not defined - Google MAP API未捕获的 ReferenceError:未定义 google - Google MAP API
【发布时间】:2020-10-04 13:45:56
【问题描述】:

我正在尝试让自动完成的 Google MAP API 正常工作。但是,每当我加载页面时,我都会收到错误“未捕获的 ReferenceError: google is not defined”

HTML

<label>Location</label>
<input id="location_field" type="text" class="form-control" placeholder="Location">

JAVASCRIPT

let locationField = document.getElementById('location_field');
let autocomplete = new google.maps.places.Autocomplete(locationField);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
     let place = autocomplete.getPlace();
     specifiedLocationObject = place;
});

我总是在这条线路上得到错误:

let autocomplete = new google.maps.places.Autocomplete(locationField);

【问题讨论】:

标签: javascript html google-maps google-maps-api-3


【解决方案1】:

我假设您包含对 Google Maps JS 脚本的引用。如果这是正确的,如果我不得不猜测,我会说您的 JavaScript 可能在 Google Maps 脚本完成处理之前正在运行。

解决方法是在 Google 地图脚本 URL 中包含一个回调函数,该函数可以在脚本完成加载时调用。然后,您可以在该回调函数中包装您希望执行的代码。

例子:

<script>
function initMap() {
    // your JS code, e.g....
    let locationField = document.getElementById('location_field');
    let autocomplete = new google.maps.places.Autocomplete(locationField);
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        let place = autocomplete.getPlace();
        specifiedLocationObject = place;
    });
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap"></script>

【讨论】:

    【解决方案2】:

    当然,另一个根本原因是您确实忘记在代码中导入 Google Maps JS 脚本。如果您使用角度,则方向为here,但在整个平台上通常相似。为后代复制的方向:

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2012-09-12
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多