AGM Map: set the zoom level to include all markers
Asked Answered
M

1

5

To set the map zoom level to include all the location markers, I have tried two options as suggested in this post.

Here's what I did:

export class LocationSelectionComponent implements OnInit, AfterViewInit {

@ViewChild('AgmMap') agmMap: AgmMap;

ngAfterViewInit() {
  console.log(this.agmMap);
  this.agmMap.mapReady.subscribe(map => {
  const bounds: LatLngBounds = new window['google'].maps.LatLngBounds();
  for (const mm of this.mapMarkers) {
    if (mm.latitude !== this.currentLocationLatitude && mm.longitude !== this.currentLocationLongitude) {
      bounds.extend(new window['google'].maps.LatLng(mm.latitude, mm.longitude));
     }
   }

   map.fitBounds(bounds);
  });
 }
}

Note that this.mapMarkers is an array which contains the coordinates for the map markers. These are populated in ngOnInit().

As mentioned in the comment of the above post, I've also tried the following:

onMapReady(map: AgmMap) {
 const bounds: LatLngBounds = new window['google'].maps.LatLngBounds();
 for (const mm of this.mapMarkers) {
   if (mm.latitude !== this.currentLocationLatitude && mm.longitude !== this.currentLocationLongitude) {
     bounds.extend(new window['google'].maps.LatLng(mm.latitude, mm.longitude));
   }
 }

 // @ts-ignore
  map.fitBounds(bounds);
}

then in HTML:

  <agm-map #AgmMap [latitude]="latitude" [longitude]="longitude"
                   [fullscreenControl]="true" [mapTypeControl]="true" (mapReady)="onMapReady($event)">
            <agm-marker *ngFor="let m of mapMarkers; let i = index"
                        [latitude]="m.latitude"
                        [longitude]="m.longitude"
                        [title]="m.title"
                        [iconUrl]="m.iconUrl"
                        [animation]="m.animation"
                        (markerClick)="clickedMarker(m.label)">
            </agm-marker>
          </agm-map>

But in both instances, I don't get the map zoomed out as I expect. The reason is, when I debug the code, the mapMarkers array is empty in both instances. How do I fix this?

Mckinley answered 27/12, 2018 at 8:57 Comment(1)
I just figured out, it's much more easier. You don't have to do it manually, all you have to do is to add [fitBounds]="true" to the <agm-map> and [agmFitBounds]="true" to the <agm-marker>Mckinley
A
15

Add [fitBounds]="true" to <agm-map> Add [agmFitBounds]="true" to <agm-marker>

Remove [usePanning]="true" from <agm-map>

For more usability Add clustering: install this module and follow the instructions

Avron answered 1/2, 2019 at 10:27 Comment(3)
Why do you have to remove Pannig? What if i want to use them together?Blanka
It automatically pans the map like a charm. There's no need to add it explicitly.Avron
Is it possible to fit all not markers but polygons to view?Lamellirostral

© 2022 - 2024 — McMap. All rights reserved.