AGM地图:将缩放级别设置为包含所有标记

5
为了将地图缩放级别设置为包括所有位置标记,我尝试了两个选项,如此帖子中建议的。
这是我的做法:
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数组在这两种情况下都为空。我该如何解决这个问题?


我刚刚发现,这要简单得多。你不必手动操作,只需在<agm-map>中添加[fitBounds] =“true”,并在<agm-marker>中添加[agmFitBounds] =“true”即可。 - devC
1个回答

15

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

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

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

为了更好的可用性,添加聚类: 安装此模块并按照说明操作


为什么你必须移除Pannig?如果我想要同时使用它们怎么办? - Tanuki
1
它可以自动平移地图,非常流畅。不需要显式添加。 - Lalaji Sananjaya
能否将所有的多边形适配到视图中,而不是标记? - DuFuS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接