Ионная карта загружается при первом входе на страницу, но после перехода назад она не загружается - PullRequest
0 голосов
/ 28 апреля 2018

Я работаю над туристическим приложением, основанным на геолокации IONIC, я пытаюсь загрузить карту, но она всегда работает хорошо в первый раз, но когда я возвращаюсь на другие вкладки и когда я возвращаюсь на эту страницу карты, страница гаснет.

Это код карты-геолокации

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 голосов
/ 30 апреля 2018

Когда вы покидаете страницу карты после того, как она впервые отображается, исходный элемент DOM, к которому была прикреплена карта, уничтожается. Следовательно, собственный элемент пользовательского интерфейса Карт Google присоединяется к несуществующему элементу DOM, когда вы «возвращаетесь» на страницу своей карты, поскольку под капотом Ionic фактически воссоздает новый набор элементов DOM для вашей страницы карты при повторном посещении.

Решение состоит в том, чтобы вызвать setDiv () на последующих страницах, отображаемых после первоначального создания карты на первой странице отображения. Это обновит собственный элемент пользовательского интерфейса для присоединения к недавно созданному элементу 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;
            });
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...