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

Nuxt使用vue2-google-maps报google is not defined错误如何解决

问题原因

该报错由三类常见问题叠加导致:

  1. Nuxt SSR 环境下服务端编译阶段不存在全局google变量,直接调用全局google会触发编译报错
  2. 虽然调用了this.$gmapApiPromiseLazy(),但未接收回调返回的google实例,仍直接调用全局变量,API加载完成前全局google可能还未挂载到window对象上
  3. 谷歌地图Places服务需要单独配置加载,默认引入的地图SDK不包含该服务

修复步骤

步骤1:修改Nuxt配置文件(nuxt.config.js)

首先确认vue2-google-maps的配置中已经添加了places库,同时配置构建选项忽略服务端对google变量的校验:

// nuxt.config.js
export default {
  modules: [
    ['vue2-google-maps/nuxt', {
      load: {
        key: '你的谷歌地图API密钥',
        libraries: 'places', // 必须添加这行,否则Places服务无法使用
        region: 'JP',
        language: 'ja'
      }
    }]
  ],
  build: {
    extend(config, { isClient }) {
      if (isClient) {
        config.externals = config.externals || []
        config.externals.push({ google: 'google' })
      }
    }
  }
}

步骤2:修改业务代码,使用回调返回的google实例

不要直接调用全局google,改用$gmapApiPromiseLazy回调返回的实例,同时将实例传递给后续调用的方法:

// 仅修改script部分的相关方法,其余代码保持不变
export default {
  // ... 其余原有代码保持不变
  methods: {
    // ... 其余原有方法保持不变
    success(position) {
      this.maplocation.lat = position.coords.latitude
      this.maplocation.lng = position.coords.longitude
      // 接收回调返回的google实例
      this.$gmapApiPromiseLazy().then(google => {
        google.maps.event.addListenerOnce(
          this.$refs.mapRef.$mapObject,
          'idle',
          () => {
            // 将google实例传递给getBathroom方法
            this.getBathroom(google)
          },
        )
      })
    },
    // 新增参数接收google实例
    getBathroom(google) {
      const map = this.$refs.mapRef.$mapObject
      const placeService = new google.maps.places.PlacesService(map)
      placeService.nearbySearch(
        {
          location: new google.maps.LatLng(this.maplocation.lat, this.maplocation.lng),
          radius: 500,
          type: ['convenience_store'],
        },
        function (results, status) {
          if (status === google.maps.places.PlacesServiceStatus.OK) {
            results.forEach((place) => {
              const icon = {
                url: place.icon,
                scaledSize: new google.maps.Size(30, 30),
              }
              const marker = {
                position: place.geometry.location,
                icon,
                title: place.name,
                id: place.place_id,
              }
              this.markers.push(marker)
            })
          }
        }.bind(this),
      )
    },
  }
}

步骤3(可选):配置ESLint忽略全局google校验

如果项目开启了ESLint,还需要在.eslintrc.js中添加全局变量配置,避免校验报错:

module.exports = {
  globals: {
    google: true
  }
}

内容的提问来源于stack exchange,提问作者A.Hayashi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 13:15:07