点只能在线上移动
const pointInLine = (pointFeature, lineFeature) => {
const pointGeom = pointFeature.getGeometry();
const pointCoordinates = pointGeom.getCoordinates();
const lineGeom = lineFeature.getGeometry();
const closestPoint = lineGeom.getClosestPoint(pointCoordinates);
pointGeom.setCoordinates(closestPoint);
};
图形只能在面内移动
let lastCoordinates = [];
const graphInPolygon = (graphFeature, polygonFeature2, options = undefined) => {
const graphGeom = graphFeature.getGeometry();
const polygonGeom2 = polygonFeature2.getGeometry();
let coordinates = [];
if (graphGeom instanceof Circle) {
const center = graphGeom.getCenter();
const r = graphGeom.getRadius();
coordinates = [
[center[0] - r, center[1] + r],
[center[0] - r, center[1] - r],
[center[0] + r, center[1] - r],
[center[0] + r, center[1] + r],
[center[0] - r, center[1] + r],
];
const cross = coordinates.find((item) => {
return !polygonGeom2.intersectsCoordinate(item);
});
if (cross) {
graphGeom.setCenterAndRadius(lastCoordinates[0], lastCoordinates[1]);
} else {
lastCoordinates = [center, r];
}
} else if (graphGeom instanceof Polygon) {
coordinates = graphGeom.getCoordinates()[0];
const cross = coordinates.find((item) => {
return !polygonGeom2.intersectsCoordinate(item);
});
if (cross) {
graphGeom.setCoordinates([lastCoordinates]);
} else {
lastCoordinates = coordinates;
}
} else if (graphGeom instanceof LineString) {
coordinates = graphGeom.getCoordinates();
if (options) {
const {appintSideCoord} = options;
const dx = coordinates[1][0] - coordinates[0][0];
const dy = coordinates[1][1] - coordinates[0][1];
const appintSideGeom = new LineString(appintSideCoord);
let cross = [];
let shortLength;
coordinates.forEach((item) => {
const closestPoint = appintSideGeom.getClosestPoint(item);
const length = Math.sqrt(
Math.pow(item[0] - closestPoint[0], 2) +
(item[1] - closestPoint[1], 2)
);
if (!shortLength) {
shortLength = length;
cross = closestPoint;
} else if (length < shortLength) {
cross = closestPoint;
}
});
const newCoordinates = [cross, [cross[0] + dx, cross[1] + dy]];
graphGeom.setCoordinates(newCoordinates);
} else {
const cross = coordinates.find((item) => {
return !polygonGeom2.intersectsCoordinate(item);
});
if (cross) {
graphGeom.setCoordinates(lastCoordinates);
} else {
lastCoordinates = coordinates;
}
}
}
};