因此,我有一个Angle 2应用程序,该应用程序应该具有地图,侧边栏和导航栏。该地图应该占据了侧边栏和导航栏下方的所有窗口。角结构如下:


一个主窗口组件,其中包含导航栏,边栏,地图和div的模板,当我单击地图上的标记时,这些模板应弹出并占据屏幕的右侧。我将每个部分的所有组件都放在一个组件中,以方便地访问其他部分中的变量。当我点击标记时要在右侧弹出的div不是maps API中存在的弹出窗口;我将其硬编码到组件的模板中,这是一个div,我将其隐藏或根据组件中的标记进行显示(我必须明确说明)。
一个main-window.html模板,该模板包含导航栏div,侧边栏div,带有id="google-map的地图div和带有ng的Highlights-section div如果将其隐藏,只要组件中的this.highlightsSection标志设置为假



这是应该实现的代码:

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()一个按钮以显示标记(直到这点工作正常),并在显示标记后在此this.registerMarkers()里面我需要添加事件单击标记的侦听器以触发其他toggleHighlights()功能,该功能又会在地图右侧显示突出显示div的此权限部分。


问题是marker.addEventListener()似乎无法在点击时触发this.toggleHighlights(),我不明白为什么

我对angular2和Typescript都是陌生的,之前做过类似的事情的唯一方法是使用jquery和DOM,但是我需要具有组件的概念来存储多个标志和变量,而我无法实现这一点

PS:我已经通过sebastian尝试了agm第三方组件,它的功能非常有限,所以我不能依靠它

如果有人帮助我弄清楚这里发生了什么我会很高兴

最佳答案

您可能可以尝试使用闭包;如下所示:

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();
   });
}


就个人而言,我不太喜欢/不推荐这种解决方案,但是我认为,这种解决方法是可行的(最后,直到找到其他解决方案为止)。当我使用相同的方法时,我也遇到过类似的情况,因为我没有找到其他解决方案。

另外,请注意,我在发布之前尚未运行此代码,只是给您提示。

所以,如果这对您有用,请在投票之前尝试::)并点击答案。

10-05 20:38
查看更多