我遇到了这个问题:我想将Google Maps Javascript API集成到一个Angular 5应用程序中。我不想使用Angular的Google Maps API组件,因为我想将这方面的知识扩展到其他Javascript API。
在组件中,我编写了以下代码。在addListener中,我调用了updateLocation方法,它可以工作(我放置了一个console.log()来检查它是否被调用),但是UI并没有刷新。
import { Component, OnInit, NgZone } from '@angular/core';
import {HostListener} from '@angular/core';
declare const google: any;
@Component({
selector: 'app-calculator',
templateUrl: './calculator.component.html',
styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {
private punto:number;
private puntoA;
private puntoB;
public sPuntoA: string;
public sPuntoB: string;
private map;
constructor(private zone: NgZone) {}
ngOnInit() {
let puntoA;
let puntoB;
this.sPuntoA="Click para definir"
this.sPuntoB="Click para definir"
let mapProp = {
center: new google.maps.LatLng(-35.040790898800104, -64.70068372786045),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
this.map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
this.puntoA = new google.maps.Marker();
this.puntoA.setMap(this.map);
this.puntoA.setLabel("A");
this.puntoB = new google.maps.Marker();
this.puntoB.setMap(this.map);
this.puntoB.setLabel("B");
google.maps.event.addListener(this.map, 'click',
(e) => this.updateLocation(e)
);
}
ngAfterViewInit() {
}
private updateLocation(event) {
console.log(event);
if(this.punto==1){
this.sPuntoA = event.lat;
this.sPuntoA = "puntooaaa";
this.puntoA.setPosition(event.latLng);
}
if(this.punto==2){ /**/
this.sPuntoB = event.lat;
this.puntoB.setPosition(event.latLng);
}
}
/* Called from the web interface. */
setMarker(punto: number){
this.punto = punto;
console.log(this.punto);
this.sPuntoB = "123";
}
}发布于 2017-12-25 13:48:37
Ui未刷新,因为只有您的变量更新未映射。因此,您需要执行以下步骤。
您需要先设置map null。所以你的代码应该是这样的
private updateLocation(event) {
this.map.setMap(null);
if(this.punto==1){
this.puntoA.setLabel("puntooaaa");
this.puntoA.setPosition(event.latLng);
this.puntoA.setMap(this.map);
}
if(this.punto==2){ /**/
this.sPuntoB = event.lat;
this.puntoB.setPosition(event.latLng);
this.puntoB.setMap(this.map);
}
}发布于 2017-12-25 23:20:52
最后我找到了一个解决方案,我读到了关于ngZone的文章,我理解它就像是执行的“区域”/作用域/上下文的管理者。
我只是在回调方法的代码中添加了zone.run()。
之前:
private updateLocation(event) {
console.log(event);
if(this.punto==1){
this.sPuntoA = event.lat;
this.sPuntoA = "puntooaaa";
this.puntoA.setPosition(event.latLng);
}
if(this.punto==2){ /**/
this.sPuntoB = event.lat;
this.puntoB.setPosition(event.latLng);
}
}之后:
private updateLocation(event) {
this.zone.run(() => {
if(this.punto==1){
this.sPuntoA = event.lat;
this.sPuntoA = "puntooaaa";
this.puntoA.setPosition(event.latLng);
}
if(this.punto==2){ /**/
this.sPuntoB = event.lat;
this.puntoB.setPosition(event.latLng);
}
})
}https://stackoverflow.com/questions/47964484
复制相似问题