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

Nuxtjs集成vue2-google-map自定义组件时$mapPromise.then报错

错误修复方案与根源分析

错误根源

这个报错的核心是组件实例上的$mapPromise并非预期的Promise类型,常见触发场景:

  1. Nuxt服务端渲染阶段,Google Maps脚本未加载,vue2-google-map无法正确注入$mapPromise,导致该属性为undefined或非Promise值。
  2. 自定义组件未标记为客户端专属,服务端执行初始化逻辑时,$mapPromise未完成注入。
  3. 自定义组件未作为<gmap-map>的直接子组件使用,父组件的地图上下文未传递过来,$mapPromise不存在。
  4. vue2-google-map插件在服务端被错误注册,导致地图相关属性初始化异常。

修复步骤

1. 修正自定义DirectionsRenderer组件写法

确保组件仅在客户端初始化,且严格遵循MapElementFactory的规范:

// components/DirectionsRenderer.js
import { MapElementFactory } from 'vue2-google-map'

export default MapElementFactory({
  name: 'DirectionsRenderer',
  ctr: () => window.google.maps.DirectionsRenderer,
  // 强制仅在客户端创建组件
  clientOnly: true,
  events: [],
  mappedProps: {
    directions: { type: Object },
    routeIndex: { type: Number },
    suppressMarkers: { type: Boolean }
  },
  props: {
    options: { type: Object }
  },
  afterCreate(directionsRenderer) {
    if (this.options) {
      directionsRenderer.setOptions(this.options)
    }
  }
})

2. 调整Nuxt插件配置

确保插件仅在客户端注册,避免服务端加载Google Maps脚本:

// plugins/vue2-google-map.js
import Vue from 'vue'
import * as VueGoogleMaps from 'vue2-google-map'

// 仅客户端环境初始化插件
if (process.client) {
  Vue.use(VueGoogleMaps, {
    load: {
      key: '你的Google Maps API密钥',
      libraries: 'places,directions' // 必须包含directions库
    }
  })
}

在nuxt.config.js中标记插件为客户端专属:

export default {
  plugins: [
    { src: '~/plugins/vue2-google-map.js', mode: 'client' }
  ]
}

3. 调整地图页面的使用方式

用<client-only>包裹地图组件,避免服务端渲染地图相关内容:

<!-- pages/MapView.vue -->
<template>
  <client-only>
    <gmap-map
      :center="center"
      :zoom="13"
      style="width: 100%; height: 500px;"
    >
      <!-- 必须作为gmap-map的子组件使用 -->
      <directions-renderer :directions="directionsResult" />
    </gmap-map>
  </client-only>
</template>

<script>
import DirectionsRenderer from '~/components/DirectionsRenderer'

export default {
  components: { DirectionsRenderer },
  data() {
    return {
      center: { lat: 40.7128, lng: -74.0060 },
      directionsResult: null
    }
  },
  async mounted() {
    // 仅在客户端获取路线数据
    if (process.client) {
      const directionsService = new window.google.maps.DirectionsService()
      const response = await directionsService.route({
        origin: 'New York, NY',
        destination: 'Boston, MA',
        travelMode: 'DRIVING'
      })
      this.directionsResult = response
    }
  }
}
</script>

4. 排查上下文注入问题

确保自定义的DirectionsRenderer始终作为<gmap-map>的直接子组件使用,$mapPromise是由父地图组件注入的,脱离地图上下文使用会导致该属性缺失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:05:24