javascript - 使用 webpack 时 Google map 无法访问回调函数

标签 javascript google-maps callback webpack

我正在使用 webpack 使用 Google map 构建一个小项目,但由于 webpack 构建脚本的方式,我在 google 访问回调函数时遇到了问题。我可以让 google 访问回调函数的唯一方法是手动将其移动到 webpack 构建的全局范围内。我想知道是否可以以不同的方式编写它,这样我就不需要手动更改捆绑的文件。

预构建:

import {apiKey} from './apiKey';

document.addEventListener('DOMContentLoaded', function(){

let lang;

if(document.querySelectorAll('#map').length > 0){
    if(document.querySelector('html').lang){
        lang = document.querySelector('html').lang;
    } else {
        lang = "en";    
    }

    let js_file = document.createElement('script');
    js_file.type = "text/javascript";
    js_file.src = 'https://maps.googleapis.com/maps/api/js?callback=initMapCallback&signed_in=true&key=' + apiKey + '&language=' + lang;
    document.getElementsByTagName('head')[0].appendChild(js_file);
};



});

   let map ;

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

构建后:

/* 0 */
/***/ function(module, exports, __webpack_require__) {

'use strict';

var _apiKey = __webpack_require__(1);

var map = void 0;

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

document.addEventListener('DOMContentLoaded', function () {

    var lang = void 0;

    if (document.querySelectorAll('#map').length > 0) {
        if (document.querySelector('html').lang) {
            lang = document.querySelector('html').lang;
        } else {
            lang = "en";
        }

        var js_file = document.createElement('script');
        js_file.type = "text/javascript";
        js_file.src = 'https://maps.googleapis.com/maps/api/js?callback=initMapCallback&signed_in=true&key=' + _apiKey.apiKey + '&language=' + lang;
        document.getElementsByTagName('head')[0].appendChild(js_file);
    };
});

  /***/ },
  /* 1 */
 /***/ function(module, exports) {

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
var apiKey = exports.apiKey = 'something';

/***/ }
/******/ ]);

最佳答案

当您在 IIFE 中使用 webpack 时,所有代码都在全局范围之外运行。如果您想让某些内容明确可用,您可以自己将其附加到窗口。

只需在函数定义后添加以下内容:

window.initMapCallback = initMapCallback;

或者在一行中完成:

window.initMapCallback = function initMapCallback() { /* ... */ };

就是这样!

关于javascript - 使用 webpack 时 Google map 无法访问回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38661579/

相关文章:

javascript - Google map 未按预期工作

javascript - .net session 超时和 Kendo 弹出窗口

ios - 我需要一个 API 来绘制航点并给我一条通过它们的路线,并给我城市人口。我应该使用哪个 API?

android - 如何在 Android Google Maps API 上平滑折线方向?

javascript - 此 jQuery getJSON AJAX 调用的回调方法存在问题

java - 如何安全地装饰现有的回调?

javascript - 自定义侧边栏嵌套菜单。我无法打开嵌套菜单

javascript - 从 inAppBrowser 设置的 localStorage 值未显示在外部 - Cordova

javascript - Fusion Tables 层中超过最大 URL 长度的请求

javascript - 如何将范围传递给 node-mysql 中的回调?