'how to know the markers information that are clustered on marker clustering in agm

I want to know about the marker information that are grouped under marker clustering in AGM google Maps.

<agm-map #agmMap [latitude]="latitude" [longitude]="longitude" [zoom]="zoomMap" [fitBounds]="true"
         (boundsChange)="checkMarkersInBounds($event)" [scrollwheel]="null">
  <agm-marker-cluster [maxZoom]="maxZoom" [gridSize]="50" [averageCenter]="true"
                      imagePath="https://raw.githubusercontent.com/googlearchive/js-marker-clusterer/gh-pages/images/m">
    <agm-marker *ngFor="let data of mapArrayListAccordingParams;let i=index" [latitude]="data.latitude"
                [longitude]="data.longitude" [agmFitBounds]="true" [gestureHandling]="cooperative"
                (markerClick)="clickedMarker(infowindow,data);selectedEmp = data;newSelectedEmp.push(data)">
    </agm-marker>
  </agm-marker-cluster>
</agm-map>

This is the code i am using for clustering, i want to know the information about each marker which are clustered under one group.



Solution 1:[1]

Okay :) I have finally found a solution. So, here is the answer:

Create a directive, which you will use instead of agm-marker-cluster

Mine is named ct-marker-cluster

And what we need - is to change clusterclick default behavior.

I have removed the default handler.

And added a new one:

    this._clusterManager
      .getClustererInstance()
      .then((markerClusterer: MarkerClusterer) => {
        google.maps.event.addListener(
          markerClusterer,
          'clusterclick',
          (cluster) => {
            this.clusterClick.emit(cluster);
          }
        );
      });

Then, in your template pass an $event argument to the clusterClick event: <ct-marker-cluster (clusterClick)="onClusterClick($event)">

And finally:

onClusterClick(cluster: Cluster): void {
    cluster.getMarkers().map((marker: google.maps.Marker) => {
        console.log(marker);
        return marker.getZIndex(); // I needed to select zIndex only
    });
}

Full source code of the directive can be found below:

import {
  Directive,
  EventEmitter,
  Input,
  OnChanges,
  OnDestroy,
  OnInit,
  Output,
  SimpleChange,
} from '@angular/core';

import { Subscription } from 'rxjs';

import { InfoWindowManager, MarkerManager } from '@agm/core';
import {
  ClusterIconStyle,
  MarkerClustererOptions,
} from '@google/markerclustererplus';
import { Calculator } from '@google/markerclustererplus/dist/markerclusterer';
import { ClusterManager } from '@agm/markerclusterer';
import MarkerClusterer from '@google/markerclustererplus';
import { Cluster } from '@google/markerclustererplus/dist/cluster';

