gpt4 book ai didi

angular - 谷歌地图监听器无法在 angular2+typescript 中正常工作

转载 作者:太空狗 更新时间:2023-10-29 18:26:51 30 4
gpt4 key购买 nike

我用 html+js+jquery 写了一个小网站,用的是 Google maps api v3。在 map 上,您可以绘制多段线,这是可能的,因为 map 上有事件处理程序,例如

 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");

});
...
}

不会工作。我不明白为什么可以将事件监听器添加到 map 而不是该 map 上的标记。是因为在另一个元素的事件处理中添加了新的监听器吗?但如果是这样,为什么它在纯 Javascript 中工作?

最佳答案

你搞砸了:

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

关于angular - 谷歌地图监听器无法在 angular2+typescript 中正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37183848/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com