Границы недействительны

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

const group = L.featureGroup(this.markerLayers);
map.fitBounds(group.getBounds()); 

Однако я получаю сообщение об ошибке «границы недействительны». Я новичок в листовках, есть идеи, в чем проблема?

HTML:

<div class="leaflet-container grow z-0" leaflet [leafletOptions]="options" [leafletZoom]="leafletZoom" [leafletCenter]="leafletCenter" (leafletMapReady)="onMapReady($event)">
    <div [leafletLayer]="tileLayer"></div>
    <div *ngFor="let marker of markerLayers " [leafletLayer]="marker"></div>
  </div>

Компонент (моя попытка в функции onMapReady):

import { Component, Input, OnChanges } from '@angular/core';
import * as L from 'leaflet';
import { Roadtrip, Landmark } from '../../detour.model';
import { Subject } from 'rxjs/Subject';
import { DetourService } from '../../detour.service';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnChanges {
  @Input() selectedRoadTrip: Roadtrip;
  public fitBounds: L.LatLngBounds;
  public markers;
  public markerLayers: L.Marker[] = [];
  public leafletZoom = 8;
  public leafletCenter = L.latLng(57.335, -95.173);
  public tileLayer = L.tileLayer(
    'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
  );
  public iconImagePath: '/assets/icons/';
  public map$ = new Subject<L.Map>();
  public options = {
    zoomControl: false,
  };

  constructor(public detourService: DetourService) {}

  ngOnChanges() {
    if (this.selectedRoadTrip) {
      this.mapInit(this.selectedRoadTrip);
    }
  }

  mapInit(roadtrip: Roadtrip) {
    const landmark1 = roadtrip.landmarks[0];
    const landmark2 = roadtrip.landmarks[1];
    const landmark3 = roadtrip.landmarks[2];

    const marker1 = L.marker([landmark1.latitude, landmark1.longitude], {
      icon: L.icon({
        iconUrl: this.detourService.getLandmarkPinImage(landmark1.category),
        iconSize: [30, 48],
        iconAnchor: [15, 48]
      })
    });
    const marker2 = L.marker([landmark2.latitude, landmark2.longitude], {
      icon: L.icon({
        iconUrl: this.detourService.getLandmarkPinImage(landmark2.category),
        iconSize: [30, 48],
        iconAnchor: [15, 48]
      })
    });
    const marker3 = L.marker([landmark3.latitude, landmark3.longitude], {
      icon: L.icon({
        iconUrl: this.detourService.getLandmarkPinImage(landmark3.category),
        iconSize: [30, 48],
        iconAnchor: [15, 48]
      })
    });

    this.leafletCenter = L.latLng([roadtrip.latitude, roadtrip.longitude]);
    this.markerLayers = [marker1, marker2, marker3];
  }

  onMapReady(map: L.Map) {
    map.addControl(L.control.zoom({position: 'bottomright'}));
    map.scrollWheelZoom.disable();
    const group = L.featureGroup(this.markerLayers);
    map.fitBounds(group.getBounds());
    this.map$.next(map);
  }

  onLandmarkClick(val: Landmark) {
    this.leafletCenter = L.latLng(val.latitude, val.longitude);
  }
}

person Kode_12    schedule 19.06.2018    source источник
comment
Вы пытались напечатать значение group.getBounds() ?   -  person StephaneM    schedule 19.06.2018
comment
да, я только что попробовал, значение было просто пустым объектом.   -  person Kode_12    schedule 19.06.2018
comment
onMapReady() выполняется до ngOnChanges()? Если это так, вам придется дополнительно установить mapInit() внутри onMapReady().   -  person Neyxo    schedule 19.06.2018
comment
хм, я только что попробовал, никаких изменений   -  person Kode_12    schedule 19.06.2018
comment
«ngOnChanges» необходим, потому что мне нужно дождаться ввода данных асинхронной карты в компонент, прежде чем запускать карту для инициализации. Итак, сначала вызывается onMapReady.   -  person Kode_12    schedule 19.06.2018
comment
Звучит похоже на stackoverflow.com/questions/50650386/   -  person ghybs    schedule 26.06.2018