Help me pls javascript google map not work some time


#1

when open application some time application crash show this error affter that my app freeze screen

this index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title>Ionic App</title>
  <meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <!-- add to homescreen for ios -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  

  
  <!-- cordova.js required for cordova apps (remove if not needed) -->
  <script src="cordova.js"></script>
  
  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.error('Error', err));
    }
  </script>-->

  <link href="build/main.css" rel="stylesheet">

</head>

<body>

  <!-- Ionic's root component and where the app will load -->
  <ion-app></ion-app>
<script async defer src="https://maps.googleapis.com/maps/api/js?key="></script>
  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <!-- The vendor js is generated during the build process
       It contains all of the dependencies in node_modules -->
  <script src="build/vendor.js"></script>

  <!-- The main bundle js is generated during the build process -->
  <script src="build/main.js"></script>

</body>
</html>

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.19.1
    ionic (Ionic CLI) : 3.19.1

global packages:

    cordova (Cordova CLI) : 8.0.0 

local packages:

    @ionic/app-scripts : 3.1.7
    Cordova Platforms  : android 6.4.0 browser 5.0.3
    Ionic Framework    : ionic-angular 3.9.2

System:

    Android SDK Tools : 26.1.1
    Node              : v9.8.0
    npm               : 5.6.0 
    OS                : Linux 4.13

Environment Variables:

    ANDROID_HOME : /home/manzer/Android/Sdk

Misc:

    backend : pro

#2

You need to include your API key.

For example:

  <!-- Load Google Maps JavaScript API and Geometry library -->
  <script defer src="https://maps.google.com/maps/api/js?key=aaBBBcccDDDdddeeeFFF&libraries=geometry"></script>

#3

sure i include api key but i remove for post issue


#4

OK, try moving the script from the body into the head.


#5

same problem error some time


#6

Remove ‘async’:

<script defer src=

#7

when removed async application only crash and show

Uncaught ReferenceError: google is not defined

#8

The problem might be in the component the map is loaded in. Post your code from that component if you dont mind


#9

this code it’s work some time if i open app 10 times 8-9 times work

about 1-2 time crash above error

