目标
我们想设置 AGM 地图的缩放级别以显示地图上的所有标记。通常在 Google Maps JavaScript API 中,您使用 google.maps.Map 类的 fitBounds() 方法来实现此目的。
https://developers.google.com/maps/documentation/javascript/reference/3/map
因此,我们必须获取地图对象的实例(JavaScript API 实例)并在其上应用fitBounds()。
解决方案
我创建了一个简单的示例,它有一个模拟服务,它为 5 个标记提供 JSON 数据,并使用 AGM 地图绘制地图和标记。在这个例子中,我使用 @ViewChild 装饰器来获取 AGM 地图的实例并监听 mapReady 事件以获取地图对象的实例(来自 JavaScript API)。获得地图实例后,我可以轻松创建 LatLngBounds 对象并在地图对象上调用 fitBounds()。看看 app.component.ts 中的ngAfterViewInit() 方法,了解一下。
代码 sn-p
app.component.ts
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { MyMarker } from './marker';
import { MarkersService } from './markers.service';
import { GoogleMapsAPIWrapper, AgmMap, LatLngBounds, LatLngBoundsLiteral} from '@agm/core';
declare var google: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, AfterViewInit {
title = 'AGM project (so48865595)';
lat = 41.399115;
lng = 2.160962;
markers: MyMarker[];
@ViewChild('AgmMap') agmMap: AgmMap;
constructor(private markersService: MarkersService) { }
ngOnInit() {
this.getMarkers();
}
ngAfterViewInit() {
console.log(this.agmMap);
this.agmMap.mapReady.subscribe(map => {
const bounds: LatLngBounds = new google.maps.LatLngBounds();
for (const mm of this.markers) {
bounds.extend(new google.maps.LatLng(mm.lat, mm.lng));
}
map.fitBounds(bounds);
});
}
getMarkers(): void {
this.markers = this.markersService.getMarkers();
}
mapIdle() {
console.log('idle');
}
}
app.component.html
<h1>{{ title }}</h1>
<!-- this creates a google map on the page with the given lat/lng from -->
<!-- the component as the initial center of the map: -->
<agm-map #AgmMap [latitude]="lat" [longitude]="lng" (idle)="mapIdle()">
<agm-marker *ngFor="let p of markers" [latitude]="p.lat" [longitude]="p.lng"></agm-marker>
</agm-map>
结论
如果您想查看完整示例,请下载示例项目:
https://github.com/xomena-so/so48865595
我希望这会有所帮助!