add points to polygons

This commit is contained in:
Jake Kasper
2025-08-21 19:38:23 -04:00
parent 018a33d28f
commit e75db9978c

View File

@@ -46,6 +46,41 @@ const calculateAreaInSqFt = (coordinates) => {
}
};
// Calculate distance from a point to a line segment
const pointToLineDistance = (point, lineStart, lineEnd) => {
const [px, py] = point;
const [x1, y1] = lineStart;
const [x2, y2] = lineEnd;
const A = px - x1;
const B = py - y1;
const C = x2 - x1;
const D = y2 - y1;
const dot = A * C + B * D;
const lenSq = C * C + D * D;
if (lenSq === 0) return Math.sqrt(A * A + B * B);
let param = dot / lenSq;
let xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
} else if (param > 1) {
xx = x2;
yy = y2;
} else {
xx = x1 + param * C;
yy = y1 + param * D;
}
const dx = px - xx;
const dy = py - yy;
return Math.sqrt(dx * dx + dy * dy);
};
// Component for drawing polygons
function PolygonDrawer({ isDrawing, onPolygonComplete, currentColor }) {
const [currentPolygon, setCurrentPolygon] = useState([]);
@@ -139,10 +174,39 @@ function EditablePolygon({ section, onUpdate, onEdit, onDelete }) {
weight: isEditing ? 3 : 2
}}
eventHandlers={{
click: () => {
click: (e) => {
if (!isEditing) {
setIsEditing(true);
toast('Edit mode enabled: Drag points to move, right-click to remove points');
toast('Edit mode enabled: Drag points to move, right-click to remove points, click edges to add points');
} else {
// Add point when clicking on polygon edge during edit mode
const newPoint = [e.latlng.lat, e.latlng.lng];
// Find the closest edge and insert the point there
let closestEdgeIndex = 0;
let minDistance = Infinity;
for (let i = 0; i < editedCoordinates.length; i++) {
const start = editedCoordinates[i];
const end = editedCoordinates[(i + 1) % editedCoordinates.length];
// Calculate distance from clicked point to edge
const distance = pointToLineDistance(newPoint, start, end);
if (distance < minDistance) {
minDistance = distance;
closestEdgeIndex = i;
}
}
// Insert new point after the closest edge start point
const newCoords = [...editedCoordinates];
newCoords.splice(closestEdgeIndex + 1, 0, newPoint);
setEditedCoordinates(newCoords);
const area = calculateAreaInSqFt([...newCoords, newCoords[0]]);
onUpdate(section.id, { ...section, coordinates: newCoords, area });
toast('Point added! Drag it to adjust position');
}
}
}}
@@ -158,6 +222,7 @@ function EditablePolygon({ section, onUpdate, onEdit, onDelete }) {
toast(isEditing ? 'Edit mode disabled' : 'Edit mode enabled');
}}
className={`text-sm ${isEditing ? 'text-green-600' : 'text-blue-600'}`}
title={isEditing ? 'Exit edit mode' : 'Drag corners, click edges to add points, right-click to remove'}
>
{isEditing ? 'Done' : 'Edit Points'}
</button>