I will read src/lib/geo.ts to check the existing geographic calculation functions so we can add new helpers for airplane bearing and flight clock time calculations.
I read src/lib/geo.ts and confirmed its structure. Now let's think about what we need to add to src/lib/geo.ts:
calculateBearing(lat1, lon1, lat2, lon2): Returns angle in degrees (0 = North, 90 = East, 180 = South, 270 = West) so our airplane icon can rotate and point directly at the destination city.
parseTimeMinutes(timeStr?: string): number | null: Parses time strings like "10:30", "14:45:00", or "2024-01-15 10:30" into total minutes from midnight (0 to 1439), or null if not present.
formatFlightClock(startMin: number | null, elapsedHours: number, totalHours: number): Returns a formatted string for the current flight time and arrival time, e.g. 10:37:15 (прилёт в 10:45).
formatDurationPrecise(hours: number): Formats duration down to seconds (e.g. 7 мин 30 сек or 1 ч 15 мин 10 сек), which is much better for a live moving flight simulation than just rounded minutes!
Let's edit src/lib/geo.ts to add these helper functions. I will first explain what I am about to do, call edit_file, and confirm the result.
Wait, let's make sure our explanation is clear and we follow:
"For each file you create or edit, you must first explain what you are about to do, then call the tool, then confirm the result."
And "After using a tool, provide only a brief summary of what you did - DO NOT output the actual code content in your response text."
Let's do this now for src/lib/geo.ts.
Wait! Since we want to add several functions at the end of src/lib/geo.ts, let's check lines 28-32 and replace them with the new functions included.I am going to edit src/lib/geo.ts to add geographic bearing calculation (to rotate the airplane icon towards the destination), precise duration formatting with seconds, and flight clock time calculation based on departure time and flight speed.
I added the geographic bearing calculation, precise duration formatting, and flight clock time calculation to src/lib/geo.ts.
Let's think about the flight animation simulation.
When a route from a fix point to Almetyevsk or Nizhnekamsk is active (p.activeRoutes[ep.id] === true):
Let's see: how should the animation progress and be controlled?
If we have an airplane marker for every active flight:
Let's make sure:
- An airplane automatically takes off and flies along the route!
- By default, it flies at a visually engaging speed (e.g. 180x speed, so a 1 hour flight takes 20 seconds, or 360x speed so 1 hour takes 10 seconds).
- When it reaches the destination (100%), it pauses for 2 seconds and then loops (restarts from 0%), so whenever the user looks at the map or toggles a route, they see the airplane flying towards the city!
- To give the user maximum control and visibility over the planes, let's add a Flight Simulation State and Control Center:
- In
App.tsx, let's add global simulation settings: simSpeed (multiplier: e.g. 60, 180, 360, 720, 3600), simPaused (boolean), and simResetTrigger (counter to reset planes to start).
- We pass these simulation settings to
MapView and Sidebar.
- In
MapView, we run a requestAnimationFrame loop that updates the position of all active airplanes smoothly!
- On the map, each flying airplane gets a rotated jet icon with a glowing trail or badge!
- Hovering or clicking on the airplane shows a detailed telemetry popup/tooltip:
- ✈️ Самолёт в полёте: [Точка фиксации] → [Город]
- 📍 Место (координаты): 54.1234, 52.5678
- 🚀 Скорость движения: 600 км/ч
- 📏 Дистанция: Пройдено 45.2 км из 90.4 км (50%)
- ⏱️ Время в пути: 4 мин 30 сек / Осталось: 4 мин 30 сек
- ⏰ Время по часам: 10:34 (Прилёт в 10:39) — рассчитано из времени фиксации и скорости!
- And in the header or floating widget on the map (or sidebar), let's show "✈️ Авиа-симулятор":
- Кнопка:
[⏸ Пауза всем] / [▶️ Лететь всем]
- Кнопка:
[🔄 Перезапуск (с начала)]
- Скорость анимации:
[x60] [x180] [x360] [x720] [x3600]
- Индикатор: Сколько самолётов сейчас в воздухе!
Let's check src/types.ts to see if we need any new interfaces for the simulation or if existing ones are fine.
Let's read src/types.ts to make sure we don't break anything. We read it earlier, let's check: it has FixPoint, Endpoint, Zone, SimpleRoute, RouteFile, PlaceResult. That's completely sufficient!
Let's check src/index.css. We need to add styling for the rotated airplane marker and telemetry tooltip so it looks stunning!
Let's see what CSS classes we might need:
.plane-marker: Container for the airplane SVG with drop-shadow and smooth rotation.
.plane-telemetry: Styling for the live telemetry card inside the tooltip/popup.
- Let's check
src/index.css before editing it. I will read src/index.css first.
Wait, let's explain and call read_file on src/index.css.I will read src/index.css to inspect the existing marker and tooltip styles before adding styles for the flying airplane marker and flight telemetry display.
Let's read the rest of src/index.css (lines 101-118). I will explain and call read_file.I will read the remaining lines of src/index.css to check the end of the file before adding our airplane animation styles.
Let's edit src/index.css to add the airplane marker and telemetry styles.
Let's see what CSS we need:
.plane-icon-wrap: Container for the rotated airplane SVG with a pulsing glow and smooth rotation transition if needed.
.plane-telemetry: Styling for the tooltip/popup showing flight progress, coordinates, clock time, speed.
- Let's make sure our explanation is clear and we follow:
"For each file you create or edit, you must first explain what you are about to do, then call the tool, then confirm the result."
And "After using a tool, provide only a brief summary of what you did - DO NOT output the actual code content in your response text."
Let's edit src/index.css now.I am going to edit src/index.css to append CSS classes for the flying airplane marker (including drop shadow, pulse animation, and rotation container) and for the flight telemetry tooltip.
I edited src/index.css to add the airplane marker and telemetry tooltip styles.
Now let's examine how to implement the flight simulation state and animation in MapView.tsx and App.tsx.
Let's see: what simulation controls and state do we want?
In App.tsx, let's add:
simSpeed: number (e.g., 180 by default, where 1 hour of flight = 20 seconds of real time). Let's allow choosing 60 (1x fast), 180 (3x fast), 360 (6x fast), 720 (12x fast), 3600 (1 sec = 1 hour).
simPaused: boolean (default false).
simResetTrigger: number (incremented when clicking "Сбросить полёты" to restart all planes from 0%).
Wait, let's check: in MapView.tsx, how should we track the airplanes?
Let's analyze:
An active flight exists for every pair (p, ep) where p.activeRoutes[ep.id] === true.
Let's define a flight ID: flightId = {p.id}__{ep.id}``.
In MapView.tsx, let's maintain a ref:
const flightsStateRef = useRef<Map<string, { progress: number; pauseTimer: number }>>(new Map());
Wait! What is pauseTimer?
When a plane reaches progress >= 1 (arrived at destination!), we set progress = 1 and set pauseTimer = 2.0 (2 seconds pause).
While pauseTimer > 0, we decrement pauseTimer -= dt. When pauseTimer <= 0, we reset progress = 0 (plane takes off again from the fix point!). That way, any active route continuously demonstrates the airplane flying to the city, landing, pausing briefly, and taking off again! And if the user clicks "Сброс на старт" (Reset), we set progress = 0 and pauseTimer = 0 for all active flights!
Let's check how the animation loop works in MapView.tsx:
We can use a requestAnimationFrame loop in a useEffect!
In each frame:
- Calculate delta time
dt (seconds since last frame, capped at e.g. 0.1s to avoid huge jumps if browser tab was inactive).
- If
!simPaused:
For each active flight (p, ep):
- Get distance
dist = haversine(p.lat, p.lng, ep.lat, ep.lng) in km.
- Flight duration in hours
durHours = dist / (p.speed || 600).
- Flight duration in real seconds at
simSpeed: durSeconds = (durHours * 3600) / simSpeed.
- Update progress:
If
st.pauseTimer > 0:
st.pauseTimer -= dt; if (st.pauseTimer <= 0) st.progress = 0;
Else:
st.progress += dt / Math.max(0.1, durSeconds); if (st.progress >= 1) { st.progress = 1; st.pauseTimer = 2.0; }
Wait! When we update progress in requestAnimationFrame, we need to update the airplane marker positions and tooltips on the map!
Wait! If we recreate Leaflet markers in useEffect whenever points change, and then inside requestAnimationFrame we update the existing markers directly (using marker.setLatLng(), marker.setIcon(), and marker.setTooltipContent()), it will be 60 FPS smooth without causing React re-renders!
Let's check: how can we keep references to the airplane markers?
We can store them in a ref:
const planeMarkersRef = useRef<Map<string, L.Marker>>(new Map());
Let's see: in useEffect (when points, endpoints, selectedPointId, pendingConnectId change), we clear and recreate the static layers (points, handles, routes, labels).
For airplanes:
In that same useEffect (or a separate one for planes), we can check which flights are active (p.activeRoutes[ep.id] === true).
For each active flight flightId:
If planeMarkersRef.current.has(flightId) doesn't exist, we create a new L.Marker and add it to layersRef.current.planes!
If a flight in planeMarkersRef is no longer active, we remove it from the layer and map!
And then, in our requestAnimationFrame loop, for each active flight flightId:
We get st = flightsStateRef.current.get(flightId). If not present, initialize { progress: 0, pauseTimer: 0 }.
Calculate:
curLat = p.lat + (ep.lat - p.lat) * st.progress
curLng = p.lng + (ep.lng - p.lng) * st.progress
bearing = calculateBearing(p.lat, p.lng, ep.lat, ep.lng)
- Distance covered:
distCovered = dist * st.progress
- Distance remaining:
distRemaining = dist * (1 - st.progress)
- Elapsed flight hours:
elapsedHours = durHours * st.progress
- Remaining flight hours:
remHours = durHours * (1 - st.progress)
- Parse clock time:
startMin = parseTimeMinutes(p.fixTime)
- Format clock time:
clock = formatFlightClock(startMin, elapsedHours, durHours)
- Update marker position:
marker.setLatLng([curLat, curLng]).
- Create or update icon: we can generate the HTML for the plane SVG with
transform: rotate(${bearing}deg) and color ep.color. Wait! Since bearing and ep.color don't change while flying along a straight line, we only need to set the icon when creating the marker (or when color/bearing changes)!
- Update tooltip content: we set
marker.setTooltipContent(html) with the rich live telemetry!
Let's check: what should the live telemetry HTML look like?
Let's craft it:
<div class="plane-telemetry">
<div class="pt-title" style="color:${ep.color}">
<span>✈️</span>
<span>Рейс: ${p.name} → ${ep.name}</span>
</div>
<div class="pt-row"><span class="pt-label">📍 Место (коорд.):</span><span class="pt-value">${formatCoord(curLat)}, ${formatCoord(curLng)}</span></div>
<div class="pt-row"><span class="pt-label">🚀 Скорость:</span><span class="pt-value">${p.speed} км/ч</span></div>
<div class="pt-row"><span class="pt-label">📏 Пройдено:</span><span class="pt-value">${distCovered.toFixed(1)} км из ${dist.toFixed(1)} км (${Math.round(st.progress * 100)}%)</span></div>
<div class="pt-row"><span class="pt-label">⏱️ В пути / Ост.:</span><span class="pt-value">${formatDurationPrecise(elapsedHours)} / ${formatDurationPrecise(remHours)}</span></div>
${clock ? `<div class="pt-row"><span class="pt-label">⏰ Время по часам:</span><span class="pt-value" style="color:#16a34a">${clock.curTime} (прилёт ${clock.arrTime})</span></div>` : `<div class="pt-row"><span class="pt-label">⏰ Время вылета:</span><span class="pt-value" style="color:#94a3b8">не указано в точке</span></div>`}
<div class="pt-progress-bar">
<div class="pt-progress-fill" style="width:${Math.round(st.progress * 100)}%; background:${ep.color}"></div>
</div>
</div>
Wait! What if we also make the tooltip appear when hovering over the plane, AND let's bind it with direction: "top", offset: [0, -16]!
Wait! Let's also give the plane marker a click handler: when clicked, what if it toggles permanent: true/false on its tooltip, or pauses/resumes that specific flight?!
Wait, why not make clicking on the plane pause/resume that specific plane?!
If we store st.paused = !st.paused when clicked, and show in the tooltip: (Клик по самолёту — Пауза/Старт)! That is so intuitive and delightful!
Let's check: how can we add global flight controls in the UI?
Let's see: in App.tsx, we have the header. Let's look at what's in the header right now.
Let's check App.tsx around the header and where we pass props to MapView. I will read src/App.tsx first.
Wait, let's explain and call read_file on src/App.tsx.I will read src/App.tsx to check the header structure and the props passed to MapView and Sidebar before adding flight simulation controls.
Let's check lines 330 to 380 of src/App.tsx. I will explain and call read_file.I will read lines 330 to 380 of src/App.tsx to see where MapView is rendered and what props it receives.
Let's check lines 380 to 436 of src/App.tsx. I will explain and call read_file.I will read the remaining lines of src/App.tsx (380-436) to check the MapView rendering and the bottom hint.
Let's add the simulation controls and state in App.tsx:
We can add state:
const [simSpeed, setSimSpeed] = useState<number>(180); // 180x: 1 час полёта = 20 секунд
const [simPaused, setSimPaused] = useState<boolean>(false);
const [simResetTrigger, setSimResetTrigger] = useState<number>(0);
And in the header (or floating on the map), let's add a "✈️ Авиа-симулятор" widget! Wait! Where is the best place to show simulation controls?
If we put a floating control panel on the map at top-3 right-3 z-[1000] (or in the header right next to the counters!), let's check: in the header, or a floating card on the top right of the map!
Wait! A floating panel on the top right of the map:
<div className="absolute top-3 right-3 z-[1000] flex items-center gap-2 rounded-xl bg-slate-900/90 px-3 py-2 text-xs text-slate-100 shadow-xl backdrop-blur-sm">
<span className="font-bold text-sky-400">✈️ Полёты ({cityRouteCount}):</span>
<button onClick={() => setSimPaused(!simPaused)} className="rounded bg-slate-700 px-2 py-1 font-semibold hover:bg-slate-600">
{simPaused ? "▶️ Пуск" : "⏸ Пауза"}
</button>
<button onClick={() => setSimResetTrigger(c => c + 1)} className="rounded bg-slate-700 px-2 py-1 font-semibold hover:bg-slate-600" title="Перезапустить все самолёты с начала">
🔄 Сброс
</button>
<select value={simSpeed} onChange={e => setSimSpeed(Number(e.target.value))} className="rounded bg-slate-800 px-2 py-1 font-semibold text-sky-300 outline-none">
<option value={60}>x60 (1 мин/с)</option>
<option value={180}>x180 (3 мин/с)</option>
<option value={360}>x360 (6 мин/с)</option>
<option value={720}>x720 (12 мин/с)</option>
<option value={3600}>x3600 (1 ч/с)</option>
</select>
</div>
Wait! What if cityRouteCount === 0? If there are no active routes to Almetyevsk / Nizhnekamsk, should we still show the bar, or show a subtle text: ✈️ Включите маршрут до города в карточке точки для запуска самолёта?
If cityRouteCount > 0, we show the controls! If 0, we show: ✈️ Нет активных полётов (включите в карточке точки).
Let's edit src/App.tsx to add simSpeed, simPaused, simResetTrigger, pass them to MapView, and add the floating flight simulator widget on the map!
Let's check what we need to pass to MapView:
simSpeed: number;
simPaused: boolean;
simResetTrigger: number;
Let's edit src/App.tsx now. Remember our rules:
"For each file you create or edit, you must first explain what you are about to do, then call the tool, then confirm the result."
And "After using a tool, provide only a brief summary of what you did - DO NOT output the actual code content in your response text."
Let's edit src/App.tsx.I am going to edit src/App.tsx to add simulation state (simSpeed, simPaused, simResetTrigger), pass them to MapView, and add a floating flight simulation control bar on the map when flights to cities are active.
Now let's update where MapView is rendered and add the floating flight simulator widget inside main in src/App.tsx.
Let's check lines 380 to 420 of src/App.tsx. I will read lines 380 to 420 first.I will read lines 380 to 420 of src/App.tsx to check the exact context around MapView inside the main tag.
Let's edit src/App.tsx to pass the new simulation props to MapView and add the floating simulation bar at top-right of main. Remember to explain first, call tool, and summarize briefly.I will edit src/App.tsx to pass simSpeed, simPaused, and simResetTrigger to MapView and render a floating flight simulation controller at the top-right of the map when city flights are active.
I edited src/App.tsx and added the flight simulation control bar.
Now let's edit src/components/MapView.tsx to add simSpeed, simPaused, simResetTrigger to MapViewProps, and implement the airplane simulation loop!
Let's check what we need in MapView.tsx:
- Add
simSpeed: number; simPaused: boolean; simResetTrigger: number; to MapViewProps.
- Add a new LayerGroup
planes to layersRef.current and initialize it.
- Keep track of active flights in a ref
flightsStateRef.current: a map from flightId (${p.id}__${ep.id}) to { progress: number; pauseTimer: number; paused: boolean }.
- Keep track of created airplane markers in a ref
planeMarkersRef.current: a map from flightId to L.Marker.
- In
useEffect (or when simResetTrigger changes): if simResetTrigger changes, reset all progress in flightsStateRef.current to 0!
- In a
useEffect running an animation loop (requestAnimationFrame):
- Check all active flights (where
p.activeRoutes[ep.id] === true).
- If a marker in
planeMarkersRef.current is no longer active, remove it from layersRef.current.planes and delete from map.
- For each active flight:
- Get or create
st = flightsStateRef.current.get(flightId). If new, set { progress: 0, pauseTimer: 0, paused: false }.
- Get or create marker in
planeMarkersRef:
If not present: create L.marker([p.lat, p.lng], { icon: makePlaneIcon(ep.color, 0), zIndexOffset: 2500 }). Add click handler: toggle st.paused! Bind tooltip with direction: 'top', offset: [0, -18]. Add to layersRef.current.planes.
- Calculate delta time
dt (capped at 0.1s).
- If
!simPaused and !st.paused:
Calculate distance dist = haversine(p.lat, p.lng, ep.lat, ep.lng).
Duration in hours durHours = dist / (p.speed || 600).
Duration in seconds durSec = (durHours * 3600) / simSpeed.
If st.pauseTimer > 0:
st.pauseTimer -= dt; if (st.pauseTimer <= 0) st.progress = 0;
Else:
st.progress += dt / Math.max(0.1, durSec); if (st.progress >= 1) { st.progress = 1; st.pauseTimer = 2.0; }
- Update marker position and bearing:
curLat = p.lat + (ep.lat - p.lat) * st.progress
curLng = p.lng + (ep.lng - p.lng) * st.progress
bearing = calculateBearing(p.lat, p.lng, ep.lat, ep.lng)
marker.setLatLng([curLat, curLng])
Let's check: how should makePlaneIcon(color: string, bearing: number, paused: boolean) look?
Let's craft a sleek SVG airplane:
function makePlaneIcon(color: string, bearing: number, paused: boolean): L.DivIcon {
return L.divIcon({
className: "plane-icon-wrap",
html: `<div style="transform: rotate(${bearing}deg); transition: transform 0.2s ease;">
<svg width="34" height="34" viewBox="0 0 36 36" class="plane-svg" xmlns="http://www.w3.org/2000/svg">
<path d="M18 2 L21 12 L32 18 L32 21 L21 18 L21 28 L25 31 L25 33 L18 31 L11 33 L11 31 L15 28 L15 18 L4 21 L4 18 L15 12 Z" fill="${color}" stroke="#ffffff" stroke-width="1.8" stroke-linejoin="round"/>
${paused ? '<circle cx="18" cy="18" r="5" fill="#ef4444" stroke="#fff" stroke-width="1.5"/>' : '<circle cx="18" cy="18" r="3" fill="#22c55e" opacity="0.8"/>'}
</svg>
</div>`,
iconSize: [34, 34],
iconAnchor: [17, 17],
});
}
Wait! That is so clean! Let's read src/components/MapView.tsx around MapViewProps and the existing useEffects so we integrate this seamlessly without breaking drag-and-draw or any existing feature!
Let's read lines 1 to 100 of src/components/MapView.tsx. I will explain and call read_file.I will read the top 100 lines of src/components/MapView.tsx to check MapViewProps, the icon functions, and the refs before adding the airplane simulation logic.
Let's check lines 101 to 160 of src/components/MapView.tsx. I will explain and call read_file.I will read lines 101 to 160 of src/components/MapView.tsx to check where layers and refs are initialized.
Let's check where layers are added to map in useEffect (around line 160). I will read lines 160 to 200 of src/components/MapView.tsx.I will read lines 160 to 200 of src/components/MapView.tsx to check layer initialization and map event setup.
Let's check the end of src/components/MapView.tsx around lines 450 to 511. I will read lines 450 to 511.I will read lines 450 to 511 of src/components/MapView.tsx to inspect the bottom of the component where we will add the airplane simulation effect.
Let's edit src/components/MapView.tsx to add:
simSpeed: number; simPaused: boolean; simResetTrigger: number; to MapViewProps.
planes: L.LayerGroup; to layersRef.current and initialize it.
- Airplane simulation state refs and animation loop (
requestAnimationFrame).
Let's make sure we import calculateBearing, formatDurationPrecise, parseTimeMinutes, formatFlightClock from ../lib/geo.
Let's check what functions we import from ../lib/geo at the top of MapView.tsx:
Currently: import { haversine, formatDuration } from "../lib/geo";
We will change it to:
import { haversine, formatDuration, calculateBearing, formatDurationPrecise, parseTimeMinutes, formatFlightClock, formatCoord } from "../lib/geo";
Let's edit src/components/MapView.tsx now. Remember our rules: explain first, call tool, summarize briefly.I will edit src/components/MapView.tsx to import the new calculation helpers, add simSpeed, simPaused, and simResetTrigger to MapViewProps, initialize a planes layer group, and add the real-time airplane animation loop using requestAnimationFrame.
Now let's update MapView component to initialize planes layer, store simulation state in refs, and run the requestAnimationFrame simulation loop! Let's check lines 100 to 180 of src/components/MapView.tsx to see where layersRef.current is defined and initialized. I will read lines 100 to 180 first.I will read lines 100 to 180 of src/components/MapView.tsx to check where layersRef.current is defined and where layers are added to the map.
Let's read lines 180 to 220 of src/components/MapView.tsx as well to see where layersRef.current is set.I will read lines 180 to 220 of src/components/MapView.tsx to check where layers are initialized in useEffect.
Let's add planes: L.layerGroup().addTo(map) to layersRef.current and update the TypeScript type for layersRef.
We also need to add our refs for flights state and markers:
const flightsStateRef = useRef<Map<string, { progress: number; pauseTimer: number; paused: boolean }>>(new Map());
const planeMarkersRef = useRef<Map<string, L.Marker>>(new Map());
Let's see: when simResetTrigger changes (or when resetting), we can add an effect:
useEffect(() => {
flightsStateRef.current.forEach((st) => {
st.progress = 0;
st.pauseTimer = 0;
});
}, [simResetTrigger]);
And let's add the simulation animation loop effect!
Let's check: in the animation loop, how do we get the active flights?
We can use refs to access the latest points, endpoints, simSpeed, simPaused:
const endpointsRef = useRef(endpoints);
endpointsRef.current = endpoints;
const simSpeedRef = useRef(simSpeed);
simSpeedRef.current = simSpeed;
const simPausedRef = useRef(simPaused);
simPausedRef.current = simPaused;
Let's write a clean, robust useEffect for the animation loop:
useEffect(() => {
let animId: number;
let lastTime = performance.now();
const step = (now: number) => {
const dt = Math.min(0.1, (now - lastTime) / 1000);
lastTime = now;
const lyr = layersRef.current?.planes;
if (lyr && mapRef.current) {
const activeFlightIds = new Set<string>();
const pts = pointsRef.current;
const eps = endpointsRef.current;
const spd = simSpeedRef.current;
const isGlobalPaused = simPausedRef.current;
pts.forEach((p) => {
eps.forEach((ep) => {
if (!p.activeRoutes?.[ep.id]) return;
const flightId = `${p.id}__${ep.id}`;
activeFlightIds.add(flightId);
let st = flightsStateRef.current.get(flightId);
if (!st) {
st = { progress: 0, pauseTimer: 0, paused: false };
flightsStateRef.current.set(flightId, st);
}
let marker = planeMarkersRef.current.get(flightId);
if (!marker) {
marker = L.marker([p.lat, p.lng], {
icon: makePlaneIcon(ep.color, 0, st.paused),
zIndexOffset: 2500,
});
marker.bindTooltip("", { direction: "top", offset: [0, -18] });
marker.on("click", (e) => {
L.DomEvent.stopPropagation(e);
const curSt = flightsStateRef.current.get(flightId);
if (curSt) {
curSt.paused = !curSt.paused;
const m = planeMarkersRef.current.get(flightId);
if (m) {
const brng = calculateBearing(p.lat, p.lng, ep.lat, ep.lng);
m.setIcon(makePlaneIcon(ep.color, brng, curSt.paused));
}
}
});
marker.addTo(lyr);
planeMarkersRef.current.set(flightId, marker);
}
const dist = haversine(p.lat, p.lng, ep.lat, ep.lng);
const speedKmh = p.speed || 600;
const durHours = speedKmh > 0 ? dist / speedKmh : 0;
const durSec = durHours > 0 ? (durHours * 3600) / spd : 1;
if (!isGlobalPaused && !st.paused && durSec > 0) {
if (st.pauseTimer > 0) {
st.pauseTimer -= dt;
if (st.pauseTimer <= 0) st.progress = 0;
} else {
st.progress += dt / Math.max(0.1, durSec);
if (st.progress >= 1) {
st.progress = 1;
st.pauseTimer = 2.0;
}
}
}
const curLat = p.lat + (ep.lat - p.lat) * st.progress;
const curLng = p.lng + (ep.lng - p.lng) * st.progress;
const brng = calculateBearing(p.lat, p.lng, ep.lat, ep.lng);
marker.setLatLng([curLat, curLng]);
marker.setIcon(makePlaneIcon(ep.color, brng, st.paused || isGlobalPaused));
const distCovered = dist * st.progress;
const elapsedHours = durHours * st.progress;
const remHours = durHours * (1 - st.progress);
const startMin = parseTimeMinutes(p.fixTime);
const clock = formatFlightClock(startMin, elapsedHours, durHours);
const statusBadge = st.paused || isGlobalPaused
? '<span style="color:#ef4444">⏸ ПАУЗА</span>'
: st.progress >= 1
? '<span style="color:#3b82f6">🛬 ПОСАДКА</span>'
: '<span style="color:#22c55e">▶️ В ПОЛЁТЕ</span>';
marker.setTooltipContent(
`<div class="plane-telemetry">
<div class="pt-title" style="color:${ep.color}">
<span>✈️</span>
<span>${p.name} → ${ep.name}</span>
<span style="margin-left:auto; font-size:10px">${statusBadge}</span>
</div>
<div class="pt-row"><span class="pt-label">📍 Место (коорд.):</span><span class="pt-value">${formatCoord(curLat)}, ${formatCoord(curLng)}</span></div>
<div class="pt-row"><span class="pt-label">🚀 Скорость:</span><span class="pt-value">${speedKmh} км/ч</span></div>
<div class="pt-row"><span class="pt-label">📏 Пройдено:</span><span class="pt-value">${distCovered.toFixed(1)} км из ${dist.toFixed(1)} км (${Math.round(st.progress * 100)}%)</span></div>
<div class="pt-row"><span class="pt-label">⏱️ В пути / Ост.:</span><span class="pt-value">${formatDurationPrecise(elapsedHours)} / ${formatDurationPrecise(remHours)}</span></div>
${clock ? `<div class="pt-row"><span class="pt-label">⏰ Время по часам:</span><span class="pt-value" style="color:#16a34a">${clock.curTime} (прилёт ${clock.arrTime})</span></div>` : `<div class="pt-row"><span class="pt-label">⏰ Время вылета:</span><span class="pt-value" style="color:#94a3b8">не указано</span></div>`}
<div class="pt-row" style="margin-top:4px"><span style="font-size:10px; color:#94a3b8; font-style:italic">💡 Клик по самолёту — Пауза / Старт</span></div>
<div class="pt-progress-bar">
<div class="pt-progress-fill" style="width:${Math.round(st.progress * 100)}%; background:${ep.color}"></div>
</div>
</div>`
);
});
});
// Очистка удалённых или отключённых полётов
planeMarkersRef.current.forEach((marker, flightId) => {
if (!activeFlightIds.has(flightId)) {
marker.remove();
planeMarkersRef.current.delete(flightId);
flightsStateRef.current.delete(flightId);
}
});
}
animId = requestAnimationFrame(step);
};
animId = requestAnimationFrame(step);
return () => cancelAnimationFrame(animId);
}, []);
Wait! Let's check this animation loop: it is completely self-contained, cleans up after itself when routes or points are removed, uses requestAnimationFrame for buttery smooth 60 FPS movement, allows pausing/resuming individual planes by clicking on them, and shows rich live telemetry with coordinates, speed, distance, duration, and clock time!
Let's edit src/components/MapView.tsx to integrate this!
Let's first edit lines around layersRef definition and initialization. I will explain and call edit_file.I will edit src/components/MapView.tsx to add planes to layersRef.current, initialize the layer group, and add refs for tracking flight simulation progress and airplane markers.
Now let's edit src/components/MapView.tsx to add planes: L.layerGroup().addTo(map) to layersRef.current initialization. I will explain and call edit_file.I will edit src/components/MapView.tsx to initialize planes: L.layerGroup().addTo(map) inside the map initialization useEffect.
Now let's check the end of src/components/MapView.tsx (before return <div ref={containerRef}...) and add:
- Refs to track latest props:
endpointsRef, simSpeedRef, simPausedRef.
useEffect to reset flights when simResetTrigger changes.
useEffect with requestAnimationFrame for the live airplane simulation!
Let's read lines 490 to 515 of src/components/MapView.tsx first.I will read the last 30 lines of src/components/MapView.tsx to check where to place the simulation useEffect hooks before the return statement.
Let's read lines 520 to 541 of src/components/MapView.tsx. I will explain and call read_file.I will read the remaining lines (520-541) of src/components/MapView.tsx to check the end of the component.
Let's edit src/components/MapView.tsx to add the refs and effects for airplane flight simulation! Remember to explain first, call tool, and summarize briefly.I will edit src/components/MapView.tsx to add latest-prop refs (endpointsRef, simSpeedRef, simPausedRef), a reset effect for simResetTrigger, and the requestAnimationFrame flight simulation loop that animates planes along active routes to cities with live telemetry.
Let's fix those names: in MapViewProps we destructured mapMode, but we need to destructure simSpeed, simPaused, simResetTrigger from MapViewProps!
Let's check line 125 of src/components/MapView.tsx where we destructure MapViewProps. I will read lines 110 to 135 of src/components/MapView.tsx.I will read lines 110 to 135 of src/components/MapView.tsx to check where props are destructured in the component signature.
Let's edit src/components/MapView.tsx to destructure simSpeed, simPaused, simResetTrigger from MapViewProps. I will explain and call edit_file.I will edit src/components/MapView.tsx to destructure simSpeed, simPaused, and simResetTrigger in the component function parameters.
Let's build the project using build_project to verify there are no TypeScript or bundling issues! Remember:
"When you are finished, ALWAYS use build_project to confirm that the project builds successfully. NEVER try to write your own build command."
Let's call build_project now.I will build the project now to confirm that our airplane flight simulation and live telemetry compile cleanly.
The build succeeded! The single-file bundle is ready.
Let's summarize the new features for the user clearly in Russian as requested.## ✅ Что реализовано — Анимация полёта самолётов до Альметьевска и Нижнекамска
✈️ Живой полёт самолёта по маршруту
-
Автоматический вылет при включении маршрута:
- Как только в карточке точки фиксации включается маршрут до г. Альметьевск (зелёный) или г. Нижнекамск (синий), с этой точки на карте сразу вылетает самолёт!
- Иконка самолёта автоматически поворачивается носом точно по направлению (азимуту) к выбранному городу.
- Полет идёт плавно со скоростью 60 FPS по реальной траектории.
-
Расчёт движения с учётом места, времени и скорости:
- 📍 Место (координаты): В процессе полёта непрерывно рассчитываются и отображаются точные текущие координаты (широта, долгота), пройденное расстояние и оставшийся путь в километрах.
- 🚀 Скорость движения: Используется индивидуальная скорость полёта, заданная в карточке точки фиксации (например, 600 км/ч или 800 км/ч). От неё напрямую зависит длительность полёта.
- ⏰ Время (с учётом времени фиксации):
- Если у точки указано «Время» (например,
10:30), система рассчитывает бортовые часы: прибавляет к времени вылета текущее время в пути и вычисляет точное время прилета в город (например, 10:37:15 (прилёт в 10:45)).
- Показываются секундомеры: сколько времени прошло с момента старта и сколько осталось до посадки.
-
🛰️ Телеметрия на карте (при наведении или клике):
- Наведите курсор на летящий самолёт — появится подробное табло с бортовой телеметрией:
- Маршрут и статус полёта (▶️ В ПОЛЁТЕ / ⏸ ПАУЗА / 🛬 ПОСАДКА)
- Текущие координаты
- Скорость в км/ч
- Пройденная дистанция и прогресс-бар в %
- Секундомер времени в пути и оставшегося времени
- Время по бортовым часам и расчётное время посадки в городе
-
🕹️ Панель управления авиа-симулятором (в правом верхнем углу карты):
- Когда активен хотя бы один полёт до городов, на карте появляется панель управления:
- [⏸ Пауза / ▶️ Пуск] — остановить или возобновить движение всех самолётов одновременно.
- [🔄 Сбросить] — вернуть все самолёты на стартовые точки фиксации и запустить полёт заново.
- Выбор скорости анимации (ускорение времени):
- x60: 1 минута полёта проходит за 1 секунду реального времени
Запуск приложения:
start.bat
или в командной строке:
npm run build && node server.js
Откройте в браузере: http://localhost:3000
Files built: src/lib/geo.ts, src/index.css, src/App.tsx, src/components/MapView.tsx