简体   繁体   English

有没有办法在谷歌地图回调中包含一个对象原型方法?

[英]Is there a way to include an object prototype method in a google map callback?

I'm building a map with the Google maps dev, the problem is that I need to build the javascript in object way, and when I call the Google API in the script tag it's a simple function in the callback. 我正在使用Google地图开发构建地图,问题是我需要以对象方式构建javascript,当我在脚本标记中调用Google API时,它在回调中是一个简单的函数。

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

Like above the function here is initMap by default. 像上面一样,这里的函数默认是initMap I want to set the function called to be mapInit like in the code I included. 我想在我包含的代码中设置被称为mapInit的函数。

The problem is that the map doesn't show up, the width and height are good in the CSS but it won't initialize if the 'function initMap(){}' is in the prototype of my Map object. 问题是地图没有显示,CSS中的宽度和高度都很好但是如果'function initMap(){}'在我的Map对象的原型中,它将不会初始化。

And of course when the function is outside it works nice. 当然,当功能在外面时,效果很好。 So, I'm quite lost and if there are any solutions to resolve my problem I would gladly take them ! 所以,我很遗憾,如果有任何解决方案可以解决我的问题,我很乐意接受它们! Thanks 谢谢

'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
}

Thanks in advance. 提前致谢。

Your callback function needs to be globally accessible so that the Maps API can see it. 您的回调函数需要全局可访问,以便Maps API可以查看它。 You can initialize a Map in that function though: 您可以在该函数中初始化Map

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

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

function initMap() {
  new Map();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM