如何将MarkerClusterer与我的地图一起使用

时间:2014-03-02 01:21:28

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

我想在我的地图上使用MarkerClusterer,但我不太清楚JavaScript。

如何将MarkerClusterer与我的地图一起使用?

我需要添加群集命令,但我不太了解编码。我的代码在下面

var LocationData = [ 

     [49.2814064, -123.1025187, "71 E Hastings St, Vancouver" ], 
     [49.2812336, -123.1020622, "122 E Hastings St, Vancouver" ], 
     [49.2813564, -123.1012253, "138 E Hastings St, Vancouver" ], 
    [49.2811625, -123.0985032, "242 E Hastings St, Vancouver" ]
];

function initialize() {
    var map =
        new google.maps.Map(document.getElementById('map_canvas'));
    var bounds = new google.maps.LatLngBounds();
    var infowindow = new google.maps.InfoWindow();

    for (var i in LocationData) {
        var p = LocationData[i];
        var latlng = new google.maps.LatLng(p[0], p[1]);
        bounds.extend(latlng);

        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: p[2]
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.setContent(this.title);
            infowindow.open(map, this);
        });
    }

    map.fitBounds(bounds);
}


google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(marker, 'click', function () {
    infowindow.setContent(p[2]);
    infowindow.open(map, marker);
});

2 个答案:

答案 0 :(得分:1)

您必须添加指向markersclusterer库的链接,如:

<script src='markerclusterer.js'></script>

一种可能的解决方案是构建一个标记数组,并将该数组一次添加到集群中。像:

function initialize() {
    var map =
        new google.maps.Map(document.getElementById('map_canvas'));
    var bounds = new google.maps.LatLngBounds();
    var infowindow = new google.maps.InfoWindow();

    var markers = [];
    var markerClusterer;

    for (var i in LocationData) {
        var p = LocationData[i];
        var latlng = new google.maps.LatLng(p[0], p[1]);
        bounds.extend(latlng);

        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: p[2]
        });

        markers.push(marker);

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.setContent(this.title);
            infowindow.open(map, this);
        });
    }

    map.fitBounds(bounds);

    markerClusterer = new MarkerClusterer(map, markers);
}

然后缩小以使群集可见。

答案 1 :(得分:0)

在您创建标记的循环中,您需要将您创建的每个标记存储在一个数组中,然后将对该地图和该数组的引用传递给该集群构造器:

var markers = [],
    i, l
    marker,
    markerCluster;

for (i = 0, l = LocationData.length; i < l; i += 1) {
    ...
    marker = new google.maps.Marker({ // whatever you need to pass in here });
    markers.push(marker);
}
markerCluster = new MarkerClusterer(map, markers);  

另外,避免使用for / in循环遍历数组,只使用常规for循环