【问题标题】:How to find bounds of multiple markers added to leafletLayer如何找到添加到leafletLayer的多个标记的边界
【发布时间】:2019-06-16 04:42:27
【问题描述】:

我在 Angular 6 项目中使用 ngx-leaflet,我在地图中绘制了多个标记,我想在多个标记上居中并缩放传单地图

在官方文档中,您可以使用 [L.latlngBounds] 并使用 L.featureGroup 查找其他解决方案

由于我使用的是ngx-leaflet,所以我没有L变量,所以找不到latlngBoundsfeatureGroup

这是我的组件:

import {latLng, tileLayer, polygon, marker, Icon, LatLngBounds} from 'leaflet';

export class CustomComponent implements OnInit {

  options = {
    layers: [
      tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 18})
    ],
    zoom: 5,
    center: latLng(46.879966, -121.726909)
  };

  layers = [];
  fitBounds: LatLngBounds;
}

ngOnInit() {
    for (let i = 0; i < this.locations.length; i++) {
        this.layers.push(this.locations[i].y, this.locations[i].x].setIcon(
            new Icon({
                iconSize: [25, 41],
                iconAnchor: [13, 41],
                iconUrl: 'assets/icons/marker-icon.png',
                shadowUrl: 'assets/icons/marker-shadow.png'
        })));
    }
}

}

还有我的模板:

<div id="map" leaflet
             [leafletOptions]="options"
             [leafletLayers]="layers"
             [leafletFitBounds]="fitBounds">
        </div>

感谢您的帮助

【问题讨论】:

    标签: angular leaflet ngx-leaflet


    【解决方案1】:

    你必须导入它

    如果你想使用featureGroup():

    import {featureGroup, latLng, tileLayer, polygon, marker, Icon, LatLngBounds} from 'leaflet';
    
    
    const marker1 = marker([51.5, -0.09]);
    const marker2 = marker([50.5, -0.09]);
    
    const group = featureGroup([marker1, marker2]);
    
    group.addTo(map);
    map.fitBounds(group.getBounds());
    

    编辑:我忽略了您使用 ngx 的事实

    在使用ngx-leaflet时,可以在leafletMapReadyevent中获取地图对象

    修改你的指令:

    <div style="height: 300px;"
         leaflet 
         [leafletOptions]="options"
         (leafletMapReady)="onMapReady($event)">
    </div>
    

    修改您的CustomComponent(根据您的 ngOnInit 方法的内容修改此示例):

    onMapReady(map: Map) {
        const marker1 = marker([51.5, -0.09]);
        const marker2 = marker([50, -0.09]);
    
        const group = featureGroup([marker1, marker2]);
    
        group.addTo(map);
        map.fitBounds(group.getBounds());
     }
    

    【讨论】:

    • 你是如何使用map的?
    • 非常感谢,虽然它是一个快速的答案,但它做了一切
    猜你喜欢
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2020-06-08
    • 1970-01-01
    相关资源
    最近更新 更多