预期的行为是,当您移动地图时(通过按住鼠标左键拖动鼠标),飞机几何形状应继续更改坐标位置。实际行为是,当地图移动时,飞机几何形状不会改变坐标位置。只有当您停止移动地图时,几何坐标位置才会更新为正确的坐标。
源代码:
import React, { useEffect, useRef } from "react";
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import Feature from "ol/Feature";
import TileLayer from "ol/layer/Tile";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { fromLonLat } from "ol/proj";
import OSM from "ol/source/OSM";
import { Point } from "ol/geom";
import {
Text as OLText,
Fill as OLFill,
Style,
Stroke,
Circle as OLCircle
} from "ol/style";
export default () => {
const mapRef = useRef();
const trafficLayer = useRef();
const aircraftPoint = useRef();
const coordinates = [
[22.3084, 113.9239],
[22.3084, 113.927],
[22.3084, 113.929]
];
const moveAirplane = (counter: number) => {
console.log("Moving airplane: ", counter);
const lonlat = fromLonLat([
coordinates[counter][1],
coordinates[counter][0]
]);
aircraftPoint.current.getGeometry().setCoordinates(lonlat);
};
const labelStyle = new Style({
text: new OLText({
font: "12px Calibri,sans-serif",
overflow: true,
fill: new OLFill({
color: "#000"
}),
stroke: new Stroke({
color: "#fff",
width: 3
}),
offsetY: -12
}),
fill: new OLFill({
color: "rgba(255, 255, 255, 0.2)"
}),
stroke: new Stroke({
color: "black",
width: 2,
lineDash: [4, 4]
}),
image: new OLCircle({
radius: 5,
fill: new OLFill({
color: "rgba(255,255,255,1)"
})
})
});
const style = [labelStyle];
useEffect(() => {
aircraftPoint.current = new Feature({
name: "Aircraft name",
geometry: new Point(fromLonLat([113.89076390019189, 22.324364815058356]))
});
trafficLayer.current = new VectorLayer({
source: new VectorSource({
features: [aircraftPoint.current]
}),
style: function (feature) {
labelStyle.getText().setText(feature.get("name"));
return style;
}
});
new Map({
target: mapRef.current,
layers: [
new TileLayer({
source: new OSM()
}),
trafficLayer.current
],
view: new View({
center: fromLonLat([113.91, 22.32]),
zoom: 14
})
});
});
useEffect(() => {
let counter = 0;
let intervalId = setInterval(() => {
if (counter + 1 > coordinates.length - 1) {
counter = 0;
} else {
counter = counter + 1;
}
moveAirplane(counter);
}, 1000);
return () => {
clearInterval(intervalId);
};
}, []);
return <div className="map" ref={mapRef} />;
};
谢谢!
解决方案是在 VectorLayer 选项中包含
updateWhileInteraction: true
。
感谢迈克提供答案。