引入问题
使用 jaredpalmer/presspack 构建此主题对于 docker,我现在苦苦挣扎了几天,因为我尝试将这对 Google map 实例插入到每个页面都会调用的元素中。 map 无法加载,Chrome 告诉我我的函数不存在。
一些背景
Presspack正在为数据库提供服务,并使用yarn来构建环境。它将通用脚本和特定脚本分开保存,因为它有一个 common.js(我在其中编写了每个页面上应加载的所有内容)和一个 .js(仅在特定页面上加载)。我现在正在共同努力,因为我相信此联系部分将用于该网站的每个页面和博客文章。本节的调用函数为WP basic <?php get_template_part( 'content', 'contato-std' ); ?>
我在functions.php 中添加了一段代码,用于在页面页脚之后加载API key 脚本。
值得一提的是,我已经在另一个纯 HTML 环境中尝试了在 common.js 中使用的 js 代码。
我的文件
common.js
export default {
init() {
// JavaScript to be fired on all pages
console.log('common');
},
finalize() {
// JavaScript to be fired on all pages, after page specific JS is fired
var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (isMobile) { // Tudo o que for pra navegadores mobile
(...)
} else { // Tudo o que for pra navegadores padrão
(...)
// GOOGLE MAPS LOAD
var markers = [{
GPS1: -15.7954901,
GPS2: -47.8926766,
client_address: "Corpus - Fisioterapia & Pilates, Unidade Asa Sul"
}];
function initialize() {
initMap();
initMap2();
};
function initMap() {
var latlng = new google.maps.LatLng(-15.7954901, -47.8926766); // default location
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.MAP,
mapTypeControl: true
};
var map = new google.maps.Map(document.getElementById('mapaAsaSul'), myOptions);
var infowindow = new google.maps.InfoWindow(),
marker, lat, lng;
for (i = 0; i < markers.length; i++) {
lat = (markers[i].GPS1);
lng = (markers[i].GPS2);
name = (markers[i].client_address);
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
name: name,
map: map
});
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent(this.name);
infowindow.open(map, this);
}.bind(marker));
}
}
var markers2 = [{
GPS1: -15.7187167,
GPS2: -47.8867326,
client_address: "Corpus - Fisioterapia & Pilates, Unidade Lago norte"
}];
function initMap2() {
var latlng = new google.maps.LatLng(-15.7187167, -47.8867326); // default location
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.MAP,
mapTypeControl: true
};
var map = new google.maps.Map(document.getElementById('mapaLagoNorte'), myOptions);
var infowindow = new google.maps.InfoWindow(),
marker, lat, lng;
for (i = 0; i < markers2.length; i++) {
lat = (markers2[i].GPS1);
lng = (markers2[i].GPS2);
name = (markers2[i].client_address);
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
name: name,
map: map
});
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent(this.name);
infowindow.open(map, this);
}.bind(marker));
}
}
},
};
function.php
<?php
...
function add_google_maps() {
wp_enqueue_script(
'my-google-maps',
'http://maps.googleapis.com/maps/api/js?key=KEY&callback=initialize',
NULL,
NULL,
true
);
add_filter( 'script_loader_tag', function ( $tag, $handle ) {
if ( 'my-google-maps' !== $handle )
return $tag;
return str_replace( ' src', ' async defer src', $tag );
}, 10, 2 );
}
add_action('wp_enqueue_scripts', 'add_google_maps');
?>
处理来自common.js和.js的路由的JS是index.js
import jQuery from 'jquery';
import './style.scss';
import Router from './util/Router';
import common from './routes/common';
import home from './routes/home';
/**
* Populate Router instance with DOM routes
* @type {Router} routes - An instance of our router
*/
const routes = new Router({
/** All pages */
common,
/** Home page */
home
/** About Us page, note the change from about-us to aboutUs. */
});
/** Load Events */
jQuery(document).ready(() => routes.loadEvents());
错误响应
它应该加载相应 div 的 #mapaAsaSul 和 #mapaLagoNorte 中的两个 map 实例,但它不会,Chrome 的控制台会返回以下内容:
(index):1
Uncaught (in promise) Xc {message: "initialize is not a function", name: "InvalidValueError", stack: "Error↵ at new Xc (http://maps.googleapis.com/ma…KEY&callback=initialize:125:107"}message: "initialize is not a function"name: "InvalidValueError"stack: "Error↵ at new Xc (http://maps.googleapis.com/maps/api/js?key=KEY&callback=initialize:56:227)↵ at Object._.Yc (http://maps.googleapis.com/maps/api/js?key=KEY&callback=initialize:56:337)↵ at Uh (http://maps.googleapis.com/maps/api/js?key=KEY&callback=initialize:125:221)↵ at http://maps.googleapis.com/maps/api/js?key=KEY&callback=initialize:125:107"__proto__: Error
Promise.then (async)
Vh @ js?key=KEY&callback=initialize:125
google.maps.Load @ js?key=KEY&callback=initialize:21
(anonymous) @ js?key=KEY&callback=initialize:212
(anonymous) @ js?key=KEY&callback=initialize:212
这个初始化是用common.js编写的。该文件在控制台中列出,由 webpack(presspack 使用)显示为红色。
我正在运行此@localhost,因此无法提供此页面的链接。 如果我在格式化这篇文章时犯了任何错误或提供了错误的信息,我很抱歉。在堆栈中创建帖子方面没有真正的经验。 :(
非常欢迎对此问题的任何想法和想法。
编辑:按照埃文在评论中建议的方式纠正了该错误,其中调用的是 maps.google.com
而不是maps.googleapis.com
编辑2:由于 Evan 在评论部分不断帮助我,我对代码做了一些添加,如下所示。
在控制台中返回问题的回调函数已被删除,我将其替换为 common.js 上出现的 initialize 函数的新回调。
var markers = [{(...)}];
function initialize() {(...)};
function initMap() {(...)};
var markers = [{(...)}];
function initMap2() {(...)};
google.maps.event.addDomListener(window, 'load', initialize); //This is the new callback for my maps
自从第一张 map 出现以来,这确实解决了一些问题。尽管如此,控制台仍然会指出一些错误:
“未捕获的ReferenceError:i在初始化(common.js?a395:56)时未在initMap(common.js?a395:77)中定义”指向common.js的这一行:for (i = 0; i < markers.length; i++) {
。
我没听懂。只是猜测这与我的标记代码有关,因为第一个 map 是在 common.js 中进行回调后出现的,但没有标记。
然后,Evan 指出如果 i
是全局初始化的,这个错误是有道理的。所以他建议将代码更改为 (let i = 0; i < markers.length; i++) {
,这为我做了。将其添加到代码中标记的两个实例中,使两个 map 都正确显示并带有标记。
感谢您的帮助,埃文!
最佳答案
首先,应该通过https://maps.googleapis.com/
调用JavaScript API ,不是http://maps.google.com/
.
“初始化不是函数”范围错误可以通过在页面加载时同步加载 Maps API 脚本来解决,例如通过使用google.maps.event.addDomListener(window, 'load', initialize)
,但一般推荐的方法是通过回调异步加载 API:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initialize"></script>
然后两个标记循环都存在问题,例如for (i = 0; i < markers.length; i++)
,因为它们丢失了i
初始化。尝试使用for (let i = 0; i < markers.length; i++)
。
您可以找到here一个工作 jsbin,显示在上述代码更改后成功加载的 map 和标记。
关于javascript - 如何使用 jaredpalmer/presspack 与 Google map 集成构建主题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57616839/