@Directive({
  selector: 'ct-marker-cluster',
  providers: [
    ClusterManager,
    { provide: MarkerManager, useExisting: ClusterManager },
    InfoWindowManager,
  ],
})
export class CtMarkerCluster
  implements OnDestroy, OnChanges, OnInit, MarkerClustererOptions
{
  /**
   * The grid size of a cluster in pixels
   */
  @Input() gridSize: number;

  /**
   * The maximum zoom level that a marker can be part of a cluster.
   */
  @Input() maxZoom: number;

  /**
   * Whether the default behaviour of clicking on a cluster is to zoom into it.
   */
  @Input() zoomOnClick: boolean;

  /**
   * Whether the center of each cluster should be the average of all markers in the cluster.
   */
  @Input() averageCenter: boolean;

  /**
   * The minimum number of markers to be in a cluster before the markers are hidden and a count is shown.
   */
  @Input() minimumClusterSize: number;

  /**
   * An object that has style properties.
   */
  @Input() styles: ClusterIconStyle[];

  /**
   * A function that calculates the cluster style and text based on the markers in the cluster.
   */
  @Input() calculator: Calculator;

  @Input() imagePath: string;
  @Input() imageExtension: string;

  /**
   * The name of the CSS class defining general styles for the cluster markers.
   * Use this class to define CSS styles that are not set up by the code that
   * processes the `styles` array.
   *
   * @defaultValue 'cluster'
   */
  @Input() clusterClass: string;

  /**
   * Whether to allow the use of cluster icons that have sizes that are some
   * multiple (typically double) of their actual display size. Icons such as
   * these look better when viewed on high-resolution monitors such as Apple's
   * Retina displays. Note: if this property is `true`, sprites cannot be used
   * as cluster icons.
   *
   * @defaultValue false
   */
  @Input() enableRetinaIcons: boolean;

  /**
   * Whether to ignore hidden markers in clusters. You may want to set this to
   * `true` to ensure that hidden markers are not included in the marker count
   * that appears on a cluster marker (this count is the value of the `text`
   * property of the result returned by the default `calculator`). If set to
   * `true` and you change the visibility of a marker being clustered, be sure
   * to also call `MarkerClusterer.repaint()`.
   *
   * @defaultValue false
   */
  @Input() ignoreHidden: boolean;

  /**
   * An array of numbers containing the widths of the group of
   * `<imagePath><n>.<imageExtension>` image files. (The images are assumed to
   * be square.)
   *
   * @defaultValue [53, 56, 66, 78, 90]
   */
  @Input() imageSizes: number[];

  /**
   * The tooltip to display when the mouse moves over a cluster marker.
   * (Alternatively, you can use a custom `calculator` function to specify a
   * different tooltip for each cluster marker.)
   *
   * @defaultValue ''
   */
  @Input() title: string;

  @Output() clusterClick: EventEmitter<Cluster> = new EventEmitter<Cluster>();

  private _observableSubscriptions: Subscription[] = [];

  constructor(private _clusterManager: ClusterManager) {}

  ngOnDestroy() {
    this._clusterManager.clearMarkers();
    this._observableSubscriptions.forEach((s) => s.unsubscribe());
  }

  ngOnChanges(changes: { [key: string]: SimpleChange }) {
    if (changes['gridSize']) {
      this._clusterManager.setGridSize(changes['gridSize'].currentValue);
    }
    if (changes['maxZoom']) {
      this._clusterManager.setMaxZoom(changes['maxZoom'].currentValue);
    }
    if (changes['zoomOnClick']) {
      this._clusterManager.setZoomOnClick(changes['zoomOnClick'].currentValue);
    }
    if (changes['averageCenter']) {
      this._clusterManager.setAverageCenter(
        changes['averageCenter'].currentValue
      );
    }
    if (changes['minimumClusterSize']) {
      this._clusterManager.setMinimumClusterSize(
        changes['minimumClusterSize'].currentValue
      );
    }
    if (changes['imagePath']) {
      this._clusterManager.setImagePath(changes['imagePath'].currentValue);
    }
    if (changes['imageExtension']) {
      this._clusterManager.setImageExtension(
        changes['imageExtension'].currentValue
      );
    }
    if (changes['calculator']) {
      this._clusterManager.setCalculator(changes['calculator'].currentValue);
    }
    if (changes['styles']) {
      this._clusterManager.setStyles(changes['styles'].currentValue);
    }
    if (changes['clusterClass']) {
      this._clusterManager.setClusterClass(
        changes['clusterClass'].currentValue
      );
    }
    if (changes['enableRetinaIcons']) {
      this._clusterManager.setEnableRetinaIcons(
        changes['enableRetinaIcons'].currentValue
      );
    }
    if (changes['ignoreHidden']) {
      this._clusterManager.setIgnoreHidden(
        changes['ignoreHidden'].currentValue
      );
    }
    if (changes['imageSizes']) {
      this._clusterManager.setImageSizes(changes['imageSizes'].currentValue);
    }
    if (changes['title']) {
      this._clusterManager.setTitle(changes['title'].currentValue);
    }
  }

  /** @internal */
  ngOnInit() {
    this._clusterManager.init({
      averageCenter: this.averageCenter,
      calculator: this.calculator,
      clusterClass: this.clusterClass,
      enableRetinaIcons: this.enableRetinaIcons,
      gridSize: this.gridSize,
      ignoreHidden: this.ignoreHidden,
      imageExtension: this.imageExtension,
      imagePath: this.imagePath,
      imageSizes: this.imageSizes,
      maxZoom: this.maxZoom,
      minimumClusterSize: this.minimumClusterSize,
      styles: this.styles,
      title: this.title,
      zoomOnClick: this.zoomOnClick,
    });

    this._clusterManager
      .getClustererInstance()
      .then((markerClusterer: MarkerClusterer) => {
        google.maps.event.addListener(
          markerClusterer,
          'clusterclick',
          (cluster) => {
            this.clusterClick.emit(cluster);
          }
        );
      });
  }
}

Solution 2:[2]

Here is the answer,

In your add attribute minimumClusterSize then only your cluster will be shown.

steps to do:

  1. install npm install @agm/js-marker-clusterer --save

  2. Import the module in your app.module.ts

    import { AgmJsMarkerClustererModule } from '@agm/js-marker-clusterer';

      imports: [
    BrowserModule,
    AgmCoreModule.forRoot({
      apiKey: ['YOUR_API_KEY_HERE']
    }),
    AgmJsMarkerClustererModule
    

    ]

  3. In app.component.html

<agm- map style="height: 300px" [latitude]="51.673858" [longitude]="7.815982"> <agm-marker-cluster [minimumClusterSize]= "minclusterSize" imagePath="https://raw.githubusercontent.com/googlemaps/v3-utility-library/master/markerclustererplus/images/m"> <agm-marker [latitude]="51.673858" [longitude]="7.815982"> </agm-map

  1. In app.component.ts

declare minclusterSize = 0 //default 0. for ex: if you want above 3 locations to cluster you need to change value as 3.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergej
Solution 2 Nishaly