警告:Google 地图已在 @googlemaps/js-api-loader 外部加载

问题描述 投票:0回答:3

我正在尝试在 Nuxt3 中将 Google Maps API 的 AdvancedMarkerView 与 @googlemaps/js-api-loader 结合使用,以创建与此处找到的地图类似的地图。
我尝试使用 @googlemaps/js-api-loader 中找到的高级标记示例代码,但标记未显示在地图上。

这是示例代码:
https://github.com/googlemaps/js-api-loader/tree/main/examples


这是我的代码:

HTML:

<div id="canvas" ref="canvas" class="canvas"></div>

TypeScript-maps.vue:

import { Loader } from '@googlemaps/js-api-loader';

const map = ref<google.maps.Map>();
const canvas = ref<HTMLElement>();

const loader = new Loader({
   apiKey: *************,
   version: "weekly",
   libraries: ["places"],
});

const initMap = () => {
    loader.importLibrary('maps')
        .then(async ({Map}) => {
            map.value = new Map(canvas.value as HTMLElement, {
                center: { lat: 34.6937, lng: 135.5023 },
                zoom: 17,
                mapId: '**************',
            });
            const priceTag = document.createElement('div');
                priceTag.className = 'price-tag';
                priceTag.textContent = '$2.5M';
            const {AdvancedMarkerElement} = await loader.importLibrary('marker'); // Here is line186
            new AdvancedMarkerElement({
                map: map.value,
                position: { lat: 34.6937, lng: 135.5023 },
                content: priceTag,
            });
        })
        .catch((e) => {
            // do something
        });
}

onMounted(() => {
      initMap();
})

显示警告消息:

maps.vue:186 
Google Maps already loaded outside @googlemaps/js-api-loader.This may result in undesirable behavior as options and script parameters may not match.

如何修改代码以使标记显示在地图上?

PS:

我在codesandbox上创建了示例代码。

https://codesandbox.io/s/interesting-sun-4xzhnf?file=/src/App.vue

google-maps google-maps-api-3 nuxt.js
3个回答
0
投票

我发现了我的错误。 当我将其更改为不使用 ref 加载地图时,
标记已显示在地图上。

const map = new Map(canvas.value as HTMLElement, {...
new AdvancedMarkerElement({
             map,
             ...

但是,警告仍然显示,但我会暂时尝试使用地图。
非常感谢。


0
投票

它可能不会造成任何问题。但导入只是承诺,因此为了避免出现该消息(并且可能会获得微小的性能提升),您可以使用 Promise.all 一次性执行所有加载程序导入:

const loader = new Loader({
    apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
    libraries: ['places']
});

const importMaps = loader.importLibrary('maps');
const importMarker = loader.importLibrary('marker');

Promise.all([importMaps, importMarker])
  .then(
    () => console.info('Google Maps loaded with status ', loader.status),
    () => console.warn('Google Maps failed to load');
  );

0
投票

由于某种原因,常规

ref
会破坏 Vue 中的 Google 地图(
ref
会利用
Proxy
对象使您传递给它的任何对象都具有深度反应性)。

你必须使用浅的

ref

const map = shallowRef<google.maps.Map>();

Google Maps already loaded outside @googlemaps/js-api-loader
警告它不要调用
importLibrary
两次。尽管有这个警告,事情似乎仍然按预期进行;我不确定
importLibrary
应该如何使用,因为文档中不清楚,并且有一个关于此的开放问题:https://github.com/googlemaps/js-api-loader/issues/第837章

© www.soinside.com 2019 - 2024. All rights reserved.