3

我正在尝试实现一个传单地图,其中缩放级别动态封装了我的 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);
  }
}
4

0 回答 0