Google新Place Autocomplete直接脚本加载失效求助
解决Google新版Place Autocomplete直接脚本加载失效问题
问题背景
迁移至Google新版Place Autocomplete组件,采用官方推荐的直接脚本加载标签方式时失效,原动态库导入方式可正常工作。替换脚本后出现两个错误:
Uncaught (in promise) ReferenceError: google is not definedUncaught (in promise) InvalidValueError: initMap is not a function
错误原因
- 模块作用域限制:JS代码以
type="module"引入,模块内的initMap函数默认处于私有作用域,无法被全局脚本的callback=initMap回调访问。 - 新版API加载逻辑变化:新版Place Autocomplete要求通过
google.maps.importLibrary("places")显式加载places库,直接加载脚本后不能直接调用google.maps.places下的类。
解决方案
核心调整点
- 将
initMap暴露到全局作用域,让脚本回调能找到该函数; - 保留新版API必需的
importLibrary加载逻辑; - 调整直接加载脚本的参数,指定新版API版本并保留异步加载配置。
完整代码示例
修改后的HTML
<!doctype html> <html> <head> <title>Place Autocomplete element</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <!-- 替换为指定新版API版本的直接加载脚本 --> <script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=weekly&loading=async&libraries=places&callback=initMap"> </script> <script type="module" src="./index.js"></script> </head> <body> <div class="place-autocomplete-card" id="place-autocomplete-card"> <p>Search for a place here:</p> </div> </body> </html>
修改后的JS(index.js)
async function initMap() { // 新版API必须显式加载places库 await google.maps.importLibrary("places"); const country = 'uk' const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement(); const card = document.getElementById('place-autocomplete-card'); card.appendChild(placeAutocomplete); placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); console.log('places return', place); await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location','addressComponents'] }); }); } // 将initMap挂载到全局window对象,供脚本回调调用 window.initMap = initMap;
额外注意事项
- 确保API密钥已启用Places API权限,且域名限制配置正确;
- 脚本参数中的
v=weekly可替换为beta或具体稳定版本号,按需选择API版本。
内容的提问来源于stack exchange,提问作者temple
相关产品推荐
相关产品推荐

