The cordova-plugin-googlemaps for Ionic 5 is currently initializing. It is recommended to wait for the platform to be ready before calling any

While I was working on implementing the marker cluster function, I encountered an error stating that cordova-plugin-googlemaps is not ready. The error message advised me to use platform.ready() before executing any methods. However, even after importing the platform statement, the issue persisted and the marker cluster was not displaying on the map. I am unsure of what exactly the error is pointing towards. If anyone has insight into this problem, please help. Thank you!

import { Component } from '@angular/core';
import { MarkersService } from '../services/markers.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ViewChild, ElementRef } from '@angular/core';

import { Plugins } from '@capacitor/core';
import { AngularFireAuth } from "@angular/fire/auth";
import { Observable } from 'rxjs';
import { AngularFirestoreCollection, AngularFirestore } from '@angular/fire/firestore';
import { map } from 'rxjs/operators';
import { MarkerCluster, GoogleMapsEvent, Marker } from '@ionic-native/google-maps';
import { marker } from 'leaflet';
import { Platform } from '@ionic/angular';
import { database } from 'firebase';
import { GoogleMapsService } from '../services/backup/google-maps.service';

const { Geolocation } = Plugins;

declare var google: any;

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

  @ViewChild('map', { read: ElementRef, static: false }) mapElement: ElementRef;
  infoWindows: any = [];
  map: any;
  markers: any = [];
  markerCluster: any;
  data: any;
  arr: any;

  locations: Observable<any>;
  locationsCollection: AngularFirestoreCollection<any>;
  user = null;
  watch = null;

  isTracking = false;
  mapCluster: any;

  constructor(private afAuth: AngularFireAuth, private afs: AngularFirestore, public platform: Platform, public googleMapsService: GoogleMapsService) {
  }

  anonLogin() {
    this.afAuth.signInAnonymously().then(res => {
      this.user = res.user;
      console.log(this.user);

      this.locationsCollection = this.afs.collection(
        `locations/${this.user.uid}/track`,
        ref => ref.orderBy('timestamp')
      );

      //load firebase data 
      this.locations = this.locationsCollection.valueChanges();
      //update map 
      this.locations.subscribe(locations => {
        console.log('new locations: ', locations);
        this.addMarker(locations);
      }); 
    });
  }

  ionViewWillEnter() {
    this.showMap();
  }

  showMap() {
    let latLng = new google.maps.LatLng(1.2902706, 103.851959);

    let mapOptions = {
      center: latLng,
      zoom: 11,
      disabledDefaultUI: false,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

    this.map.init().then((map) => {
      this.mapCluster.addCluster(map);
    });
  }

  addMarker(locations) {
    for (let loc of locations) {
      let latLng = new google.maps.LatLng(loc.lat, loc.lng);
      let marker = new google.maps.Marker({
        position: latLng,
        timestamp: loc.timestamp,
        latitude: loc.lat,
        longitude: loc.lng
      });
      marker.setMap(this.map);
      this.addInfoWindowToMarker(marker);
    }
  }

  addInfoWindowToMarker(loc) {
    let infoWindowContent = '<div id="content">' +
      //'<h2 id="firstHeading" class="firstHeading">' + loc.timestamp + '<h2>' +
      '<p>No. of fever cases: ' + loc.timestamp + '<p>' +
      //'<p>Longitude: ' + loc.longitude + '<p>' + 
      '</div>';
    let infoWindow = new google.maps.InfoWindow({
      content: infoWindowContent
    });

    loc.addListener('click', () => {
      this.closeAllInfoWindows();
      infoWindow.open(this.map, loc);
    });
    this.infoWindows.push(infoWindow);
  }

  closeAllInfoWindows() {
    for (let window of this.infoWindows) {
      window.close();
    }
  }

  startTracking() {
    this.isTracking = true;
    this.watch = Geolocation.watchPosition({}, (position, err) => {
      console.log('new position: ', position);
      if (position) {
        this.addNewLocation(
          position.coords.latitude,
          position.coords.longitude,
          position.timestamp,
        );
      }
    });
  }

  stopTracking() {
    Geolocation.clearWatch({ id: this.watch }).then(() => {
      this.isTracking = false;
    });
  }

  addNewLocation(lat, lng, timestamp) {
    this.locationsCollection.add({
      lat,
      lng,
      timestamp
    });

    let position = new google.maps.LatLng(lat, lng);
    this.map.setCenter(position);
    this.map.setZoom(9);
  }

  ngOnInit() {
    this.platform.ready().then(() => {
      this.anonLogin();
      this.showMap();
    })
  }
}

google-maps.service.ts

import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
//import { ConnectivityService } from './connectivity.service';
import { Geolocation } from 'ionic-native';
import { MarkerCluster, Marker } from '@ionic-native/google-maps';

@Injectable({
  providedIn: 'root'
})
export class GoogleMapsService {

  markerCluster: any;
  locations: any;

  constructor(public mapCluster: MarkerCluster) {

  }

  addCluster(map) {

    if (google.maps) {

      //Convert locations into array of markers
      let markers = this.locations.map((location) => {
        return new google.maps.Marker({
          position: location,
          label: "Hello!"
        });
      });

      this.markerCluster = new MarkerCluster(map, markers);

    } else {
      console.warn('Google maps needs to be loaded before adding a cluster');
    }

  }
}

Answer №1

