为了将地图缩放级别设置为包括所有位置标记,我尝试了两个选项,如此帖子中建议的。
这是我的做法:
请注意,this.mapMarkers是一个包含地图标记坐标的数组。这些坐标在ngOnInit()中被填充。
如上帖子的评论中提到的,我也尝试了以下方法:
这是我的做法:
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);
});
}
}
请注意,this.mapMarkers是一个包含地图标记坐标的数组。这些坐标在ngOnInit()中被填充。
如上帖子的评论中提到的,我也尝试了以下方法:
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);
}
在 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>
但在这两种情况下,我无法按照预期将地图缩小。原因是,当我调试代码时,mapMarkers数组在这两种情况下都为空。我该如何解决这个问题?