Google Map "Reference Error Google not found" when running on mobile device


#1

I’ve used google map for my project. It works on the browser type “ionic serve”. But when I link through " ionic cordova run android" and run simulator with chrome inspect, the map does not appear and show “ReferenceError: google is not defined”.

this is my code.

index.html

<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyB2zG2HW7VihyFmjknMuyg9X60fjg6J9kM"></script>
  <script src="http://maps.google.com/maps/api/js"></script>

  <script src="cordova.js"></script>
  <script src="build/main.js"></script>
map.ts

import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams, Platform } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { CustomerRouteList } from '../custRoute-list/custRoute-list';
import { Changefont } from '../changefont/changeFont';
import { Storage } from '@ionic/storage';
import { CustRouteDetail } from '../custRoute-Detail/custRoute-detail';

declare var google:any;

@IonicPage()
@Component({
  selector: 'page-cust-route-detail-map',
  templateUrl: 'cust-route-detail-map.html',
  providers: [Changefont]
})

export class CustRouteDetailMapPage {

  @ViewChild('map') mapElement: ElementRef;
  map:any;

constructor(public navCtrl: NavController, public navParams: NavParams, 
              public geolocation: Geolocation,public changefont: Changefont,
              public storage: Storage, public platform: Platform) {
  
    this.storage.get('language').then((font) => {
      this.changelanguage(font);
    });
    //this.loadMap();
  }

ionViewDidLoad() {
    // this.platform.ready().then(() => {
    //   this.loadMap();
    // })
    this.loadMap();
    console.log('map called');
    //console.log('ionViewDidLoad CustRouteDetailMapPage');
  }

  loadMap() {
    this.geolocation.getCurrentPosition().then((position) => {
      let latLng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      let mapOptions = {
        center: latLng,
        zoom: 15
      }
      this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
      this.addMarker();
    },(error) => {
      console.log(error);
    });
  }

  addMarker() {
    let marker = new google.maps.Marker({
      map:this.map,
      animation: google.maps.Animation.DROP,
      position: this.map.getCenter(),
      icon: 'assets/green-dot.png'
    });
  }
}

this is the error


#2

You need to give the browser time to load the Google Maps API.

Try:

    setTimeout(() => {

      this.loadMap();

    }, 3000);

You should use a Service to load your Map API:

Or:


#3

when I load, this error has occurred
1212


#4

I’ve used “Google Map JavaScript API” and “cordova-plugin-geolocation”. It is find on browser but PositionError message appear when loading on device.