Search code examples
angulargoogle-mapsmarkerclustererangular13

Angular map-marker-clusterer component doesn't work


I'm using the map as follow, but this doesn't works

<google-map #googleMap width="100%" height="100%" (idle)="initClusterer($event)">
  <map-marker-clusterer *ngIf="googleMap?.googleMap">
    <ng-container *ngFor="let i of items">
      <ng-container *ngIf="i.categories | haveCategory: targetCategory">
        <map-marker #markerElem [position]="i.position"> </map-marker>
      </ng-container>
    </ng-container>
  </map-marker-clusterer>
</google-map>
import { MarkerClusterer } from '@googlemaps/markerclusterer'

//...

@ViewChild('googleMap', { static: true }) googleMap: GoogleMap
markerCluster?: MarkerClusterer

// ...

initClusterer(e) {
    console.log('initClusterer', e)
    if (!this.googleMap?.googleMap || this.markerCluster) return

    console.log(this.googleMap, this.googleMap.googleMap)
    this.markerCluster = new MarkerClusterer({
      map: this.googleMap.googleMap,
      markers: this.markerElem,
    })
}

I did download the following dependencies npm i @googlemaps/markerclusterer
npm i @types/google.maps --save-dev

and not the markerclustererplus, because it is deprecated.

But I get the following error.

vendor.js:91237 ERROR Error: MarkerClusterer class not found, cannot construct a marker cluster. Please install the MarkerClustererPlus library: https://github.com/googlemaps/js-markerclustererplus
    at MapMarkerClusterer.ngOnInit (vendor.js:125746:15)

What did I did wrong ?

Environment

Angular: 13.2.3 CDK/Material: 13.2.3
@angukar/google-maps: 13.2.3
@types/google.maps: 3.47.4


Solution

  • The @angular/google-maps do have a bug and did import the incorrect library.

    The workaround is to add the following script in the head of your index.html file. (or as script in the angular.json file)

    <script src="https://unpkg.com/@googlemaps/markerclustererplus/dist/index.min.js" async defer></script>

    Still not working?

    You're surely loading the google-map object before you get the google map javascript ready.

    To fix this issue.

    1. npm i @googlemaps/js-api-loader Docs
    2. Add this piece of code I did it in a service and subscribed to an observable, but you just show the component once this is loaded. Up to you
    google?: any // Type somehow not working that great
    onMapApiDidLoad$: BehaviorSubject<any> = new BehaviorSubject(null)
        
    this.mapLoader
      .load()
      .then((google) => {
        this.google = google
    
        this.onMapApiDidLoad$.next(google)
      })
      .catch(() => {
        this.onMapApiDidLoad$.next(false)
      })