在featureGroup上使用getBounds / fitBounds,其中ngx-leaflet为angular

时间:2018-06-01 20:08:26

标签: javascript angular leaflet fitbounds ngx-leaflet

在我创建的应用中,我动态地将一组点添加到嵌套地图点击事件中引用的featureGroup。所以要点是我有一个显示不同地区的国家的地图。单击一个区域可以使地图边界适合该多边形,并显示与该多边形相关联的点,让我们说一下城市。点击单个点/城市钻孔进一步向下钻取并显示与第一个单击点相关联的另一组点,例如所选城市中的所有库。

问题是,一旦我的最后一组点(库)位于featureGroup中(由于我的点击事件的嵌套特性,这是必要的),我无法在该组上使用fitBounds / getBounds。这是一个最小的例子(基于ngx-leaflet-tutorial-ngcli教程):

app.component.html

<div class="map"
  leaflet
  (leafletMapReady)="onMapReady($event)"
  [leafletOptions]="options"></div>

app.component.ts

import { Component, OnInit } from '@angular/core';

import * as L from 'leaflet';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  googleMaps = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
    maxZoom: 20,
    subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
    detectRetina: true
  });

  summit = L.marker([ 46.8523, -121.7603 ], {
    icon: L.icon({
      iconSize: [ 25, 41 ],
      iconAnchor: [ 13, 41 ],
      iconUrl: 'leaflet/marker-icon.png',
      shadowUrl: 'leaflet/marker-shadow.png'
    })
  });
  paradise = L.marker([ 46.78465227596462,-121.74141269177198 ], {
    icon: L.icon({
      iconSize: [ 25, 41 ],
      iconAnchor: [ 13, 41 ],
      iconUrl: 'leaflet/marker-icon.png',
      shadowUrl: 'leaflet/marker-shadow.png'
    })
  });

  fGroup = L.featureGroup();

  options = {
    layers: [ this.googleMaps, this.fGroup ],
    zoom: 7,
    center: L.latLng([ 46.879966, -121.726909 ])
  };

  onMapReady(map: L.Map) {
    this.paradise.addTo(this.fGroup);
    this.summit.addTo(this.fGroup);
    console.log(this.fGroup);
  }

  ngOnInit(){

  }
}

我使用console.log来显示featureGroup的输出:

NewClass {options: {…}, _layers: {…}, _initHooksCalled: true, _leaflet_id: 183, _mapToAdd: NewClass, …}
options: {}
_initHooksCalled: true
_layers: {184: NewClass, 186: NewClass}
_leaflet_id: 183
_map: NewClass {options: {…}, _container: div.map.leaflet-container.leaflet-touch.leaflet-retina.leaflet-fade-anim.leaflet-grab.leaflet-touch-…, _leaflet_id: 2, _containerId: 3, _fadeAnimated: true, …}
_mapToAdd: NewClass {options: {…}, _container: div.map.leaflet-container.leaflet-touch.leaflet-retina.leaflet-fade-anim.leaflet-grab.leaflet-touch-…, _leaflet_id: 2, _containerId: 3, _fadeAnimated: true, …}
_zoomAnimated: true
__proto__: NewClass

如您所见,没有_bounds方法可用。有没有办法将fitBounds装到ngx-leaflet中的featureGroup?

1 个答案:

答案 0 :(得分:1)

正如@ghybs指出的那样,直接在功能组上使用getBounds()实际 在此示例中工作。在我的真实应用中,事件是嵌套的,因此让fitBounds()工作的关键是每this documentation使用this.changeDetector.detectChanges()