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?