// import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { IonicPage, NavController , NavParams} from 'ionic-angular';
import { Component, ViewChild, ElementRef } from '@angular/core';
import { LoadingController } from 'ionic-angular';
import { RestProvider } from '../../providers/rest/rest';
import { Geolocation } from '@ionic-native/geolocation';
import { AlertController } from 'ionic-angular';
import { AngularFireDatabase } from 'angularfire2/database';
import * as firebase from 'firebase';
import SlidingMarker from 'marker-animate-unobtrusive';
import {
  GoogleMaps,
  GoogleMap,
  GoogleMapsEvent,
  GoogleMapOptions,
  CameraPosition,
  MarkerOptions,
  Marker
} from '@ionic-native/google-maps';
import { Platform } from 'ionic-angular';
// import { Observable } from 'rxjs/Observable';
/**
 * Generated class for the MapPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
declare var google:any;
@IonicPage()
@Component({
  selector: 'page-map',
  templateUrl: 'map.html',
})
export class MapPage {

  @ViewChild('map') mapElement: ElementRef;
  lat:any;
  lng:any;
  name:any;
  map: GoogleMap;
  location: any;
  // start:any;
  end:any;
  gps: any;
  distance: any;
  howtime: any;
  loader: any;
  cars: any;
  marker:any;
  markers: any = [];
  sloop = 0;
  iconEnd:any;
  iconStart:any
  directionsService:any;
  directionsDisplay:any;

  constructor(public platform: Platform, public loading:LoadingController, public db: AngularFireDatabase, public alertCtrl: AlertController, public navParams:NavParams,public navCtrl: NavController, public geolocation: Geolocation, public loadingCtrl: LoadingController, public restProvider: RestProvider) {

    this.lat = navParams.get("lat");
    this.lng = navParams.get("lng");
    this.name = navParams.get("name");
  
    this.end = {lat:this.lat, lng:this.lng};
    

  }

  users: any;

  ionViewDidLoad() {
      this.platform.ready().then(() => {    
        this.directionsService = new google.maps.DirectionsService;
        this.directionsDisplay = new google.maps.DirectionsRenderer;
        //กำหนดไอคอน
        this.iconEnd = {
          url: 'assets/icon/imhere.png',
          // This marker is 20 pixels wide by 32 pixels high.
          size: new google.maps.Size(60, 82),
          // The origin for this image is (0, 0).
          destination: new google.maps.Point(0, 0),
          // The anchor for this image is the base of the flagpole at (0, 32).
          anchor: new google.maps.Point(29, 82),
          rotation: ''
        };
        this.iconStart = {
          url: 'assets/icon/caricon.png',
          // This marker is 20 pixels wide by 32 pixels high.
          size: new google.maps.Size(60, 82),
          // The origin for this image is (0, 0).
          origin: new google.maps.Point(0, 0),
          // The anchor for this image is the base of the flagpole at (0, 32).
          anchor: new google.maps.Point(29, 82),
          rotation: ''
        };    
        //connect รถใน firebase
        this.cars = this.db.list('/car_gps/' + this.name).valueChanges();
        this.initMap();
        this.loader = this.loading.create({
          content: 'โปรดรอสักครู่...ระบบกำลังคำนวณเส้นทาง',
        });
        this.loader.present();
    });
  }
  ionViewWillLeave() {
    this.loader.dismiss();
  }
  carPosition()
  {
    return new Promise((resolve, reject) => {
      this.cars = this.db.list('/car_gps/' + this.name).valueChanges();
      resolve(this.cars);
      reject('error');
    });
  }
  getCurrentLocation(){

    let watch = this.geolocation.watchPosition();
    watch.subscribe((data) => {
      this.carPosition().then(result => {
        this.cars.forEach(element => {
          for (var i = 0; i < element.length; i++) {
            //นับจำนวนรอบ
            //เก็บจำนวนรถทั้งหมด
            if (i === 1)
              this.lat = element[i]
            if (i === 2)
              this.lng = element[i]
            if (i === 4) {
              this.name = element[i];
            }
          }
          this.end = { lat: this.lat, lng: this.lng };
          this.calculateAndDisplayRoute(this.end['lat'] + "," + this.end['lng'], data.coords.latitude + ',' + data.coords.longitude);
          console.log(this.lat);
          console.log(this.lng);
        });
      });
      // console.log(data.coords.longitude);
    });
    
  }

  initMap() {
    const options = {
      // center: location,
      zoom: 10
    }

    this.map = new google.maps.Map(this.mapElement.nativeElement, options);
    this.directionsDisplay.setMap(this.map);
    this.directionsDisplay.setOptions({ suppressMarkers: true });
    this.getCurrentLocation();
  }

  centerMap(lat, lng)
  {
    const location = new google.maps.LatLng(lat, lng);
    this.createMap(location);
  }

  createMap(location){
    const options = {
      center: location,
      zoom: 10
    }
    this.map = new google.maps.Map(this.mapElement.nativeElement, options);
  }
  addMarker(position, map, icon, i)
  {
    //เพิ่ม marker แบบ slide
     this.markers[i] = this.marker = new SlidingMarker({
      map: this.map,
      position: new google.maps.LatLng(position),
      icon: icon
    });
    
    this.marker.setDuration(10000);
    this.marker.setEasing('linear');

  }
  updateMarker(position, i)
  {
    //อัพเดทตำแหน่งเดิม
    this.markers[i].setPosition(new google.maps.LatLng(position));
  }

 clearLocations() {
   for (var i = 0; i < this.markers.length; i++) {
     this.markers[i].setMap(null);
   }
  
    this.markers.length = 0;
}

  calculateAndDisplayRoute(start, end) {
    
    var sp_start = start.split(",", 2); 
    var sp_end = end.split(",", 2); 
    
    console.log(Number(sp_start[0]));
    this.sloop++;

    var ss = { lat: Number(sp_start[0]), lng: Number(sp_start[1])};
    var ee = { lat: Number(sp_end[0]), lng: Number(sp_end[1])};

    //if not first round give update
    if(this.sloop === 1)
    {
      this.addMarker(ss, this.map, this.iconStart, 0);
      this.addMarker(ee, this.map, this.iconEnd, 1);
    }else{
      this.updateMarker(ss, 0);
      this.updateMarker(ee, 1);
    }

    this.directionsService.route({
      origin: start,
      destination: end,
      travelMode: 'DRIVING'
    }, (response, status) => {
      if (status === 'OK') {
        this.loader.dismiss();
        this.directionsDisplay.setDirections(response);
        this.distance = response['routes'][0]['legs'][0]['distance']['text'];
        this.howtime = response['routes'][0]['legs'][0]['duration']['text'];

      } else {
   
      }
    });
  }
  showAlert(message) {
    let alert = this.alertCtrl.create({
      title: 'New Friend!',
      subTitle: message,  
      buttons: ['OK']
    });
    alert.present();
  }  
}


#10

Ok, so you need to ensure that ‘Google Maps JavaScript API’ is loaded.

E.g., by moving the script from the body into the head. And, by removing ‘async’.

In your .ts do you:

...

import {} from '@types/googlemaps';

if (google) {

  ...

  this.map = new google.maps.Map(this.mapElement.nativeElement, opts);
}

#11

when removed async opened application 10 times show above error 10 times


#12

OK this issue resolve with removed async and defer