我想在地图上拖放标记并显示位置。
当我使用此代码拖放功能时:
var modify = new Modify({ source: this.vectorSource });
his.map.addInteraction(modify);
发生此错误:
类型错误:t.getType 不是一个函数
如果需要在地图上移动要素,则需要使用交互,而不是修改。在开放层中没有移动交互,您需要创建一个。这是我的拖动交互
import PointerInteraction from 'ol/interaction/Pointer';
import { MapBrowserEvent, Feature } from 'ol';
import Event from 'ol/events/Event';
type DragEventType = 'moveend';
export class DragInteractionEvent extends Event {
feature: Feature;
mapBrowserEvent: MapBrowserEvent;
constructor(type: DragEventType, feature: Feature, mapBrowserEvent: MapBrowserEvent) {
super(type);
this.feature = feature;
this.mapBrowserEvent = mapBrowserEvent;
}
}
// tslint:disable: only-arrow-functions
// tslint:disable: space-before-function-paren
export class DragInteraction extends PointerInteraction {
constructor(theFeature: Feature) {
super({
handleDownEvent(evt: MapBrowserEvent): boolean {
const map = evt.map;
const feature = map.forEachFeatureAtPixel(evt.pixel, function (f) {
return f;
});
if (feature && theFeature === feature) {
this.coordinate_ = evt.coordinate;
this.feature_ = feature;
return true;
}
return false
},
handleDragEvent(evt: MapBrowserEvent) {
const deltaX = evt.coordinate[0] - this.coordinate_[0];
const deltaY = evt.coordinate[1] - this.coordinate_[1];
const geometry = this.feature_.getGeometry();
geometry.translate(deltaX, deltaY);
this.coordinate_[0] = evt.coordinate[0];
this.coordinate_[1] = evt.coordinate[1];
},
handleMoveEvent(evt: MapBrowserEvent) {
if (!this.cursor_) {
return;
}
const map = evt.map;
const feature = map.forEachFeatureAtPixel(evt.pixel, function (f) {
return f;
});
const element = evt.map.getTargetElement();
if (feature) {
if (element.style.cursor !== this.cursor_) {
this.previousCursor_ = element.style.cursor;
element.style.cursor = this.cursor_;
}
} else if (this.previousCursor_ !== undefined) {
element.style.cursor = this.previousCursor_;
this.previousCursor_ = undefined;
}
},
handleUpEvent(evt: MapBrowserEvent): boolean {
this.dispatchEvent(new DragInteractionEvent('moveend', theFeature, evt))
this.coordinate_ = null;
this.feature_ = null;
return false;
},
})
}
}
你可以这样使用
this.dragInteraction = new DragInteraction(feature);
this.dragInteraction.on('moveend', (evt: DragInteractionEvent) => {
console.log('evt', evt);
})