离子地图在我第一次进入页面时加载但在导航后不加载

时间:2018-04-28 19:12:12

标签: javascript angular cordova typescript ionic-framework

我正在开发一个基于IONIC地理定位的远足应用程序,我一直在尝试加载地图但它总是第一次运行良好,但当我回到其他标签时,当我返回到该地图页面页面空白。

  

这是map-geolocation的代码

import { Component, ViewChild, ElementRef } from '@angular/core';
import {Navbar, NavController, NavParams, Platform} from 'ionic-angular';
import * as firebase from 'Firebase';
import { Geolocation } from '@ionic-native/geolocation';
import { Device } from '@ionic-native/device';
import {Hike} from "../../shared/hike";


declare var google: any;

@Component({
  selector: 'page-Geoloc',
  templateUrl: 'Geoloc.html'
  })
export class Geoloc {

@ViewChild('map') mapElement: ElementRef;
map: any;
markers = [];
ref = firebase.database().ref('geolocations/');
hike: Hike;

@ViewChild(Navbar) navBar: Navbar;
constructor(public navCtrl: NavController,
          public navParams: NavParams,
          public platform: Platform,
          private geolocation: Geolocation,
          private device: Device) {

this.hike = navParams.get('data');


}

initMap() {
this.geolocation.getCurrentPosition().then((resp) => {

  let mylocation = new 
  google.maps.LatLng(resp.coords.latitude,resp.coords.longitude);
  this.map = new google.maps.Map(this.mapElement.nativeElement, {
    zoom: 15,
    center: mylocation
  });
 });
 google.maps.event.trigger(this.map, 'resize');
 let watch = this.geolocation.watchPosition();
 watch.subscribe((data) => {
 this.deleteMarkers();
 this.updateGeolocation(this.device.uuid, 
 data.coords.latitude,data.coords.longitude);
 let updatelocation = new 
 google.maps.LatLng(data.coords.latitude,data.coords.longitude);
    let image = 'assets/imgs/blue-bike.png';
    this.addMarker(updatelocation,image);
    this.setMapOnAll(this.map);
  });
} 

 addMarker(location, image) {
   let marker = new google.maps.Marker({
   position: location,
   map: this.map,
   icon: image
  });
  this.markers.push(marker);
 }

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

 clearMarkers() {
 this.setMapOnAll(null);
 }

 deleteMarkers() {
   this.clearMarkers();
   this.markers = [];
 }

 updateGeolocation(uuid, lat, lng) {
     let timestamp = Date();
     if(localStorage.getItem('mykey')) {


firebase.database().ref('geolocations/'+localStorage.getItem('mykey')).set({
    uuid: uuid,
    latitude: lat,
    longitude : lng,
    timestamp : timestamp
  });
} else {
  let newData = this.ref.push();
  newData.set({
    uuid: uuid,
    latitude: lat,
    longitude: lng,
    timestamp : timestamp
  });
  console.log(newData.key);
  localStorage.setItem('mykey', newData.key);
  }
}

ionViewDidLoad() {
 this.navBar.backButtonClick = (e:UIEvent)=>{
   // todo something
   this.navCtrl.pop();
 }

 this.platform.ready().then(() => {
  this.initMap();
 });
 this.ref.on('value', resp => {
  this.deleteMarkers();
  snapshotToArray(resp).forEach(data => {
    if (data.uuid !== this.device.uuid){
      var currentTime = new Date().getSeconds();
      if (data.timestamp + 25 <= currentTime) {
        let image = 'assets/imgs/green-bike.png';
        let updatelocation = new google.maps.LatLng(data.latitude, data.longitude);
        this.addMarker(updatelocation, image);
        this.setMapOnAll(this.map);
      }
      else {
        let image = 'assets/imgs/blue-bike.png';
        let updatelocation = new google.maps.LatLng(data.latitude, data.longitude);
        this.addMarker(updatelocation, image);
        this.setMapOnAll(this.map);
      }
    }
    else {
      let image = 'assets/imgs/blue-bike.png';
      let updatelocation = new google.maps.LatLng(data.latitude, data.longitude);
      this.addMarker(updatelocation, image);
      this.setMapOnAll(this.map);
      }
    });
  });

}


}

export const snapshotToArray = snapshot => {
 let returnArr = [];

snapshot.forEach(childSnapshot => {
  let item = childSnapshot.val();
  item.key = childSnapshot.key;
  returnArr.push(item);
});

 return returnArr;
};

我通过更改生命周期元素并使用this.maps.remove()来尝试了一些解决方案;但他们不工作

1 个答案:

答案 0 :(得分:0)

当您在首次显示地图页面后离开地图页面时,地图附加到的原始DOM元素将被销毁。 因此,当您&#34;返回&#34;时,原生Google Maps UI元素会附加到不存在的DOM元素上。到你的地图页面,因为在你重新访问它时,Ionic实际上正在为你的地图页面重新创建一组新的DOM元素。

解决方案是在第一页显示初始创建地图后,在后续页面显示中调用setDiv()。 这将更新本机UI元素以附加到新创建的DOM元素。

在您的代码中:

export class Geoloc {

    mapInitialised = false;

    ionViewDidLoad() {

        if(this.mapInitialised){
            this.map.setDiv(this.mapElement.nativeElement);
        }else{
            this.platform.ready().then(() => {
                this.initMap();
                this.mapInitialised = true;
            });
        }
    }
}