Ionic Google maps Can not find the element [#map_canvas]

I have a Ionic App using google maps polyline to get latitude and longitude from data json api for flight route . l want to do reload data automatic , to see live data on map . l added set Interval to reload data. The data is reload and console , but l have error below and no live data showing on map .

ERROR Error: Uncaught (in promise): Error: Can not find the element [#map_canvas]
Error: Can not find the element [#map_canvas]
    at vendor.js:76400
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.js:2781)
    at Object.onInvokeTask (vendor.js:51333)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.js:2780)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (polyfills.js:2553)
    at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (polyfills.js:2856)
    at ZoneTask.invoke (polyfills.js:2845)
    at timer (polyfills.js:4639)
    at resolvePromise (polyfills.js:3189)
    at resolvePromise (polyfills.js:3146)
    at polyfills.js:3250
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.js:2781)
    at Object.onInvokeTask (vendor.js:51333)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.js:2780)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (polyfills.js:2553)
    at drainMicroTaskQueue (polyfills.js:2959)
    at push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask (polyfills.js:2860)
    at ZoneTask.invoke (polyfills.js:2845)

my code

 import { Component, OnInit } from '@angular/core';
import { ToastController, Platform } from '@ionic/angular';
import { HTTP } from '@ionic-native/http/ngx';
import { GoogleMap, GoogleMaps, Polyline, ILatLng, Marker } from '@ionic-native/google-maps';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-map-track-befor',
  templateUrl: './map-track-befor.page.html',
  styleUrls: ['./map-track-befor.page.scss'],
})
export class MapTrackBeforPage implements OnInit {

  map: GoogleMap;
  points: { lng: number, lat: number }[] = [];
  public myFlag = true;
  id: any
  callsign : any
  constructor(
    public toastCtrl: ToastController,
    private platform: Platform,
    private http: HTTP,
    private activatedRoute: ActivatedRoute) {
    this.activatedRoute.params.subscribe((params) => {
      this.id = params['id'];
      this.callsign = params['callsign']

    });

    setInterval(()=> {
      this.getmarker()
    },4000); 
    

  }

  async  ngOnInit() {
    await  this.platform.ready();
    await   this.getmarker();
    
  }

  async getmarker() {
    this.http.get('xxxxxxxxxx.json?flightId=' + this.id + '', {}, {})

      .then(data => {

        for (let datas of JSON.parse(data.data).result.response.data.flight['track']) {
          this.points.push({ lng: datas.longitude, lat: datas.latitude });
        }
        let AIR_PORTS = this.points;
        console.log(AIR_PORTS)
    
        this.map = GoogleMaps.create('map_canvas', {
          camera: {
            target: AIR_PORTS
          }
        });
    
        let polyline: Polyline = this.map.addPolylineSync({
          points: AIR_PORTS,
          color: '#AA00FF',
          width: 5,
          geodesic: true,
          clickable: true,
    
    
        });
        var mvcArray = polyline.getPoints();

        let marker: Marker = this.map.addMarkerSync({
          title: 'Ionic',
          icon: 'blue',
          animation: 'DROP',
          position:this.points[- 1]

        });
    
        let points: Array<ILatLng> = this.points = []
    
    

      })
  } 


  
}

html

  <div style="height: 100%;width: 100%" id="map_canvas"></div>

I think you have some problems with your timings. Can you ensure, that your Google Map(s) is fully loaded and ready to retrieve data?

Where and how you initialize your Google Map(s)?

Cheers
Unkn0wn0x

Thank you for replied , l updated full code now

Oh :slight_smile: Nice code, but at first glance I see many errors in the code.

First of all, do never execute code in your constructor.

Don’t fetch data in a component constructor. You shouldn’t worry that a new component will try to contact a remote server when created under test or before you decide to display it. Constructors should do no more than set the initial local variables to simple values.

First mistake
You are executing a 4s interval inside of your constructor without knowing, if the Google Map is ready to retrieve data.

Second mistake
You are initializing every time, you call getmarker to create a new map, marker and so on. You should prevent that. Create once a map, marker and so on and pass data into it.

Third mistake
Stick to a pattern in fact of declaring variables, do not mix var with const, let, etc. if you want to benefit from the features of typescript.

