【发布时间】:2020-04-20 07:46:21
【问题描述】:
我正在尝试在动态脚本中更改地图的中心。问题是我确实得到了我订阅的数据,但它不会改变地图的中心。我通过在组件内创建一个 setInterval() 并在我在组件外执行该方法后查看数据是否更改来对此进行了测试。下面是代码示例
https://codesandbox.io/s/joey-basic-gmaps-lw5d4
export class AppComponent implements OnInit, OnChanges {
public markerLat = 39;
public markerLng = -76;
title = "CodeSandbox";
private apiKey = environment.googleMapsAPIkey;
constructor(private data: DataService) {
const dynamicScripts = [
"https://maps.googleapis.com/maps/api/js?key=" + this.apiKey
];
for (var i = 0; i < dynamicScripts.length; i++) {
const node = document.createElement("script");
node.src = dynamicScripts[i];
node.type = "text/javascript";
node.async = true;
node.charset = "utf-8";
document.getElementsByTagName("head")[0].appendChild(node);
}
}
ngOnInit() {
this.data.markerLat.subscribe(markerLat => this.markerLat = markerLat);
this.data.markerLng.subscribe(markerLng => this.markerLng = markerLng);
setTimeout(() => {
this.initMap();
}, 1000);
}
ngOnChanges() {
setTimeout(() => {
this.initMap();
}, 1000);
}
ngOnDestroy() {
this.data.markerLat.subscribe(markerLat => this.markerLat = markerLat).unsubscribe();
this.data.markerLng.subscribe(markerLng => this.markerLng = markerLng).unsubscribe();
}
initMap() {
const google = window.google;
const center = { lat: this.markerLat, lng: this.markerLng };
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: center
});
const marker = new google.maps.Marker({ position: center, map: map });
}
}
【问题讨论】:
-
@Chellappanவ 市场是可见的......它只是不会改变位置
-
将 initMap 方法移到 subscribe 方法中
-
@Chellappanவ 我不知道你的意思……你能告诉我吗
标签: javascript angular google-maps observable