Uncaught ReferenceError: google is not defined - Google MAP API
Uncaught ReferenceError: google is not defined - Google MAP API
我正在尝试让自动完成 Google MAP API 工作。但是,每当我加载页面时,我都会收到错误 'Uncaught 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;
});
我总是在这个 lin 上遇到错误:
let autocomplete = new google.maps.places.Autocomplete(locationField);
我假设您包含对 Google Maps JS 脚本的引用。如果这是正确的,如果我不得不猜测,我会说在 Google 地图脚本完成处理之前,您的 JavaScript 可能是 运行。
解决此问题的方法是在 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>
另一个根本原因当然是您 确实 忘记在代码中导入 Google Maps JS 脚本。如果您使用的是 angular,则说明是 here,但在不同平台上通常是相似的。为后代复制的路线:
- 首先按照these steps获得一个API键,可用于加载Google地图。
- 载入 Google Maps JavaScript API.
- Google 地图 JavaScript API 必须在 Google 地图组件之前加载。
我正在尝试让自动完成 Google MAP API 工作。但是,每当我加载页面时,我都会收到错误 'Uncaught 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;
});
我总是在这个 lin 上遇到错误:
let autocomplete = new google.maps.places.Autocomplete(locationField);
我假设您包含对 Google Maps JS 脚本的引用。如果这是正确的,如果我不得不猜测,我会说在 Google 地图脚本完成处理之前,您的 JavaScript 可能是 运行。
解决此问题的方法是在 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>
另一个根本原因当然是您 确实 忘记在代码中导入 Google Maps JS 脚本。如果您使用的是 angular,则说明是 here,但在不同平台上通常是相似的。为后代复制的路线:
- 首先按照these steps获得一个API键,可用于加载Google地图。
- 载入 Google Maps JavaScript API.
- Google 地图 JavaScript API 必须在 Google 地图组件之前加载。