Without knowing your code, I’ve improved your code. Hopefully it helps you. You should only update your data and not creating every time a new map and / or marker.

import { Component, OnInit } from '@angular/core';
import { ToastController, Platform } from '@ionic/angular';
import { HTTP } from '@ionic-native/http/ngx';
import { GoogleMap, GoogleMaps, Polyline, ILatLng, Marker } from '@ionic-native/google-maps';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-map-track-befor',
  templateUrl: './map-track-befor.page.html',
  styleUrls: ['./map-track-befor.page.scss'],
})
export class MapTrackBeforPage implements OnInit {

  protected map: GoogleMap;
  protected marker: Marker;
  protected points: any 	=  { lng: number, lat: number }[] = [];
  protected myFlag: any 	= true;
  protected id: any 		= null;
  protected callsign: any 	= null;
  protected myInterval: any = null;


  constructor(
    public toastCtrl: ToastController,
    private platform: Platform,
    private http: HTTP,
    private activatedRoute: ActivatedRoute) {}

	async ngOnInit() {
		await this.initializeModule();    
	}

  async initializeModule() {

		await this.platform.ready();

		this.activatedRoute.params.subscribe((params) => {
			this.id = params['id'];
			this.callsign = params['callsign']
		});
		
		this.map = GoogleMaps.create('map_canvas', {
			camera: {
				target: this.points
			}
		});  

		// I don't know if it's the right way to create a marker, please checkout the Google Maps Documentation for it
		this.marker = this.map.addMarkerSync({
			title: 'Ionic',
			icon: 'blue',
			animation: 'DROP',
			position: this.points[- 1]
		});

		await this.getMarker();
  	}

  	async getmarker() {

		this.http.get('xxxxxxxxxx.json?flightId=' + this.id + '', {}, {})

		.then(data => {

			for (let datas of JSON.parse(data.data).result.response.data.flight['track']) {
			this.points.push({ lng: datas.longitude, lat: datas.latitude });
			}
		
			let polyline: Polyline = this.map.addPolylineSync({
				points: this.points,
				color: '#AA00FF',
				width: 5,
				geodesic: true,
				clickable: true,
			});
			
			// Unused variable? Do you require it?
			var mvcArray = polyline.getPoints();
		
			// Whatever you are doing here :-)
			let points: Array<ILatLng> = this.points = []
		
			// If no interval is set yet, create a new one
			if (!this.myInterval) {

				this.myInterval = setInterval(()=> {
					this.getmarker()
				}, 4000); 
				return;
			}
		});
  	}   
}

Hope it helps!

Cheers
Unkn0wn0x

l am really thank you for clarifying . After l copy and paste your edited code and run my app i get error

ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'polyline_704597448714' of undefined
TypeError: Cannot set property 'polyline_704597448714' of undefined
    at vendor.js:76726
    at GoogleMap.push../node_modules/@ionic-native/google-maps/index.js.GoogleMap.addPolylineSync (vendor.js:76735)
    at map-track-befor-map-track-befor-module.js:164
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (polyfills.js:2749)
    at Object.onInvoke (vendor.js:51342)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (polyfills.js:2748)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (polyfills.js:2508)
    at polyfills.js:3247
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.js:2781)
    at Object.onInvokeTask (vendor.js:51333)
    at resolvePromise (polyfills.js:3189)
    at polyfills.js:3254
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.js:2781)
    at Object.onInvokeTask (vendor.js:51333)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.js:2780)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (polyfills.js:2553)
    at drainMicroTaskQueue (polyfills.js:2959)

You’re welcome! Please never copy and paste code, without knowing, what it’s doing. This was just an example how to deal with your code in general.

To add polylines to a Google Map, checkout the dev docs for it:

There you can see simply, how to set / update polylines, funnily enough that there are flightroutes used as a example like in your case :-).

Cheers
Unkn0wn0x

Yes sure , l readed already , but you know for short time l did copy past . About the error , in my previous code above he was working fine and l he shows the flight routes , but when we update code l get that error .

Hello sir . l have problem , depending on your code , when l run my code l got empty page without any error in console . but if l move map_canvas inside getmarker() the map shows with flight route but l have error ERROR Error: Uncaught (in promise): Error: Can not find the element [#map_canvas] Error: Can not find the element [#map_canvas] while reloading data .