我用html + js + jquery编写了一个小型网站,并使用了Google Maps 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中运行?
您搞砸了:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句