Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AGM Map: set the zoom level to include all markers

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?

like image 496
devC Avatar asked Dec 17 '22 19:12

devC


1 Answers

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

like image 136
Lalaji Sananjaya Avatar answered Dec 20 '22 07:12

Lalaji Sananjaya