Приложение IONIC V4 закрывается при добавлении маркеров в карты Google - PullRequest
0 голосов
/ 24 марта 2019

У меня проблема с Google Maps и IONIC V4. Я создал приложение, используя IONIC, Firebase и Google Maps. В моем домашнем виде у меня есть вид карт Google, в который я добавляю маркеры, которые хранятся в Firebase. Я не понимаю, почему, когда я запрашиваю мой firebase firestore и там более 5 мест, приложение вылетает при вызове функции addMarkerSync.

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"));

      });

    });

  }


}

Есть идеи, почему мое приложение закрывается без причины?

1 Ответ

1 голос
/ 05 мая 2019

Я понял, что когда мне нужно добавить несколько маркеров в разных местах в Картах Google в Ionic, я должен использовать кластер маркеров.Чтобы добавить кластер с пользовательскими маркерами, вы должны иметь массив значков и массив данных.Для этого я создал массивы:

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

В массиве storyPint у меня есть информация о маркерах, которые я хочу добавить на карту.Я перебрал свой массив storyPint и добавил необходимую информацию в каждый массив.

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
  });
}

Наконец, я добавляю кластер маркеров на свою карту Google Maps и начинаю прослушивать события MARKER_CLICK в моем 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");
} 

С этим решением приложение больше не падает.

...