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?

Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79
devC
  • 1,384
  • 5
  • 32
  • 56
  • 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 and [agmFitBounds]="true" to the – devC Dec 27 '18 at 10:22

1 Answers1

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

BackSlash
  • 21,927
  • 22
  • 96
  • 136