向markerCluster添加更多标记而不删除之前的标记

时间:2016-08-29 12:08:38

标签: ruby-on-rails google-maps

我制作地图并添加标记。当我调用AJAX时,会有更多记录来自db并更新要映射的位置而不重新加载地图。但问题是它是为新记录制作新的集群。 这是代码:

var marker, i;
      var markers=[]
      for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
          position: new google.maps.LatLng(locations[i][1], locations[i][2]),
          map: map,
          icon: locations[i][4]
        });


        google.maps.event.addListener(marker, 'mouseover', (function (marker, i) {
          return function () {
            infowindow.setContent("<img src="+locations[i][5]+" width='100%'><br> <strong>"+locations[i][0]+"</strong>");
            infowindow.open(map, marker);
          }
        })(marker, i));

        // assuming you also want to hide the infowindow when user mouses-out
        marker.addListener('mouseout', function() {
            infowindow.close();
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
          return function () {
            infowindow.setContent("<img src="+locations[i][5]+" width='100%'><br> <strong>"+locations[i][0]+"</strong>");
            infowindow.open(map, marker);
          }
        })(marker, i));
        markers.push(marker);
      }

      var markerCluster = new MarkerClusterer(map, markers,{ 
          imagePath: 'https://cdn.rawgit.com/googlemaps/js-marker-clusterer/gh-pages/images/m'
        });

1 个答案:

答案 0 :(得分:3)

您可以添加标记

var markers = []
var marker = new google.maps.Marker({position: center});
markers.push(marker);
markerClusterer.addMarkers(markers);

请注意,我在这里只添加了一个。

您可以删除所有标记

markerClusterer.clearMarkers();
markers = [];

请注意,为了整洁,我还在这里取消了标记数组。

你可以通过 http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/docs/reference.html