简体   繁体   中英

IONIC V4 app close when adding markers in google maps

I have a problem with google maps and IONIC V4. I created an app using IONIC, Firebase and google maps. In my home view I have a google maps view in which I add markers that I have store in Firebase. I do not why when I query my firebase firestore and there are more than 5 places, the app crashes when I call the addMarkerSync function.

import { Component, ViewChild } from '@angular/core';
import { MenuController, Platform, LoadingController, ToastController } from '@ionic/angular';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';
import { CompartirService } from '../services/compartir.service';
import { Compartir } from '../models/compartir';
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
import { environment } from '../../environments/environment';



import {
  GoogleMaps,
  GoogleMap,
  GoogleMapsEvent,
  Marker,
  MyLocation,
  LatLng
} from '@ionic-native/google-maps';
import { AngularFirestore } from 'angularfire2/firestore';
import { GoogleMapsAnimation } from '@ionic-native/google-maps/ngx';
import { Observable } from 'rxjs';

declare global {
  interface Window { my: any; }
}

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {


  usuario : Observable<any>;;
  map: GoogleMap;
  loading: any;
  latLong: any;

  //Lista donde se almacenan las historias
  stories: any[]=[];

  constructor(public loadingCtrl: LoadingController,public menuController: MenuController,public authService:AuthService,
    private router: Router,public compartirService:CompartirService,private db: AngularFirestore,
    private platform: Platform,
    public toastCtrl: ToastController,
    private androidPermissions: AndroidPermissions){
    this.menuController.enable(true);

    this.authService.user.subscribe(user => {
      if(user){
        console.log(user);
        this.usuario= this.db.doc("/usuarios/"+user.uid).valueChanges();

      }
    }); 

  }
  async ngOnInit() {
    //Carg mis historias de forma local
    await this.platform.ready();
    await this.loadMap();

    this.cargarMisHistorias()

  }


  loadMap() {
    console.log("Loading map")
    this.map = GoogleMaps.create('map_canvas', {
      camera: {
        target: {
          lat: 4.6028611,
          lng: -74.0657429
        },
        zoom: 18,
        tilt: 30
      }
    });
    this.loadCurrentPosition()


  }

  async loadCurrentPosition() {
    //this.map.clear();

    this.loading = await this.loadingCtrl.create({
      message: 'Localizando...'
    });
    await this.loading.present();

    // Get the location of you
    this.map.getMyLocation().then((location: MyLocation) => {
      this.loading.dismiss();
      console.log(JSON.stringify(location, null ,2));

      this.latLong = location.latLng;
      console.log(this.latLong);

      // Move the map camera to the location with animation
      this.map.animateCamera({
        target: location.latLng,
        zoom: 17,
        tilt: 30
      });



    })
    .catch(err => {
      this.loading.dismiss();
      this.showToast(err.error_message);
    });
  }

  async showToast(message: string) {
    let toast = await this.toastCtrl.create({
      message: message,
      duration: 2000,
      position: 'middle'
    });

    toast.present();
  }

  //retorna la lat y long.
  getLatLong() { 
    return this.latLong;
  }

  cargarMisHistorias(){
    this.map.clear();

    this.stories = [];
    this.db.collection('historias', ref => ref.where('userID', '==', this.authService.userDetails.uid)).get().subscribe( (querySnapshot) => {
      //querySnapshot.forEach((doc) => {
      for(var i=0;i<querySnapshot.size;i++){
        var doc = querySnapshot.docs[i];
        console.log(doc.data());
        console.log(doc.data().geoposition.geopoint);
        console.log(doc.data().geoposition.geopoint._lat);
        console.log(doc.data().geoposition.geopoint._long);
        var story = {
          id: doc.id,
          name: doc.data().name,
          pic: doc.data().imagen,
          geoposition: {
            Latitude: doc.data().geoposition.geopoint.latitude,
            Longitude: doc.data().geoposition.geopoint.longitude
          }
        }         
        this.stories.push(story);

      } 
      console.log("pintar marcadores");
      //Pintar marcadores
      this.pintarMarcadores();

    });
  }
  pintarMarcadores(){

    this.map.clear();


    console.log(this.stories);
    this.stories.forEach((story) => {
      console.log("Add marker");

      console.log(this.map);
      console.log(story);
      var marker=this.map.addMarkerSync({
        title: story.name,
        icon: { url : story.pic ,size: {
          width: 40,
          height: 40
        }},
        id:story.id,
        position: new LatLng(story.geoposition.Latitude,story.geoposition.Longitude),
        animation: GoogleMapsAnimation.BOUNCE,
        draggable:true
      });

      marker.on(GoogleMapsEvent.INFO_CLICK).subscribe((params: any) => {
        console.log(params);
        let marker: Marker = <Marker>params[1];
        this.router.navigateByUrl('/stories/'+marker.get("id"));

      });

    });

  }


}

Any idea why my app is closing without any reason?

I realized that when I have to add multiple markers in different locations inside Google Maps in Ionic I have to use a cluster of markers. To add a cluster with custom markers you have to have an icons array and a data array. I created to arrays for that purpose:

var icons = [];
var data = [];

In the array storiesPint I have the information of the markers I want to add to the map. I iterated over my storiesPint array and I add the information I need in each array.

for(var i=0;i<storiesPint.length;i++)
{
  var story = storiesPint[i];


  icons.push({ url : story.pic ,size: {
    width: 40,
    height: 40
  }})
  data.push({
    title: story.name,
    icon: { url : story.pic ,size: {
      width: 40,
      height: 40
    }},
    id:story.id,
    position: new LatLng(story.geoposition.Latitude,story.geoposition.Longitude),
    animation: GoogleMapsAnimation.BOUNCE,
    draggable:false
  });
}

Finally I add the marker cluster in my google maps map and I started listening for MARKER_CLICK events in my markerCluster.

if(this.map){
  var markerCluster = this.map.addMarkerClusterSync({
    markers: data,
    icons: icons
  });
  markerCluster.on(GoogleMapsEvent.MARKER_CLICK).subscribe((params) => {
    let marker: Marker = params[1];
    marker.setTitle(marker.get("title"));
    marker.showInfoWindow();
    marker.on(GoogleMapsEvent.INFO_CLICK).subscribe((params: any) => {
      let marker: Marker = <Marker>params[1];
      this.router.navigateByUrl('/stories/detail/'+marker.get("id"));

    });
  }); 


}
else{
  console.log("Map is null");
} 

With this solution the app is not crashing anymore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM