谷歌地图回调ES6文件

问题描述 投票:5回答:2

我试图在ES6文件上添加回调,但它找不到它。

我收到此错误消息:“initMap不是函数”

我的文件是这样的:

<div id="map"></div>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=<myKey>&callback=initMap"></script>

我的js文件是:

export function initMap()
{
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 8
    });

    fetch('/data/markers.json')
      .then(function(response){return response.json()})
      .then(plotMarkers);
}

我使用browserify和babelify来转换js文件

我试图上下移动并且到目前为止没有运气,唯一可行的方法是直接在html上添加initMap函数,如本指南所示:

https://developers.google.com/maps/documentation/javascript/adding-a-google-map

实际上我找不到/理解ES6上的函数在哪里运行(范围是什么)我在initMap函数中打印了这个值,它是未定义的。

javascript google-maps scope callback ecmascript-6
2个回答
8
投票

通过使用callback=initMap,谷歌地图预计initMap将成为全球性的。

您可以通过执行window.initMap = initMap将其公开为全局:

window.initMap = () => {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 8
    });

    fetch('/data/markers.json')
      .then(function(response){return response.json()})
      .then(plotMarkers);
};

另一种方法是import脚本并在另一个文件中公开全局,就像你提到的:

import * as mapObj from "./modules/map";
window.initMap = mapObj.initMap

0
投票

如果你想在没有转换的情况下提供你的ES6代码(使用总是被推迟的<script type="module">),你可能遇到同样的问题,上面的解决方案并不总是有效。

我认为问题是延迟脚本的执行顺序有点随机,如果API脚本在ES6代码之前运行,错误仍将显示。

您可以通过从API &callback=initMap中删除<script>并等待定义API来解决此问题:

const googleDefined = (callback) => typeof google !== 'undefined' ? callback() : setTimeout(() => googleDefined(callback), 100)

googleDefined(() => {
    // init map
})
...
© www.soinside.com 2019 - 2024. All rights reserved.