Essentially, the key is to trigger your map initialization functions once the platform in question has fully loaded. Here's an example of how you can achieve this:

 ngOnInit() {
   this.platform.ready().then(() => {
     this.showMap();
   }
 }

Source

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"I am looking to retrieve the properties of an object that belongs to the EChartsOption type in TypeScript when working with Angular and ECharts. How

Currently, I am exploring how to access a property of an EChartOptions object in Angular 16.0.2, which may be undefined as I am still new to TypeScript. List of npm packages: eapp/src$ npm list <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Tips for ensuring the angular FormArray is properly validated within mat-step by utilizing [stepControl] for every mat-step

When using Angular Material stepper, we can easily bind form controls with form groups like [stepControl]="myFormGroup". But how do we bind a FormArray inside a formGroup? Constructor constructor(private _fb: FormBuilder){} FormArray inside For ...

Encountering a crash when trying to create a form within a subscription in Angular 2 due to the formGroup being

I have data stored in my Firebase database that I want to use in a form using FormBuilder. Although it generally works fine, I often encounter errors saying formGroup expects a FormGroup instance. Please pass one in.. What confuses me is that the error oc ...

Once an element is focused, the selection range's getClientRects method will result in a list that is void of any elements

Utilizing this code snippet to target the specified element const selectEnd = (element: HTMLElement, position: number) => { element.focus(); const range = document.createRange(); const sel = window.getSelection(); if (position !== -1) { ...

Prevent inspection of elements in Angular 2

Is there a way to prevent users from using inspect element on my website? I have disabled text selection, but users are still able to copy content through inspect element. ...

Troubleshooting: Facing the "jspdf__WEBPACK_IMPORTED_MODULE_2__.jsPDF is not a constructor" error while trying to utilize jsPDF in Angular 7?

I'm currently facing an issue with integrating jsPDF into my Angular 7.1.3 project. Here are the relevant sections from my package.json file: "dependencies": { "@angular/animations": "~7.1.0", "@angular/common": "~7.1.0", "@angular/compi ...

Is there a way to turn off the backdrop of angular material2's side nav?

I'm new to using Angular Material and I am looking for guidance on how to disable the backdrop of a side nav. I have created a working example on Plunker but the backdrop is still enabled. You can view it here. Here's what I've tried so far ...

Discover the power of Google Maps with Angular. Unlock the full potential of built

I'm currently working on a project involving Google Maps where I need to utilize the setZoom method upon clicking a custom button. The issue I'm encountering is that setZoom() returns undefined. I have loaded all necessary dependencies (the map s ...

Utilizing a Dependency Injection container effectively

I am venturing into the world of creating a Node.js backend for the first time after previously working with ASP.NET Core. I am interested in utilizing a DI Container and incorporating controllers into my project. In ASP.NET Core, a new instance of the c ...

What is the method for passing an element in Angular2 Typescript binding?

Is there a way to retrieve the specific HTML dom element passed through a binding in Angular? I'm having trouble figuring it out, so here is the relevant code snippet: donut-chart.html <div class="donut-chart" (donut)="$element"> ...

Utilize the automatically detected type of an object for utilization in a Generic context in Typescript

The Scenario I am experimenting with the combination of Alpine.js and TypeScript. To achieve this, I am utilizing the community-maintained typings package @types/alpinejs (GitHub) along with the reusable components design pattern outlined here. Here' ...

Tips for assigning the 'store_id' value to a variable in Angular 6 within the Ionic4 environment

Trying to retrieve the store_id from the StorageService in Ionic4 (angular 6). Managed to retrieve the store_id using: let id = this.storageService.get('store_id'); id.then(data => { this.store.push(data) }); After pushing it into an ar ...

How can I send 'blocking' parameter to getStaticPaths function in Next.js using TypeScript?

Whenever I try to use fallback: 'blocking', in my Next.js page, TypeScript throws an error. I am using the latest 12.2.0 version of Next.js. What could be causing this issue? Type '() => Promise<{ paths: any; fallback: string; }>&ap ...

Having trouble with the on-screen keyboard functioning with a customized input field

I am encountering an issue while trying to integrate an on-screen keyboard with a customized input field. The error message I receive is ERROR TypeError: Cannot read properties of undefined (reading 'substr'. Surprisingly, the keyboard functions ...

Issue: NG0900: Encountered an error while attempting to differentiate '[object Object]'. Only arrays and iterables are permitted

I'm currently working on the frontend development of a crud application. While implementing lazy pagination, I encountered an error Error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed I have search ...

New color scheme in Visual Studio Code for JavaScript and TypeScript files within Visual Studio 2017

I am interested in importing or setting a Visual Studio Code color theme for JavaScript and TypeScript files in Visual Studio 2017. Specifically, I would like to customize the color theme for files with extensions: .js, .jsx, .ts, and .tsx. If individual f ...

Consuming AMQP in Node.js using Typescript

After diving into node.js/typescript for the first time, I encountered a challenge when trying to create a consumer for a rabbit queue. Check out the code snippet below: let amqp = require('amqp'); let connection = amqp.createConnection({url: ...

Challenges in Displaying Components in React with Typescript

I'm currently facing an issue where the content I am trying to render on my screen is not appearing. Although the function correctly enters the if conditional statement, as confirmed by console logging. This is the section where I have implemented th ...

Incorporate @ngx-translate into individual components within Angular 17 for enhanced translation capabilities

I have encountered an issue while using standalone components in Angular 17. Interestingly, when I used module architecture, this problem did not arise. By adding the necessary import to 'AppModule', everything worked perfectly. imports: [ Trans ...

Issues may arise in Typescript when trying to return an array of data from a redux createAsyncThunk function

Below is the code I am using to retrieve a list of users: export const fetchUserById = createAsyncThunk( "users/fetchById", async (_, { rejectWithValue, fulfillWithValue }) => { try { const response = await fetch(`https://reqres. ...