如何使用 jaredpalmer/presspack 和 Google 地图集成构建主题?

How to build a theme using jaredpalmer/presspack with Google Maps integration?

引入问题

使用 jaredpalmer/presspack 为 docker 构建这个主题,我已经苦苦挣扎了几天,因为我试图在一个元素中插入这对 Google 地图实例在每个页面中被调用。地图无法加载,Chrome 告诉我我的功能不存在。

一些上下文

Presspack为DB服务,使用yarn搭建环境。它为一般用途和特定用途分别保留脚本,因为它有一个 common.js - 我在其中编写它应该在每个页面上加载的所有内容 - 和一个 .js - 只在特定页面上加载。我现在正在处理 common,因为我相信这个联系部分将用在这个站点的每个页面和博客 post 上。本节调用函数为WP basic <?php get_template_part( 'content', 'contato-std' ); ?>

我在 functions.php 中添加了一个代码,用于在我的页面页脚之后加载 API 键脚本。

值得一提的是,我已经在另一个仅 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 中加载两个地图实例,但它不会和 Chrome 的控制台 returns 这:

(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

这个initialize写在common.js。该文件在控制台中列出,由 webpack(presspack 使用)显示为红色。

我是 运行 这个@localhost,所以无法为这个页面提供 link。 如果我在格式化此 post 时犯了任何错误或提供了错误的信息,我深表歉意。在堆栈中创建 posts 方面并没有真正的经验。 :(

欢迎就此问题提出任何想法。

编辑: 更正了 Evan 在评论中建议的错误,调用的是 maps.google.com 而不是 maps.googleapis.com

Edit2: 由于 Evan 一直在评论区帮助我,我对我的代码做了如下补充。

在控制台中返回问题的回调函数已被删除,我将其替换为出现在 [=85 上的 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

这确实解决了一些问题,因为第一张地图出现了。尽管如此,控制台仍会指出一些错误: "Uncaught ReferenceError: i is not defined at initMap (common.js?a395:77) at initialize (common.js?a395:56)" 指向 common.js 的这一行:for (i = 0; i < markers.length; i++) {

我没听懂。只是猜测它与我的标记代码有关,因为第一张地图出现在 common.js 回调之后,但没有标记。

然后,Evan 指出,如果 i 是全局初始化的,那么该错误是有道理的。所以他建议将代码更改为 for (let i = 0; i < markers.length; i++) {,它为我做了。将它添加到代码中标记的两个实例中,使两个地图都正确显示并带有标记。

感谢您的帮助,埃文!

首先,JavaScript API 应该通过 https://maps.googleapis.com/ 调用,而不是 http://maps.google.com/

"initialize is not a function" 范围错误可以通过在页面加载时同步加载地图 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。