在Google地图中添加标记时,IONIC V4应用程序关闭

时间:2019-03-24 06:11:19

标签: android angular firebase google-maps ionic4

我在使用Google地图和IONIC V4时遇到问题。我使用IONIC,Firebase和Google Maps创建了一个应用程序。在我的主视图中,我有一个Google Maps视图,其中添加了我存储在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 个答案:

答案 0 :(得分:0)

我意识到,当我不得不在Ionic的Google Maps内部的不同位置添加多个标记时,必须使用一组标记。要添加具有自定义标记的群集,您必须具有一个图标数组和一个数据数组。我为此创建了数组:

dir(str) 

在阵列storyPint中,我具有要添加到地图的标记的信息。我遍历了storyPint数组,并在每个数组中添加了所需的信息。

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

最后,我在Google地图地图中添加了标记簇,然后开始在markerCluster中监听MARKER_CLICK事件。

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

使用此解决方案,该应用不再崩溃。