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



我对谷歌地图和IONIC V4有问题。我使用IONIC,Firebase和谷歌地图创建了一个应用程序。在我的主页视图中,我有一个谷歌地图视图,我可以在其中添加存储在Firebase中的标记。我不知道为什么当我查询我的火力商店并且有超过 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"));
      });
    });
  }

}

知道为什么我的应用程序无缘无故关闭吗?

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

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

在数组中 故事品脱 我有要添加到地图中的标记的信息。我遍历了我的 storiesPint 数组,并在每个数组中添加了我需要的信息。

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

最后,我在谷歌地图中添加了标记集群,并开始监听我的标记集群中的MARKER_CLICK事件。

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

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

相关内容

  • 没有找到相关文章

最新更新