1

In my ionic app, I want to display several maps in the same page. My code is given as below, but, when I run the script, I get an error as:

Uncaught TypeError: Cannot read property 'nativeElement' of undefined
   at HomePage.webpackJsonp.982.HomePage.initMap

Can you tell me where is wrong in my code?

home.ts

maps: google.maps.Map[];
...
@ViewChild('map') mapElement;
...
initMap(i){
    let latLng = new google.maps.LatLng(100, 100);
    let mapOptions = {
      center: latLng,
      zoom:0,
      scrollwheel: true,
      zoomControl: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
    };
    this.maps[i]  =  new google.maps.Map(this.mapElement.nativeElement, 
      mapOptions);
 }

ionViewDidLoad() {
   setTimeout(()=>{
       for(var j=0;j<5;j++){
          initMap(j);
       }
   }, 5000)
}

home.html

<ion-card  class="transparent-card" *ngFor="let number of [0,1,2,3,4]" >
  <div #map id="maps[number]" style="height:250px;"></div>
</ion-card>

1 Answer 1

1

You now have five elements with the identifier #map.

Is there some reason you cannot create a MapComponent and init the map on the component's ngOnInit:

MapComponent:

import { Component, ElementRef, OnInit } from '@angular/core';

@Component({
    selector: 'app-map',
    templateUrl: './app-map.html',
    styleUrls: ['./app-map.scss']
})
export class MapComponent implements OnInit {
    constructor(private readonly elem: ElementRef) {}

    map: google.maps.Map;

    ngOnInit(): void {
        let latLng = new google.maps.LatLng(100, 100);
        let mapOptions = {
            center: latLng,
            zoom: 0,
            scrollwheel: true,
            zoomControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        this.map = new google.maps.Map(
            this.elem.nativeElement,
            mapOptions
        );
    }
}

home.html

<ion-card *ngFor="let number of [0,1,2,3,4]">
  <app-map></app-map>
</ion-card>
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I need to separately mark the maps[i] lately according to number i. That is why I maps[] in my code.
In the real application, the number of maps is varies. it is not fix to 5.
How can I mark specific one of these 5 maps? any id or reference?
Without knowing more about what you are trying to achieve I cannot really help. You could interact with the MapComponents using Inputs and Outputs or by using a Service.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.