Marker cluster number in a polygon or/and infowindow

☆樱花仙子☆ 提交于 2019-11-28 11:50:34

The simplest way to do this is to process through the Polygons in your "useTheData" function, which runs after the data is available after processing by geoxml3 and put the number of markers in the infowindow of the clicked polygon.

As you process the array of Placemarks to render the sidebar, also process each polygon to see how many markers it contains:

function useTheData(doc){
  var currentBounds = map.getBounds();
  if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
  // Geodata handling goes here, using JSON properties of the doc object
  sidebarHtml = '<table><tr><td><a href="javascript:showAll();">Show All</a></td></tr>';
  geoXmlDoc = doc[0];
  for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
    var placemark = geoXmlDoc.placemarks[i];
    if (placemark.polygon) { // processing a polygon
      // polygon highlighting
      var kmlStrokeColor = kmlColor(placemark.style.color);
      var kmlFillColor = kmlColor(placemark.style.fillcolor);
      var normalStyle = {
          strokeColor: kmlStrokeColor.color,
          strokeWeight: placemark.style.width,
          strokeOpacity: kmlStrokeColor.opacity,
          fillColor: kmlFillColor.color,
          fillOpacity: kmlFillColor.opacity
          };
      placemark.polygon.normalStyle = normalStyle;

      highlightPoly(placemark.polygon, i);

      // new code  
      var markersInPoly = 0;
      for (var mrkr=0; mrkr<gmarkers.length; mrkr++) {
        if (google.maps.geometry.poly.containsLocation(gmarkers[mrkr].getPosition(),placemark.polygon)) {
            markersInPoly++;
        }
      }
      placemark.numMarkers = markersInPoly;
      if (currentBounds.intersects(placemark.polygon.bounds)) {
        makeSidebarPolygonEntry(i);
      }
      clickablePolygon(placemark, "contains "+markersInPoly+" markers"); 
    }
// rest of processing (note if you will never have polylines, you can remove that code).

Function to add the number of markers to the polygon's infowindow:

function clickablePolygon(placemark, info) {
  google.maps.event.addListener(placemark.polygon, "click", function(e) {
    if (e && e.latLng) {
      infowindow.setPosition(e.latLng);
    } else {
      infowindow.setPosition(placemark.polygon.bounds.getCenter());
    }
    infowindow.setContent('<div class="geoxml3_infowindow"><h3>' + placemark.name +
               '</h3><div>' + info + '</div></div>');
    infowindow.open(map);
  });
}

working proof of concept

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!