You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ACF Google Map偶发加载失败 报错google is not defined

错误原因

你遇到的google is not defined报错属于典型的脚本加载时序不匹配问题:你的地图初始化函数initMap执行时,Google Maps JS SDK 还没有完成加载、没有向全局注入google对象。偶尔加载正常是巧合下SDK加载速度快于初始化代码执行,多数场景下初始化代码先执行就会触发报错。

修复方案
  • 方案1:调整WordPress脚本入队依赖(最稳妥)
    在主题functions.php中修改脚本加载逻辑,明确指定地图初始化代码依赖Google Maps SDK,确保SDK加载完成后再执行初始化:
// 配置ACF谷歌地图API密钥
add_filter('acf/fields/google_map/api', function($api){
    $api['key'] = '替换为你自己的Google Maps API密钥';
    return $api;
});

// 统一入队地图相关脚本,明确依赖关系
add_action('wp_enqueue_scripts', function(){
    // 加载谷歌地图SDK,指定加载完成后自动回调initMap
    wp_enqueue_script(
        'google-maps-sdk',
        'https://maps.googleapis.com/maps/api/js?key=替换为你自己的API密钥&callback=initMap',
        array(),
        '1.0',
        true // 加载到页脚,避免阻塞页面渲染
    );
    // 加载自定义初始化脚本,依赖谷歌SDK和jQuery,保证加载顺序
    wp_enqueue_script(
        'custom-map-init',
        get_stylesheet_directory_uri() . '/js/map-init.js',
        array('google-maps-sdk', 'jquery'),
        '1.0',
        true
    );
});
  • 方案2:初始化代码增加加载状态校验
    如果你不想调整脚本入队逻辑,可以直接修改初始化代码,轮询判断google对象是否存在再执行初始化,兼容所有加载场景:
// 你的原有地图初始化逻辑
function initMap() {
    $('.acf-map').each(function(){
        const $el = $(this);
        const map = new google.maps.Map($el[0], {
            zoom: 16,
            center: new google.maps.LatLng($el.data('lat'), $el.data('lng'))
        });
        new google.maps.Marker({
            position: map.getCenter(),
            map: map
        });
    });
}

// 新增加载校验,避免提前执行报错
if (typeof google === 'undefined') {
    let timer = setInterval(() => {
        if (typeof google !== 'undefined') {
            clearInterval(timer);
            initMap();
        }
    }, 150);
} else {
    initMap();
}
  • 方案3:检查脚本加载属性
    如果你是直接在页面模版中硬编码了Google SDK的script标签,不要同时加async和defer属性,如果加了async必须保证初始化逻辑写在SDK的callback回调中,否则会随机出现时序错误。

内容的提问来源于stack exchange,提问作者Muhammed Muneer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:45:00