首页 > 解决方案 > AGM 地图:设置缩放级别以包括所有标记

问题描述

要将地图缩放级别设置为包括所有位置标记,我尝试了本文中建议的两个选项。

这是我所做的:

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 数组在两个实例中都是空的。我该如何解决?

标签: google-mapsangular-google-maps

解决方案


添加[fitBounds]="true"<agm-map> 添加[agmFitBounds]="true"<agm-marker>

[usePanning]="true"从中删除<agm-map>

为了提高可用性添加集群: 安装此模块并按照说明进行操作


推荐阅读