Google map API:仅将 MarkerClusterer 应用于特定标记的类别

Posted

技术标签:

【中文标题】Google map API:仅将 MarkerClusterer 应用于特定标记的类别【英文标题】:Google map API : apply MarkerClusterer only to a category of specific markers 【发布时间】:2018-04-15 01:14:09 【问题描述】:

使用 MarkerClusterer,我想只对一类标记进行聚类。 我这里有 10 个标记。我只想对其中的 8 个进行聚类,使用“类型”变量,即“cluster”或“nocluster”。

听起来很简单,但我没有找到任何提示... 有什么想法吗?

谢谢

<script>

    function initMap() 

      var map = new google.maps.Map(document.getElementById('map'), 
        zoom: 8,
        center: 
          lat: 48.371310,
          lng: 7.593634
        ,
        gestureHandling: 'cooperative'
      );

      var markers1 = locations.map(function(location, i) 

        var marker = new google.maps.Marker(
          position: location,
          type: location.type
        );

      );

      // Add a marker clusterer to manage the markers. 
      var mcOptions = gridSize: 50, maxZoom: 10, styles: [
        anchor:[0,0],
        textSize: 14,
        height: 50,
        width: 50
      ]
    ;

      var markerCluster = new MarkerClusterer(map, markers1, mcOptions);

     /* end FUNCTION initMap */

    var locations = [
            num: '1', type: 'cluster', lat: 49.050288, lng: 7.950412,
            num: '2', type: 'cluster', lat: 48.929413, lng: 7.852254,
            num: '3', type: 'cluster', lat: 48.926529, lng: 7.361955,
            num: '4', type: 'cluster', lat: 48.892072, lng: 7.655839,
            num: '5', type: 'cluster', lat: 48.887685, lng: 7.785195,
            num: '6', type: 'cluster', lat: 48.857382, lng: 7.321078,
            num: '7', type: 'cluster', lat: 48.856634, lng: 7.319182,
            num: '8', type: 'cluster', lat: 48.761871, lng: 7.967141,
            num: '9', type: 'nocluster', lat: 48.736924, lng: 7.709988,
            num: '10', type: 'nocluster', lat: 48.749944, lng: 7.340100
          ];

    google.maps.event.addDomListener(window, "load", initMap);

</script>

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

【问题讨论】:

【参考方案1】:

这很简单——如果你想要一个标记被聚集,然后将它添加到markerCluster,否则,只需使用marker.setMap(map)

google.maps.Marker 将忽略您传入的 type 键,因为它对它没有任何作用(此外,没有检索它的机制)所以您可能应该只创建两组标记:

var markersToCluster = [];
var markersToNotCluster = [];
locations.forEach(function(location, i) 
   var marker = new google.maps.Marker(position:location);
   location.type === 'something' ? markersToCluster.push(marker) : markersToNotCluster.push(marker);
);

var markerCluster = new MarkerClusterer(map, markersToCluster, mcOptions);
markersToNotCluster.forEach(function(m)  m.setMap(map); );

【讨论】:

以上是关于Google map API:仅将 MarkerClusterer 应用于特定标记的类别的主要内容,如果未能解决你的问题,请参考以下文章