【问题标题】:Is there a way to include an object prototype method in a google map callback?有没有办法在谷歌地图回调中包含对象原型方法?
【发布时间】:2019-06-14 16:52:23
【问题描述】:

我正在使用 Google maps dev 构建地图,问题是我需要以对象方式构建 javascript,当我在 script 标签中调用 Google API 时,它是回调中的一个简单函数。

<script src="https://maps.googleapis.com/maps/api/js?key={ApiKey}&callback=initMap"
async defer></script>

和上面一样,这里的函数默认是initMap。 我想将调用的函数设置为mapInit,就像我包含的代码中一样。

问题是地图没有显示出来,宽度和高度在 CSS 中很好,但如果 'function initMap(){}' 在我的 Map 对象的原型中,它不会初始化。

当然,当函数在外部时,它工作得很好。 所以,我很迷茫,如果有任何解决方案可以解决我的问题,我很乐意接受它们!谢谢

'use strict';

var Map = function () {
    this.mapInit();
};

Map.prototype.mapInit = function () {

};
 function initMap() {
        var map;
        map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 47.2173, lng: -1.5534},
            zoom: 10
}

提前致谢。

【问题讨论】:

    标签: javascript google-maps object


    【解决方案1】:

    您的回调函数需要可全局访问,以便地图 API 可以看到它。不过,您可以在该函数中初始化 Map

    var Map = function () {
      this.mapInit();
    };
    
    Map.prototype.mapInit = function () {
      // do the stuff you want to do
    };
    
    function initMap() {
      new Map();
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      相关资源
      最近更新 更多