在特定缩放级别更改标记 - Google Maps API 3

时间:2014-01-10 09:35:06

标签: javascript google-maps google-maps-api-3 google-maps-markers

我有一张地图可以加载并正确显示一堆标记。标记的数量是无限的,因此它们是在初始化地图之前通过在javascript中运行一些PHP来创建的(标记来自数据库)。

我想知道,当达到某个缩放级别时,是否可以将标记从简单的点更改为其他内容?

以下是一些代码:

<script>
    var <?php echo $clinic_string; ?>; //string with marker names
    var map;

    function initialize() {
        var kzn = new google.maps.LatLng(-28.459033,30.217037);
        var mapOptions = {
            zoom: 7,
            center: kzn,
            mapTypeId: google.maps.MapTypeId.ROADMAP 
        }
        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

        <?php foreach($jsdata as $data) : ?>
            marker_<?php echo $data['id'];?> = new google.maps.Marker({
                position: new google.maps.LatLng(<?php echo $data['location'];?>),
                map: map,
                icon: 'images/reddot.gif'
            });
        <?php endforeach; ?>
    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

假设我的缩放级别达到15级,则需要将icon更改为images/clinic.gif

这可能吗?如果是这样,我怎么能实现这个目标呢?

1 个答案:

答案 0 :(得分:2)

不太难。您需要一个事件侦听器来处理map对象的zoom_changed事件。您可以使用标记的setIcon函数更改标记图标。类似的东西:

    <?php foreach($jsdata as $data) : ?>
        marker_<?php echo $data['id'];?> = new google.maps.Marker({
            position: new google.maps.LatLng(<?php echo $data['location'];?>),
            map: map,
            icon: 'images/reddot.gif'
        });

        map.addListener('zoom_changed', function() {
            if (map.getZoom() >= 15) {
                marker_<?php echo $data['id'];?>.setIcon('images/clinic.gif');
            } else {    // assuming you want to change it back if they zoom back out
                marker_<?php echo $data['id'];?>.setIcon('images/reddot.gif');
            }
        });
    <?php endforeach; ?>

事实上,我不是拥有X个'zoom_changed'事件监听器,而是想让我的所有标记都有一个数组。然后只有一个事件监听器函数,它循环遍历所有这些标记。

    markers = [];

    <?php foreach($jsdata as $data) : ?>
        marker_<?php echo $data['id'];?> = new google.maps.Marker({
            position: new google.maps.LatLng(<?php echo $data['location'];?>),
            map: map,
            icon: 'images/reddot.gif'
        });

        markers.push(marker_<?php echo $data['id'];?>);
    <?php endforeach; ?>

    map.addListener('zoom_changed', function() {
        var image;
        if (map.getZoom() >= 15) {
            image = 'images/clinic.gif';
        else {  // assuming you want to change it back if they zoom back out
            image = 'images/reddot.gif';
        }

        for (var i = 0; i < markers.length; i++) {
            markers[i].setIcon(image);
        }
    });