所以我很抱歉,如果我把这里的条款搞砸了,我在Drupal中使用jQuery相对较新。我正在尝试用V3 API实现一个定制的Google应用程序。当我开始对模块进行模拟时,如果不将我的JS封装在闭包中,我就可以调用google函数回调。但是,由于需要使用jQuery函数,我需要将JS封装在闭包中,引用jquery,并将js附加到Drupal.behaviors对象。我遇到的问题是,现在看来,我的Google脚本标记上的回调超出了范围。我不确定这是由于关闭,是因为我加载脚本的方式,还是其他我还没有遇到的问题。我得到的特定JS错误是
Uncaught (in promise) message: "initMap is not a function" 我的JS模块是
(function ($) {
Drupal.behaviors.gmap_json = {
attach : function (context, settings){
var map, alumLayer, chapterLayer, assocLayer, userLayer;
function initMap() {
map = new google.maps.Map(document.getElementById('json-map'), {
zoom: 4,
center: {lat: 38.43, lng: -90}
});
alumLayer.setStyle({
icon: 'purple.png',
});
}
}
};
alert('it works');
}(jQuery));我的模块php是
function gmap_json_block_info() {
$blocks = array();
$blocks['gmap_json'] = array(
'info' => t('Google Maps with GeoJSON'),
);
return $blocks;
}
function gmap_json_block_view($delta = '') {
$block = array();
if ($delta == 'gmap_json') {
$block['subject'] = '';
$block['content'] = '';
}
$path = drupal_get_path('module', 'gmap_json');
drupal_add_js('https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap', 'external');
drupal_add_js($path. '/gmap_json.js', 'file');
return $block;
}那么,我做错了什么,如何才能将回调引入范围?或者是什么正确的方法来设置这个。
编辑:我已经尝试实现这两个答案,以及其中一个评论。
drupal_add_js('https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap', array('type' => 'external', 'defer' => 'defer'));通过数组添加“延迟”不会产生任何更改,而更改对js的调用顺序只会在错误被调用的地方更改。
发布于 2019-02-26 15:13:04
您可以/应该按照google (https://developers.google.com/maps/documentation/javascript/tutorial)的建议,将延迟标记添加到地图中(C0)。
您将获得更好的页面性能,并且应该解决您面临的问题,因为google地图代码总是在脚本之后加载的。
下面是如何添加延迟标记:如何实现_添加_js外部和延迟脚本
https://drupal.stackexchange.com/questions/276980
复制相似问题