Search code examples
angulargoogle-mapsionic2long-polling

Ionic 2 - *ngFor over google maps disappears


<div *ngFor="let job of jobBoard">
        <div style="height: 200px">
          <!-- <div #map id="map"></div> -->
          <div #map id="jobBoard.jobBoardId"></div>
        </div>
</div>

I'm trying to figure out how to loop and keep adding map. I have a jobBoard card which displays job related information - category, earnings, etc. What I'm trying to figure out is how to loop over the jobBoard and keep adding maps to it as well.

Another challenge here is I am fetching data for jobBoard every 30 seconds, so if I keep calling

this.map = new google.maps.Map(this.mapElement[mapId].nativeElement, mapOptions);

new google.maps then the map flickers.

Here is the stackblitz: https://stackblitz.com/edit/ionic-map-test

If you stay on the page for about 15 seconds, the map disappears.

Update 1:

By using trackby:

<div *ngFor="let job of jobBoard; trackBy: trackByFn">

map comes up for the first item. But its still not showing for all the items in the loop.

  public trackByFn(index, jobBoard): void {
    return jobBoard.jobBoardId;
  }

Solution

  •   <div *ngIf="jobBoard">
        <div *ngFor="let job of jobBoard; trackBy trackByFn">
          <div style="height: 200px">
            <div style="height: 100%;width: 100%;display: block;" id="{{'map'+job.jobBoardId}}"></div>
          </div>
        </div>
      </div>
    

    And then on the .ts side:

    private loadMap(job: JobBoardInterface): void {
        console.log('loading map: ' + job.jobBoardId);
        var mapCanvas = document.getElementById('map' + job.jobBoardId);
        console.log("job.consumerGeo: ", job.consumerGeo);
        console.log("mapCanvas: ", mapCanvas);
        let lat: number = Number(job.consumerGeo.y);
        let lng: number = Number(job.consumerGeo.x);
        if (mapCanvas) {
          var Home_Map_Option = {
            center: { lat: lat, lng: lng }, // contractor's position
            zoom: 16,
            disableDefaultUI: true,
            mapTypeControl: false,
          }
          let map = new google.maps.Map(mapCanvas, Home_Map_Option);
          this.listOfAllMaps.push(map);
        }
      }
    

    Further: where I have the polling from server every few seconds:

      if (!this.isMapAlreadyLoaded) {
        this.isMapAlreadyLoaded = true;            
        this.loadONeTimeMap(this.jobBoard);
      }