所以我有一个angular 2应用程序,它应该有一个地图,一个侧边栏和一个导航栏。地图应该占据侧边栏和导航栏下面的所有窗口。角度结构如下:
id="google-map
的地图div和突出显示部分div,只要组件中的this.highlightsSection
标志设置为false,就会将其隐藏
这是应该实现这一点的代码:
import { Component, OnInit } from '@angular/core';
import { Sensor } from '../entities/sensor';
declare const google: any;
@Component({
selector: 'app-main-window',
templateUrl: './main-window.component.html',
styleUrls: ['./main-window.component.css']
})
export class MainWindowComponent implements OnInit {
highlightsSection: boolean = false;
zoom: number = 14;
lat: number = 26.67946;
lng: number = -80.41719;
map: any;
marker: any;
mapProp: any = {
center: new google.maps.LatLng(this.lat, this.lng),
zoom: this.zoom,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
constructor() { }
ngOnInit() {
this.map =new google.maps.Map(document.getElementById("google-map"), this.mapProp);
}
toggleHighlights(): void {
if(!this.highlightsSection) {
this.highlightsSection = true;
} else {
this.highlightsSection = false;
}
}
registerMarkers(): void {
this.marker = new google.maps.Marker({
position: {lat: this.lat, lng: this.lng},
title: "Hello world!"
});
this.marker.setMap(this.map);
this.marker.addListener('click', function() {
// What should go here to allow the marker to change the flag value of highlightsSection variable??
});
}
}
你可以看到这两个处理程序函数:this.toggleHighlights()
和this.registerMarkers()
,我需要按如下方式使用它们:我需要在侧边栏中有一个按钮来触发this.registerMarkers()
one来显示标记(直到它工作得很好),并且在这个this.registerMarkers()
中,在显示标记后,我需要在标记上添加事件侦听器,单击以触发另一个toggleHighlights()
函数,该函数依次显示地图右侧的突出显示部分。
问题是marker.addEventListener()
似乎不能在点击时触发this.toggleHighlights()
,我不明白为什么
我对angular2和typescript都是新手,以前我做过类似的事情的唯一方法是使用jquery和DOM,但是我需要组件的概念来存储多个标志和变量,但我不能做到这一点
PS:我已经尝试过sebastian的第三方组件,它的功能非常有限,所以我不能依赖它
如果有人能帮我弄清楚这里发生了什么,我会很高兴的
发布于 2017-12-04 12:13:52
您可以尝试使用闭包,如下所示:
registerMarkers(): void {
var toggler = () => {
// toggle the flag here
}
this.marker = new google.maps.Marker({
position: {lat: this.lat, lng: this.lng},
title: "Hello world!"
});
this.marker.setMap(this.map);
this.marker.addListener('click', function() {
toggler();
});
}
就我个人而言,我不是很喜欢/推荐这个解决方案,但我认为,这个变通办法是可行的(直到你找到其他解决方案为止)。当我使用相同的解决方案时,我也遇到了类似的情况,因为我没有找到任何其他解决方案。
另外,请注意,我在发布之前并没有运行这段代码,只是为了给你一个提示。
所以,在投反对票之前,请先试试...:)并点击答案,如果这对你有效...:)
https://stackoverflow.com/questions/47612886
复制相似问题