使用 Google Maps JavaScript API 加载器未定义“google”

Goo*_*n L 3 javascript google-maps vue.js

我有一个使用 Google Maps JavaScript API 加载器的 Vue CLI 项目。我使用下面的代码导入加载器:

import { Loader } from "@googlemaps/js-api-loader";
Run Code Online (Sandbox Code Playgroud)

之后,我定义了加载器,如下所示:

const loader = new Loader({
  apiKey: "XXXXX",
  version: "weekly",
  libraries: ["places"]
});
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试使用 google.maps.Map 对象显示地图时,我收到一条错误消息,指出“google”未定义。上面的所有代码都位于项目的“src”目录中的“main.js”文件中,下面的代码是最后一点,不幸的是,它触发了错误。

loader.load().then(() => {
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
});
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

PS 我按照 Google 文档中的说明使用 npm安装了@googlemaps/js-api-loader 。

小智 7

当承诺得到解决时,新包不会返回“google”对象,而是附加到window. 要像遵循 Vue 教程(我也在遵循)一样使用它,您需要添加:

this.google = window.google

到地图组件。为了清楚起见:

async mounted() {
   // As per the documentation for the google maps API loader
   const googleMapApi = await Loader({
       apiKey: this.apiKey
    })

    // This returns a promise, but not a 'google' object
    this.google = await googleMapApi.load();
    // Set the google object from the correct location
    this.google = window.google;
    this.initializeMap();
},

methods: {
    initializeMap() {
        const mapContainer = this.$refs.googleMap;
        this.map = new this.google.maps.Map(mapContainer, this.mapConfig);
    }
}
Run Code Online (Sandbox Code Playgroud)

我谈论的教程的参考:https://v2.vuejs.org/v2/cookbook/practical-use-of-scoped-slots.html