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

Timber主题中ACF地图数据传入Twig循环及谷歌地图多标记实现问题

解决Timber主题中ACF地图数据传入Twig生成谷歌地图标记的问题

别发愁,咱们一步一步来搞定这个事儿!你已经正确获取了所有发布的场馆数据,接下来只需要把ACF的地图数据整合到Twig模板里就行,Timber对ACF的支持其实很友好,不用太复杂的转换。

第一步:确认PHP端的数据传递(小优化)

你现有的PHP代码没问题,不过可以把变量名改成复数更贴合逻辑(毕竟是多个场馆),Timber会自动把每个场馆的ACF字段附加到Timber\Post对象上,所以不需要额外处理,直接传递就行:

$venue_query = array( 
    'post_type' => 'venue', 
    'posts_per_page' => -1, 
    'post_status' => 'publish' 
); 
// 改成复数$venues更合理
$context['venues'] = Timber::get_posts( $venue_query ); 
Timber::render( 'beesknees-participating-venues.twig', $context );

第二步:在Twig模板里处理地图和标记

假设你的ACF地图字段名为location(如果不是,记得替换成你自己的字段名),ACF地图字段返回的是包含lat(纬度)、lng(经度)、address(完整地址)等信息的数组。

下面是完整的Twig模板示例,包含谷歌地图初始化、循环生成标记,还有点击标记显示信息窗口的功能:

{# 引入谷歌地图API,替换成你自己的API Key #}
<script src="https://maps.googleapis.com/maps/api/js?key=你的API_KEY&callback=initMap" async defer></script>

<div id="map" style="width: 100%; height: 600px;"></div>

<script>
function initMap() {
    // 初始化地图,这里可以设置默认中心点(比如第一个场馆的坐标,或者城市中心)
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: { lat: {{ venues[0].location.lat }}, lng: {{ venues[0].location.lng }} }
    });

    // 循环遍历所有场馆,生成标记
    {% for venue in venues %}
        // 创建标记
        var marker{{ loop.index }} = new google.maps.Marker({
            position: { lat: {{ venue.location.lat }}, lng: {{ venue.location.lng }} },
            map: map,
            title: "{{ venue.title|escape('js') }}"
        });

        // 给标记添加信息窗口
        var infowindow{{ loop.index }} = new google.maps.InfoWindow({
            content: `
                <h3>{{ venue.title|escape('html') }}</h3>
                <p>{{ venue.location.address|escape('html') }}</p>
                <a href="{{ venue.link }}">查看详情</a>
            `
        });

        marker{{ loop.index }}.addListener('click', function() {
            infowindow{{ loop.index }}.open(map, marker{{ loop.index }});
        });
    {% endfor %}
}
</script>

关键注意事项

  • 字段名替换:如果你的ACF地图字段不是location,一定要把代码里的venue.location改成你实际的字段名(比如venue.map_address)。
  • 转义处理:用|escape('js')和|escape('html')处理动态内容,避免XSS安全问题和JS语法错误。
  • API Key:记得替换谷歌地图API链接里的你的API_KEY,不然地图加载不出来。
  • 默认中心点:如果场馆列表为空,venues[0]会报错,你可以加个判断,比如:
    center: { 
        lat: {% if venues is not empty %}{{ venues[0].location.lat }}{% else %}40.7128{% endif %}, 
        lng: {% if venues is not empty %}{{ venues[0].location.lng }}{% else %}-74.0060{% endif %} 
    }
    
    上面的默认坐标是纽约的,你可以换成自己需要的城市坐标。

这样就能在谷歌地图上显示所有场馆的标记啦!

内容的提问来源于stack exchange,提问作者Michael Ware

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:19:19