You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中使用Google Places API无回调实现自动补全报错解决方案

解决Google Places API无回调函数的初始化错误

核心原因

异步加载Google Maps JS API时,官方强制要求指定callback参数,用于API加载完成后触发初始化逻辑,否则会抛出Loading the Google Maps JavaScript API without a callback is not supported错误。

具体解决步骤

1. 修改API引入链接,添加callback参数

在index.html的<head>里,给API的script标签加上&callback=initGooglePlaces参数:

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script async src="https://maps.googleapis.com/maps/api/js?key=[KEY]&libraries=places&callback=initGooglePlaces"></script>
    <title>DocBay</title>
</head>

2. 定义全局回调函数,触发自定义事件

在index.html的<body>底部添加一个全局函数,这个函数会在API加载完成后触发一个自定义事件,通知组件可以初始化自动补全:

<body>
  <!-- 你的页面内容 -->
  <script>
    function initGooglePlaces() {
      // 触发自定义事件,告诉组件API已就绪
      window.dispatchEvent(new Event('googlePlacesReady'));
    }
  </script>
</body>

3. 组件内监听事件,执行初始化逻辑

在组件的onMounted钩子中,先检查API是否已经加载完成,若未完成则监听自定义事件,再执行自动补全的初始化:

onMounted(() => {
  // 封装初始化逻辑为单独函数
  function initAutocomplete() {
    autocomplete.value = new google.maps.places.Autocomplete(document.getElementById('autocomplete'), {
      componentRestrictions: { country: ['us'] },
      fields: ['address_components'],
      types: ['address']
    })
    autocomplete.value.addListener('place_changed', fillInAddress)
  }

  // 优先检查API是否已加载(处理缓存场景)
  if (window.google?.maps?.places) {
    initAutocomplete();
  } else {
    // 监听API就绪事件
    window.addEventListener('googlePlacesReady', initAutocomplete);
  }
})

额外说明

  • 把回调逻辑拆成全局事件通知的方式,既满足了API的callback要求,又不用在<head>里写组件相关的初始化代码,符合你的限制条件。
  • 添加缓存检查是为了避免API因浏览器缓存提前加载完成,导致自定义事件未被监听的情况。

内容的提问来源于stack exchange,提问作者capiono

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 01:25:25