谷歌地图回调ES6文件

Art*_* RV 5 javascript google-maps scope callback ecmascript-6

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

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

我的文件是这样的:

<div id="map"></div>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=<myKey>&callback=initMap"></script>
Run Code Online (Sandbox Code Playgroud)

我的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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Ion*_*zău 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);
};
Run Code Online (Sandbox Code Playgroud)

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

import * as mapObj from "./modules/map";
window.initMap = mapObj.initMap
Run Code Online (Sandbox Code Playgroud)