【发布时间】:2019-05-25 07:41:22
【问题描述】:
要设置地图缩放级别以包含所有位置标记,我尝试了this post 中建议的两个选项。
这就是我所做的:
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 数组在两个实例中都是空的。我该如何解决这个问题?
【问题讨论】:
-
我刚刚想通了,这要容易得多。您不必手动执行此操作,只需将 [fitBounds]="true" 添加到
并将 [agmFitBounds]="true" 添加到
标签: google-maps angular-google-maps