Search code examples
angularionic4

TypeError: Cannot read property 'nativeElement' of undefined Ionic-v4


I am trying this example, In this example step 6 in getting an error. I try a few solutions but those are isn't working.

page.ts

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation/ngx';
import { PlaceDataService } from '../services/place-data.service';
declare var google: any;

@Component({
  selector: 'app-add-marker',
  templateUrl: './add-marker.page.html',
  styleUrls: ['./add-marker.page.scss'],
})
export class AddMarkerPage implements OnInit {

  @ViewChild('map', {static: false}) mapContainer: ElementRef;
  map: any;
  museumData = [];

  constructor(
    private geolocation: Geolocation,
    private placeDataService: PlaceDataService) { }

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

  displayGoogleMap() {
    const latLng = new google.maps.LatLng(28.6117993, 77.2194934);

    const mapOptions = {
      center: latLng,
      disableDefaultUI: true,
      zoom: 4,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    this.map = new google.maps.Map(this.mapContainer.nativeElement, mapOptions);
  }

  getMarkers() {
    // tslint:disable-next-line:variable-name
    for (let _i = 0; _i < this.museumData.length; _i++) {
      if (_i > 0) {
        this.addMarkersToMap(this.museumData[_i]);
      }
    }
  }

  addMarkersToMap(museum) {
    const position = new google.maps.LatLng(museum.latitude, museum.longitude);
    const museumMarker = new google.maps.Marker({ position, title: museum.name });
    museumMarker.setMap(this.map);
  }

}

page.html

<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>
    <ion-title>Museum in India</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <div #map id="map"></div>
</ion-content>

Please help


Solution

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

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

    After that, your code will works fine.

    It will be:

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