Accepted answer

1.when your page loaded, the view's value is 'list', the element map can't render on your page.so the mapRef is null,

2.the quesition is ngSwitchCase,when the ngSwitch value can't match ngSwitchCase,the element will not be rendered.

3.maybe you can use directive [hidden]  <div [hidden]="view!='list'"> </div> <div [hidden]="view!='map'"> </div>

you have to be careful with timing, and make sure your variable has actually been updated before you use it.

One useful trick for knowing when a @ViewChild value has been updated is to use a getter/setter.

private _mapElement: ElementRef;

@ViewChild("map", {static: false}) get mapElement(): ElementRef { return this._mapElement; }
set mapElement(newValue: ElementRef) {
  if (this._mapElement !== newValue) {
    this._mapElement = newValue;
    // Check that newValue is a defined value, and possibly perform actions here.
  }
}

using ionic 5 but its the same with 4. Moving the code to ionViewDidEnter() solve it with static:false. For you the solution will be:

ngOnInit() {
    
}
ionViewDidEnter(){
   this.museumData = this.placeDataService.getMuseums();
   this.displayGoogleMap();
   this.getMarkers();
}

You should have to mark 'true' the static here:

@ViewChild('map', {static: false}) mapContainer: ElementRef;

It will be:

@ViewChild('map', {static: true}) mapContainer: ElementRef;

it should works fine.


Look like you are trying to access the element when it not visible to DOM ,you can do is run setTimeOut or use ngAfterContentInit life cycle hook to wait for the DOM to be render

export class AppComponent implements OnInit, OnDestroy, AfterContentInit {

    public ngAfterContentInit(): void {
       const mapProp = {
           center: new google.maps.LatLng(6.9404, 79.8464),
           zoom: 15,
           mapTypeId: google.maps.MapTypeId.satellite
       };
       this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
    }
}

or use setTimeOut

initGMap = () => {
    const mapProp = {
      center: new google.maps.LatLng(6.9404, 79.8464),
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.satellite
    };
    setTimeout(() => {
         this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
    }, 3000);
  }