Google Maps监听器在Angular2+TypeScript中无法正常工作

3

我用html+js+jquery编写了一个小型网站,并使用了Google地图api v3。在地图上,你可以绘制折线,这是由于地图上的事件处理程序实现的,例如:

 map.addListener('click', addLatLng);

并且。
function addLatLng(event) {
    // Add a new marker at the new plotted point on the polyline.
    polyline.getPath().push(event.latLng);

    var marker = new google.maps.Marker({
        position: event.latLng,
        draggable: true,
        map: map,
        icon: {
          path: google.maps.SymbolPath.CIRCLE,
          scale: 5
        }
    })

    var i = gmarkers.length;
    marker.addListener('drag', function() {
      polyline.getPath().setAt(i, marker.getPosition());
    });
 ...
}

现在我想将这个页面翻译成Angular2组件。我知道事件处理可能不应该以这种方式进行,但我不知道其他方法... 我可以将第一行更改为:
this.map.addListener('click', (event) => this.addLatLng(event));

这个应该可以按照预期工作。但是!

addLatLng(event) {
    // Add a new marker at the new plotted point on the polyline.
    this.polyline.getPath().push(event.latLng);

    var marker = new google.maps.Marker({
        position: event.latLng,
        draggable: true,
        map: this.map,
        icon: {
          path: google.maps.SymbolPath.CIRCLE,
          scale: 5
        }
    })


    var i = this.gmarkers.length;

    marker.addListener('drag', () => function() {
     // this.polyline.getPath().setAt(i, marker.getPosition());
      console.log("drag listening");

    });
  ...
}

无法工作。我不明白为什么事件监听器可以添加到地图上,但不能添加到该地图上的标记。是因为新的监听器在另一个元素的事件处理中被添加了吗?但如果是这样,为什么在纯JavaScript中可以正常工作呢?


你是收到了错误消息还是事件处理程序没有被调用? - Günter Zöchbauer
它只是没有被称为。 - Stubbi
1个回答

3
你把这个搞砸了:
marker.addListener('click', () => function() {
    // this.polyline.getPath().setAt(i, marker.getPosition());
    console.log("drag listening");
});

应该是这样的:
marker.addListener('drag', () => {
    // this.polyline.getPath().setAt(i, marker.getPosition());
    console.log("drag listening");
});

这个结构
() => {}

这是一个箭头函数。如果没有{},它将返回=>后面的值。

因此,您创建了一个返回函数的函数。

更多信息请参见:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html


啊,那就是诀窍!非常感谢!顺便说一下,它不是点击,而是拖动,当然也在那里。问题中错了。 - Stubbi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接