我正在尝试在单个页面应用程序的两个不同页面中以角度插入两个谷歌地图。当我打开第一页时,我正确地看到了地图,当我转到第二页时,地图不可见。相反,如果我刷新网站并首先打开第二页,我会正确地看到地图,如果我然后转到第一页,我就看不到地图。就好像它只初始化了显示的第一张地图,而第二张地图没有。
你知道我怎样才能在两个不同的页面上看到两个不同的地图吗?
这是代码,在 index.html 中,我将 google 脚本放在主体的底部
<script src="https://maps.googleapis.com/maps/api/js?key=[KEY]=weekly" defer >
第一个组件 ts:
export class ExploreComponent implements OnInit, AfterViewInit {
ngAfterViewInit(): void {
this.initMap();
}
map?: google.maps.Map;
infoWindow?: google.maps.InfoWindow;
initMap() {
const myLatLng = { lat: 45.902780, lng: 16.496370 };
this.map = new google.maps.Map(
document.getElementById("map") as HTMLElement,
{
zoom: 6,
center: myLatLng,
// disableDefaultUI:true,
streetViewControl: false,
fullscreenControl: false
}
);
const locationButton = document.createElement("button");
locationButton.textContent = "Pan to Current Location";
locationButton.classList.add("custom-map-control-button");
this.map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(locationButton);
locationButton.addEventListener("click", () => {
this.getActualPosition();
});
this.getActualPosition();
};
}
第一个组件的html:
<div id="map" style="width: 100%; height: 95%;"></div>
第二个组件 ts 的结构几乎相同:
ngAfterViewInit(): void {
this.initMap();
}
map?: google.maps.Map;
initMap() {
const myLatLng = { lat: 41.902780, lng: 12.496370 };
this.map = new google.maps.Map(
document.getElementById("map") as HTMLElement,
{
zoom: 6,
center: myLatLng,
}
);
}
第二个组件的html:
<div id="map" style="width: 100%; height: 250px; margin: auto; border-radius: 5px;margin-top: 5px;"\>\</div>