javascript - 如何定义多个位置 使用 Google Maps API 为循环生成的帖子列表中的每个帖子放置图钉

标签 javascript php wordpress loops google-maps-api-3

这个问题可能会在其他帖子中得到解答,但我还没有找到具体的答案,而且我无法辨别如何逻辑地思考这个问题。我有一个网站,每个帖子都有一个地址。在每个帖子页面上,我都使用 Google Maps API 将地址转换为 map 位置,并显示带有该地址处的图钉的 map 。效果很好。

我现在需要做的是在我的存档/类别/等页面(包含由查询和循环生成的帖子列表的页面)的顶部显示一个 map ,并为每个显示的帖子列出一个图钉在该特定查询中。我还需要 map 自动调整大小以显示所有引脚,而不是显示引脚边界之外的无关 map 。

发生这种情况的方式似乎是我可以使用循环内的脚本创建标记,这样每次循环运行时,它都会生成一个新标记并将其添加到 map 中。

另一种似乎有潜力的方法是将循环每圈的位置添加到数组中,然后在循环完成时显示引脚数组。

任何人都可以给我一些关于如何实现这一目标的建议吗?此时,我使用以下代码,它为我提供了 map 以及循环生成的列表中最后一篇文章的位置。这段代码位于循环之外。我需要知道应该在循环内移动哪一部分,以及如何调整它,这样我就不会在循环的每次迭代期间简单地重写标记。

<script type="text/javascript">
    function initialize() {
        geocoder = new google.maps.Geocoder();
        var mapOptions = {
            zoom: 3,
        }
        var myAddress = document.getElementById('theAddress');
        var address = myAddress.textContent;
        geocoder.geocode({
            'address': address
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,

                });


            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });

        var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

最佳答案

您需要在循环中添加标记。这是取 self 正在工作的一个项目。

var locations = ["Denver, CO, United States"];
var markers = [];
var iterator = 0;

for (var i = 0; i < locations.length; i++) {
    setTimeout(function() {
            geocoder.geocode({'address': locations[iterator]}, function(results, status){
        if (status == google.maps.GeocoderStatus.OK) {
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                animation: google.maps.Animation.DROP
            });
            bounds.extend(marker.getPosition());
            map.fitBounds(bounds);
        } else {
            log('Geocode was not successful for the following reason: ' + status);
        }
    });
    iterator++;

    }, i * 250);
}

关于javascript - 如何定义多个位置 使用 Google Maps API 为循环生成的帖子列表中的每个帖子放置图钉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25167596/

相关文章:

php - 注销用户 php 和 pdo 时出错

php - 页面刷新 WP PHP

javascript - 古腾堡预览缺少样式(仅在预览中,不在编辑器中)

php - 如何在 Underscores Wordpress 主题中创建第二个侧边栏?

WordPress tinyMCE 窗口管理器上传按钮未将 url 添加到文本字段

javascript - 没有括号的函数返回一个奇怪的输出

javascript - 当用户后退和上一个按钮时如何刷新下拉菜单

javascript - 我可以使用 JavaScript .value 属性将数据从一个 div 复制到另一个 div 吗?

php - WordPress 插件如何区分 WordPress

javascript ->= 和只是 > 之间有区别吗?