我创建了一个类来扩展 openlayers 中的 Interaction。此类允许选择矢量切片功能。
/**
* Vector Tile selector class.
*/
export class VectorTileSelect extends Interaction {
constructor() {
super({
handleEvent: (evt: MapBrowserEvent<UIEvent>): boolean => {
return this.selectFeaturesAtPixel(evt);
},
});
}
/**
* Select vector features at a given pixel and fires
* a vector tile select event on selection (select:vectortile)
* @param e - Map browser event
* @returns true when the selection is made
*/
private selectFeaturesAtPixel(e: MapBrowserEvent<UIEvent>): boolean {
if (e.type === 'click') {
const features = this.getMap()?.getFeaturesAtPixel(e.pixel, {
layerFilter: (layer) => layer instanceof VectorTileLayer,
});
this.dispatchEvent(new VectorTileSelectEvent(features, e));
}
return true;
}
}
做出选择后,将触发以下自定义事件:
/**
* Vector tile selection event
*/
export class VectorTileSelectEvent extends Event {
private selected: FeatureLike[] | undefined;
private mapBrowserEvent: MapBrowserEvent<UIEvent>;
constructor(
selected: FeatureLike[] | undefined,
mapBrowserEvent: MapBrowserEvent<UIEvent>
) {
super('select:vectortile');
this.selected = selected;
this.mapBrowserEvent = mapBrowserEvent;
}
}
但是当我尝试像这样听这个事件时:
const yolo = new VectorTileSelect();
map.addInteraction(yolo);
yolo.on('select:vectortile', (e) => {
console.log(e);
});
TS 向我抛出以下错误:
No overload matches this call.
Overload 1 of 3, '(type: EventTypes, listener: (event: BaseEvent) => unknown): EventsKey', gave the following error.
Overload 2 of 3, '(type: "propertychange" | "change:active", listener: (event: ObjectEvent) => unknown): EventsKey', gave the following error.
Overload 3 of 3, '(type: (EventTypes | "propertychange" | "change:active")[], listener: (event: BaseEvent | Event) => unknown): EventsKey[]', gave the following error.ts(2769).
我该如何解决这个问题?
您似乎正在尝试创建自定义事件,如果您检查this文档,您会发现您的自定义事件未定义。我提到的这个 URL 还提供了类似于 w3c 标准页面的解释 2 类事件接口以及更多相关信息。
为了通过扩展具有所有类型声明的“eventType”接口来创建您自己的事件
declare module 'ol/events' {
interface EventTypes {
'select:vectortile': VectorTileSelectEvent;
}
}
然后像这样使用它
const yolo = new VectorTileSelect();
map.addInteraction(yolo);
yolo.on('select:vectortile', (e: VectorTileSelectEvent) => {
console.log(e.selected);
// Access the selected features
});