Search code examples
angularleafletngx-leaflet

How to find bounds of multiple markers added to leafletLayer


I am working with ngx-leaflet in an Angular 6 project, I draw multiple markers in my map and I want to center and zoom a leaflet map on multiple Markers

In the official doc you can do it by using [L.latlngBounds] and find other solutions using L.featureGroup

Since I am using ngx-leaflet, I don't have L variable, so I can't find latlngBoundsand featureGroup

Here is my component:

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'
        })));
    }
}

}

And my template:

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

Thanks for your help


Solution

  • You have to import it

    If you want to use 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());
    

    EDIT: I overlooked the fact your are using ngx

    As you are using ngx-leaflet, you can get the map object in the leafletMapReady event

    Modify your directive:

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

    Modify your CustomComponent (adapt this example with the content of your ngOnInit method):

    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());
     }