Update application ports to 3051 and enhance frontend/backend configurations
This commit is contained in:
@@ -3,7 +3,8 @@
|
|||||||
"allow": [
|
"allow": [
|
||||||
"Bash(npm test:*)",
|
"Bash(npm test:*)",
|
||||||
"Bash(npm run:*)",
|
"Bash(npm run:*)",
|
||||||
"Bash(npx playwright:*)"
|
"Bash(npx playwright:*)",
|
||||||
|
"Bash(node -e ':*)"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
### Docker (preferred workflow)
|
### Docker (preferred workflow)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker-compose up --build # Start all services (frontend :3050, backend :3001, postgres)
|
docker-compose up --build # Start all services (frontend :3050, backend :3051, postgres)
|
||||||
docker-compose down # Stop all services
|
docker-compose down # Stop all services
|
||||||
docker-compose logs -f # View logs
|
docker-compose logs -f # View logs
|
||||||
|
|
||||||
@@ -25,7 +25,7 @@ docker-compose exec frontend npm run test:e2e
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Backend
|
# Backend
|
||||||
cd backend && npm run dev # Nodemon dev server on :3001
|
cd backend && npm run dev # Nodemon dev server on :3051
|
||||||
|
|
||||||
# Frontend
|
# Frontend
|
||||||
cd frontend && npm run start # Vite dev server on :3050
|
cd frontend && npm run start # Vite dev server on :3050
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ docker-compose up --build
|
|||||||
### 3. Access Application
|
### 3. Access Application
|
||||||
|
|
||||||
- **Frontend**: http://localhost:3050
|
- **Frontend**: http://localhost:3050
|
||||||
- **Backend API**: http://localhost:3001
|
- **Backend API**: http://localhost:3051
|
||||||
- **Database**: localhost:5432 (PostgreSQL with PostGIS)
|
- **Database**: localhost:5432 (PostgreSQL with PostGIS)
|
||||||
|
|
||||||
## 🎮 How to Use
|
## 🎮 How to Use
|
||||||
@@ -220,7 +220,7 @@ npm run dev
|
|||||||
```bash
|
```bash
|
||||||
# Find process using port
|
# Find process using port
|
||||||
lsof -i :3050
|
lsof -i :3050
|
||||||
lsof -i :3001
|
lsof -i :3051
|
||||||
|
|
||||||
# Kill process
|
# Kill process
|
||||||
kill -9 <PID>
|
kill -9 <PID>
|
||||||
|
|||||||
+1
-1
@@ -10,7 +10,7 @@ RUN npm install
|
|||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Expose port
|
# Expose port
|
||||||
EXPOSE 3001
|
EXPOSE 3051
|
||||||
|
|
||||||
# Start server
|
# Start server
|
||||||
CMD ["npm", "start"]
|
CMD ["npm", "start"]
|
||||||
|
|||||||
+54
-32
@@ -4,9 +4,8 @@ const { Pool } = require('pg');
|
|||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const PORT = process.env.PORT || 3001;
|
const PORT = process.env.PORT || 3051;
|
||||||
|
|
||||||
// Database connection pool
|
|
||||||
const pool = new Pool({
|
const pool = new Pool({
|
||||||
connectionString: process.env.DATABASE_URL || 'postgresql://line_of_sight:line_of_sight_pass@postgres:5432/line_of_sight'
|
connectionString: process.env.DATABASE_URL || 'postgresql://line_of_sight:line_of_sight_pass@postgres:5432/line_of_sight'
|
||||||
});
|
});
|
||||||
@@ -14,7 +13,6 @@ const pool = new Pool({
|
|||||||
app.use(cors());
|
app.use(cors());
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
|
|
||||||
// Helper to calculate destination point given start, bearing, and distance (km)
|
|
||||||
const calculateDestination = (lat, lon, bearing, distance) => {
|
const calculateDestination = (lat, lon, bearing, distance) => {
|
||||||
const R = 6371;
|
const R = 6371;
|
||||||
const brng = (bearing * Math.PI) / 180;
|
const brng = (bearing * Math.PI) / 180;
|
||||||
@@ -39,40 +37,46 @@ const calculateDestination = (lat, lon, bearing, distance) => {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
// Real API endpoint - uses PostGIS for spatial queries
|
const haversineKm = (lat1, lon1, lat2, lon2) => {
|
||||||
|
const R = 6371;
|
||||||
|
const toRad = (d) => d * Math.PI / 180;
|
||||||
|
const dLat = toRad(lat2 - lat1);
|
||||||
|
const dLon = toRad(lon2 - lon1);
|
||||||
|
const a = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2;
|
||||||
|
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||||
|
};
|
||||||
|
|
||||||
app.get('/api/line-of-sight', async (req, res) => {
|
app.get('/api/line-of-sight', async (req, res) => {
|
||||||
const { lat, lon, direction, tolerance } = req.query;
|
const { lat, lon, direction, tolerance } = req.query;
|
||||||
|
|
||||||
const startLat = parseFloat(lat) || 51.5074;
|
const startLat = parseFloat(lat) || 51.5074;
|
||||||
const startLon = parseFloat(lon) || -0.1278;
|
const startLon = parseFloat(lon) || -0.1278;
|
||||||
const bearing = parseInt(direction) || 0;
|
const bearing = parseInt(direction) || 0;
|
||||||
const toleranceKm = parseInt(tolerance) || 50;
|
const toleranceKm = parseInt(tolerance) || 50;
|
||||||
|
|
||||||
console.log(`Processing real request: lat=${startLat}, lon=${startLon}, bearing=${bearing}, tolerance=${toleranceKm}`);
|
console.log(`Processing request: lat=${startLat}, lon=${startLon}, bearing=${bearing}, tolerance=${toleranceKm}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Generate path points for visualization and spatial query
|
|
||||||
const pathPoints = [];
|
const pathPoints = [];
|
||||||
const totalDistance = 40074; // Full Earth circumference (km)
|
const totalDistance = 40074;
|
||||||
const steps = 160;
|
const steps = 160;
|
||||||
|
|
||||||
for (let i = 0; i <= steps; i++) {
|
for (let i = 0; i <= steps; i++) {
|
||||||
const dist = (totalDistance * i) / steps;
|
const dist = (totalDistance * i) / steps;
|
||||||
pathPoints.push(calculateDestination(startLat, startLon, bearing, dist));
|
pathPoints.push(calculateDestination(startLat, startLon, bearing, dist));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Batch check for 'over water' status for all path points
|
// Batch water check: a point is "over water" if no city is within 500 km
|
||||||
// We'll consider a point 'over water' if no city is within 500km
|
|
||||||
const waterChecks = await Promise.all(pathPoints.map(async (p) => {
|
const waterChecks = await Promise.all(pathPoints.map(async (p) => {
|
||||||
const checkQuery = `
|
const checkQuery = `
|
||||||
SELECT EXISTS (
|
SELECT EXISTS (
|
||||||
SELECT 1 FROM cities
|
SELECT 1 FROM cities
|
||||||
WHERE ST_DWithin(geom, ST_SetSRID(ST_MakePoint($1, $2), 4326)::geography, 500000)
|
WHERE ST_DWithin(geom, ST_SetSRID(ST_MakePoint($1, $2), 4326)::geography, 500000)
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
) as has_land;
|
) as has_land;
|
||||||
`;
|
`;
|
||||||
const res = await pool.query(checkQuery, [p.lon, p.lat]);
|
const r = await pool.query(checkQuery, [p.lon, p.lat]);
|
||||||
return !res.rows[0].has_land;
|
return !r.rows[0].has_land;
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const pathPointsWithWater = pathPoints.map((p, i) => ({
|
const pathPointsWithWater = pathPoints.map((p, i) => ({
|
||||||
@@ -81,37 +85,56 @@ app.get('/api/line-of-sight', async (req, res) => {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
const lineWKT = `LINESTRING(${pathPoints.map(p => `${p.lon} ${p.lat}`).join(',')})`;
|
const lineWKT = `LINESTRING(${pathPoints.map(p => `${p.lon} ${p.lat}`).join(',')})`;
|
||||||
|
|
||||||
|
// Top 5 cities per 100 km bin, ranked by population descending
|
||||||
const query = `
|
const query = `
|
||||||
WITH path AS (
|
WITH path AS (
|
||||||
SELECT ST_GeogFromText($1) as route,
|
SELECT ST_GeogFromText($1) as route,
|
||||||
ST_MakePoint($3, $4)::geography as start_node
|
ST_MakePoint($3, $4)::geography as start_node
|
||||||
|
),
|
||||||
|
candidates AS (
|
||||||
|
SELECT
|
||||||
|
id, name, population, country,
|
||||||
|
ST_Y(geom::geometry) as lat,
|
||||||
|
ST_X(geom::geometry) as lon,
|
||||||
|
ST_Distance(geom, (SELECT route FROM path)) / 1000 as distance_off_line_km,
|
||||||
|
ST_Distance(geom, (SELECT start_node FROM path)) / 1000 as distance_from_start_km,
|
||||||
|
ST_LineLocatePoint((SELECT route FROM path)::geometry, geom::geometry) as pos_on_line,
|
||||||
|
FLOOR(ST_Distance(geom, (SELECT start_node FROM path)) / 1000 / 100)::int as bin_100km
|
||||||
|
FROM cities
|
||||||
|
WHERE ST_DWithin(geom, (SELECT route FROM path), $2 * 1000)
|
||||||
|
),
|
||||||
|
ranked AS (
|
||||||
|
SELECT *,
|
||||||
|
ROW_NUMBER() OVER (PARTITION BY bin_100km ORDER BY population DESC NULLS LAST) as rank_in_bin
|
||||||
|
FROM candidates
|
||||||
)
|
)
|
||||||
SELECT
|
SELECT id, name, population, country, lat, lon,
|
||||||
id,
|
distance_off_line_km, distance_from_start_km, pos_on_line
|
||||||
name,
|
FROM ranked
|
||||||
population,
|
WHERE rank_in_bin <= 5
|
||||||
country,
|
ORDER BY pos_on_line ASC;
|
||||||
ST_Y(geom::geometry) as lat,
|
|
||||||
ST_X(geom::geometry) as lon,
|
|
||||||
ST_Distance(geom, (SELECT route FROM path)) / 1000 as distance_off_line_km,
|
|
||||||
ST_Distance(geom, (SELECT start_node FROM path)) / 1000 as distance_from_start_km,
|
|
||||||
ST_LineLocatePoint((SELECT route FROM path)::geometry, geom::geometry) as pos_on_line
|
|
||||||
FROM cities
|
|
||||||
WHERE ST_DWithin(geom, (SELECT route FROM path), $2 * 1000)
|
|
||||||
ORDER BY pos_on_line ASC
|
|
||||||
LIMIT 200;
|
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const result = await pool.query(query, [lineWKT, toleranceKm, startLon, startLat]);
|
const result = await pool.query(query, [lineWKT, toleranceKm, startLon, startLat]);
|
||||||
|
|
||||||
|
// Greedy 30 km deduplication: sort by population desc, accept a city only if
|
||||||
|
// it's at least 30 km from every already-accepted city.
|
||||||
|
const byPopulation = [...result.rows].sort((a, b) => (b.population || 0) - (a.population || 0));
|
||||||
|
const accepted = [];
|
||||||
|
for (const city of byPopulation) {
|
||||||
|
const tooClose = accepted.some(s => haversineKm(s.lat, s.lon, city.lat, city.lon) < 30);
|
||||||
|
if (!tooClose) accepted.push(city);
|
||||||
|
}
|
||||||
|
accepted.sort((a, b) => a.pos_on_line - b.pos_on_line);
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
start_point: { lat: startLat, lon: startLon },
|
start_point: { lat: startLat, lon: startLon },
|
||||||
direction: bearing,
|
direction: bearing,
|
||||||
tolerance_km: toleranceKm,
|
tolerance_km: toleranceKm,
|
||||||
conurbations: result.rows.map(row => ({
|
conurbations: accepted.map(row => ({
|
||||||
...row,
|
...row,
|
||||||
name: row.name || 'Unknown',
|
name: row.name || 'Unknown',
|
||||||
country: row.country || 'Unknown',
|
country: row.country || 'Unknown',
|
||||||
@@ -127,7 +150,6 @@ app.get('/api/line-of-sight', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Health check endpoint
|
|
||||||
app.get('/api/health', (req, res) => {
|
app.get('/api/health', (req, res) => {
|
||||||
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||||||
});
|
});
|
||||||
|
|||||||
+3
-3
@@ -27,10 +27,10 @@ services:
|
|||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
container_name: line-of-sight-backend
|
container_name: line-of-sight-backend
|
||||||
ports:
|
ports:
|
||||||
- "3001:3001"
|
- "3051:3051"
|
||||||
environment:
|
environment:
|
||||||
- DATABASE_URL=postgresql://line_of_sight:line_of_sight_pass@postgres:5432/line_of_sight
|
- DATABASE_URL=postgresql://line_of_sight:line_of_sight_pass@postgres:5432/line_of_sight
|
||||||
- PORT=3001
|
- PORT=3051
|
||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -46,7 +46,7 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "3050:3050"
|
- "3050:3050"
|
||||||
environment:
|
environment:
|
||||||
- VITE_API_URL=http://localhost:3001/api
|
- VITE_API_URL=http://localhost:3051/api
|
||||||
depends_on:
|
depends_on:
|
||||||
- backend
|
- backend
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
+1
-1
@@ -13,7 +13,7 @@ COPY . .
|
|||||||
EXPOSE 3050
|
EXPOSE 3050
|
||||||
|
|
||||||
# Set environment variable for API URL
|
# Set environment variable for API URL
|
||||||
ENV VITE_API_URL=http://localhost:3001/api
|
ENV VITE_API_URL=http://localhost:3051/api
|
||||||
|
|
||||||
# Start development server
|
# Start development server
|
||||||
CMD ["npm", "start"]
|
CMD ["npm", "start"]
|
||||||
|
|||||||
+151
-85
@@ -12,38 +12,47 @@ const APP = () => {
|
|||||||
const cityMarkersRef = useRef([]);
|
const cityMarkersRef = useRef([]);
|
||||||
const animationRef = useRef(null);
|
const animationRef = useRef(null);
|
||||||
const popupRef = useRef(null);
|
const popupRef = useRef(null);
|
||||||
// Ref mirrors mapProjection state so stale closures (style.load) read the current value
|
// Refs mirror state so stale closures (e.g. style.load) always read the current value
|
||||||
const mapProjectionRef = useRef('globe');
|
const mapProjectionRef = useRef('globe');
|
||||||
|
const selectedPointRef = useRef({ lat: 51.5074, lon: -0.1278 });
|
||||||
|
const directionRef = useRef(90);
|
||||||
|
const lineOfSightDataRef = useRef(null);
|
||||||
|
const flightProgressRef = useRef(0);
|
||||||
|
const seekRef = useRef(null);
|
||||||
|
const currentCityIndexRef = useRef(-1);
|
||||||
|
|
||||||
const [selectedPoint, setSelectedPoint] = useState({ lat: 51.5074, lon: -0.1278 });
|
const [selectedPoint, setSelectedPoint] = useState({ lat: 51.5074, lon: -0.1278 });
|
||||||
const [direction, setDirection] = useState(45);
|
const [direction, setDirection] = useState(90);
|
||||||
const [lineOfSightData, setLineOfSightData] = useState(null);
|
const [lineOfSightData, setLineOfSightData] = useState(null);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [isPlaying, setIsPlaying] = useState(false);
|
const [isPlaying, setIsPlaying] = useState(false);
|
||||||
const [flightSpeed, setFlightSpeed] = useState(1.0);
|
const [flightSpeed, setFlightSpeed] = useState(1.0);
|
||||||
const [mapStyle, setMapStyle] = useState('light');
|
const [mapStyle, setMapStyle] = useState('basic');
|
||||||
const [mapProjection, setMapProjection] = useState('globe');
|
const [mapProjection, setMapProjection] = useState('globe');
|
||||||
const [tolerance, setTolerance] = useState(50);
|
const [tolerance, setTolerance] = useState(50);
|
||||||
const [selectedCity, setSelectedCity] = useState(null);
|
const [selectedCity, setSelectedCity] = useState(null);
|
||||||
const [isLocked, setIsLocked] = useState(false);
|
const [isLocked, setIsLocked] = useState(false);
|
||||||
|
const [currentCityIndex, setCurrentCityIndex] = useState(-1);
|
||||||
|
|
||||||
// Keep ref in sync with state
|
// Keep refs in sync with state so stale closures always have current values
|
||||||
|
useEffect(() => { mapProjectionRef.current = mapProjection; }, [mapProjection]);
|
||||||
|
useEffect(() => { selectedPointRef.current = selectedPoint; }, [selectedPoint]);
|
||||||
|
useEffect(() => { directionRef.current = direction; }, [direction]);
|
||||||
|
useEffect(() => { lineOfSightDataRef.current = lineOfSightData; }, [lineOfSightData]);
|
||||||
|
|
||||||
|
// Auto-scroll sidebar to current city during flight
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
mapProjectionRef.current = mapProjection;
|
if (isPlaying && currentCityIndex >= 0) {
|
||||||
}, [mapProjection]);
|
const row = document.getElementById(`city-row-${currentCityIndex}`);
|
||||||
|
if (row) row.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||||
|
}
|
||||||
|
}, [currentCityIndex, isPlaying]);
|
||||||
|
|
||||||
// --- Helpers ---
|
// --- Helpers ---
|
||||||
|
|
||||||
// Build GeoJSON for the line, splitting at the antimeridian for flat projections
|
// Build GeoJSON for the line, splitting at the antimeridian for flat projections
|
||||||
const buildLineGeoJSON = (lineCoords, projection) => {
|
const buildLineGeoJSON = (lineCoords) => {
|
||||||
const coords = lineCoords.map(c => [c.lon, c.lat]);
|
const coords = lineCoords.map(c => [c.lon, c.lat]);
|
||||||
if (projection === 'globe') {
|
|
||||||
return {
|
|
||||||
type: 'Feature',
|
|
||||||
properties: {},
|
|
||||||
geometry: { type: 'LineString', coordinates: coords }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
// Split segments wherever consecutive points cross the antimeridian (±180°)
|
// Split segments wherever consecutive points cross the antimeridian (±180°)
|
||||||
const segments = [];
|
const segments = [];
|
||||||
let current = [coords[0]];
|
let current = [coords[0]];
|
||||||
@@ -80,7 +89,8 @@ const APP = () => {
|
|||||||
ctx.lineTo(size * 0.78, size * 0.5);
|
ctx.lineTo(size * 0.78, size * 0.5);
|
||||||
ctx.lineTo(size * 0.2, size * 0.78);
|
ctx.lineTo(size * 0.2, size * 0.78);
|
||||||
ctx.stroke();
|
ctx.stroke();
|
||||||
map.addImage('arrow-icon', canvas);
|
// MapLibre v5 requires ImageData, not a raw canvas element
|
||||||
|
map.addImage('arrow-icon', ctx.getImageData(0, 0, size, size));
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Map initialisation (runs once) ---
|
// --- Map initialisation (runs once) ---
|
||||||
@@ -92,7 +102,7 @@ const APP = () => {
|
|||||||
center: [-0.1278, 51.5074],
|
center: [-0.1278, 51.5074],
|
||||||
zoom: 2,
|
zoom: 2,
|
||||||
pitch: 0,
|
pitch: 0,
|
||||||
projection: 'globe'
|
projection: { type: 'globe' }
|
||||||
});
|
});
|
||||||
|
|
||||||
mapRef.current.on('style.load', () => {
|
mapRef.current.on('style.load', () => {
|
||||||
@@ -136,10 +146,15 @@ const APP = () => {
|
|||||||
map.setTerrain({ source: 'terrain', exaggeration: 1.5 });
|
map.setTerrain({ source: 'terrain', exaggeration: 1.5 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Read current values from refs to avoid stale closure problems
|
||||||
|
const currentPoint = selectedPointRef.current;
|
||||||
|
const currentDirection = directionRef.current;
|
||||||
|
const currentLineData = lineOfSightDataRef.current;
|
||||||
|
|
||||||
// 3. Start marker
|
// 3. Start marker
|
||||||
if (startMarkerRef.current) startMarkerRef.current.remove();
|
if (startMarkerRef.current) startMarkerRef.current.remove();
|
||||||
startMarkerRef.current = new maplibregl.Marker({ color: '#FF6B6B' })
|
startMarkerRef.current = new maplibregl.Marker({ color: '#FF6B6B' })
|
||||||
.setLngLat([selectedPoint.lon, selectedPoint.lat])
|
.setLngLat([currentPoint.lon, currentPoint.lat])
|
||||||
.addTo(map);
|
.addTo(map);
|
||||||
|
|
||||||
// 4. Preview line source and layer
|
// 4. Preview line source and layer
|
||||||
@@ -157,13 +172,13 @@ const APP = () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 5. Restore results line and markers if they existed
|
// 5. Restore results line and markers if they existed
|
||||||
if (lineOfSightData) {
|
if (currentLineData) {
|
||||||
renderLineOnMap(lineOfSightData);
|
renderLineOnMap(currentLineData);
|
||||||
if (map.getLayer('preview-line')) {
|
if (map.getLayer('preview-line')) {
|
||||||
map.setLayoutProperty('preview-line', 'visibility', 'none');
|
map.setLayoutProperty('preview-line', 'visibility', 'none');
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
updatePreviewLine(selectedPoint, direction);
|
updatePreviewLine(currentPoint, currentDirection);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -173,29 +188,38 @@ const APP = () => {
|
|||||||
const map = mapRef.current;
|
const map = mapRef.current;
|
||||||
if (!map) return;
|
if (!map) return;
|
||||||
|
|
||||||
map.setProjection(mapProjection);
|
const applyProjection = () => {
|
||||||
|
map.setProjection({ type: mapProjection });
|
||||||
|
|
||||||
if (mapProjection === 'globe') {
|
if (mapProjection === 'globe') {
|
||||||
map.setSky({
|
map.setSky({
|
||||||
'sky-color': '#199EF3',
|
'sky-color': '#199EF3',
|
||||||
'sky-horizon-blend': 0.5,
|
'sky-horizon-blend': 0.5,
|
||||||
'horizon-color': '#ffffff',
|
'horizon-color': '#ffffff',
|
||||||
'horizon-fog-blend': 0.5,
|
'horizon-fog-blend': 0.5,
|
||||||
'fog-color': '#add8e6',
|
'fog-color': '#add8e6',
|
||||||
'fog-ground-blend': 0.5
|
'fog-ground-blend': 0.5
|
||||||
});
|
});
|
||||||
if (map.getSource('terrain')) {
|
if (map.getSource('terrain')) {
|
||||||
map.setTerrain({ source: 'terrain', exaggeration: 1.5 });
|
map.setTerrain({ source: 'terrain', exaggeration: 1.5 });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
map.setTerrain(null);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
map.setTerrain(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Re-render line with correct antimeridian handling for this projection
|
// Re-render line with correct antimeridian handling for this projection
|
||||||
if (lineOfSightData && map.getSource('line-of-sight')) {
|
if (lineOfSightData && map.getSource('line-of-sight')) {
|
||||||
map.getSource('line-of-sight').setData(
|
map.getSource('line-of-sight').setData(
|
||||||
buildLineGeoJSON(lineOfSightData.line_coordinates, mapProjection)
|
buildLineGeoJSON(lineOfSightData.line_coordinates)
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (map.isStyleLoaded()) {
|
||||||
|
applyProjection();
|
||||||
|
} else {
|
||||||
|
map.once('style.load', applyProjection);
|
||||||
|
return () => map.off('style.load', applyProjection);
|
||||||
}
|
}
|
||||||
}, [mapProjection]); // eslint-disable-line react-hooks/exhaustive-deps
|
}, [mapProjection]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
@@ -207,6 +231,8 @@ const APP = () => {
|
|||||||
const handleClick = (e) => {
|
const handleClick = (e) => {
|
||||||
if (isLocked) return;
|
if (isLocked) return;
|
||||||
const { lng, lat } = e.lngLat;
|
const { lng, lat } = e.lngLat;
|
||||||
|
// Update ref immediately (state update is async)
|
||||||
|
selectedPointRef.current = { lat, lon: lng };
|
||||||
setSelectedPoint({ lat, lon: lng });
|
setSelectedPoint({ lat, lon: lng });
|
||||||
if (startMarkerRef.current) {
|
if (startMarkerRef.current) {
|
||||||
startMarkerRef.current.setLngLat([lng, lat]);
|
startMarkerRef.current.setLngLat([lng, lat]);
|
||||||
@@ -218,6 +244,9 @@ const APP = () => {
|
|||||||
map.removeLayer('line-of-sight');
|
map.removeLayer('line-of-sight');
|
||||||
map.removeSource('line-of-sight');
|
map.removeSource('line-of-sight');
|
||||||
}
|
}
|
||||||
|
if (map.getLayer('preview-line')) {
|
||||||
|
map.setLayoutProperty('preview-line', 'visibility', 'visible');
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
mapRef.current.on('click', handleClick);
|
mapRef.current.on('click', handleClick);
|
||||||
@@ -322,20 +351,23 @@ const APP = () => {
|
|||||||
if (animationRef.current) cancelAnimationFrame(animationRef.current);
|
if (animationRef.current) cancelAnimationFrame(animationRef.current);
|
||||||
setIsPlaying(false);
|
setIsPlaying(false);
|
||||||
setFlightSpeed(1.0);
|
setFlightSpeed(1.0);
|
||||||
|
setCurrentCityIndex(-1);
|
||||||
|
currentCityIndexRef.current = -1;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setIsPlaying(true);
|
setIsPlaying(true);
|
||||||
setSelectedCity(null);
|
setCurrentCityIndex(-1);
|
||||||
|
currentCityIndexRef.current = -1;
|
||||||
if (popupRef.current) popupRef.current.remove();
|
if (popupRef.current) popupRef.current.remove();
|
||||||
|
|
||||||
const coordinates = lineOfSightData.line_coordinates.map(c => [c.lon, c.lat]);
|
const coordinates = lineOfSightData.line_coordinates.map(c => [c.lon, c.lat]);
|
||||||
const route = turf.lineString(coordinates);
|
const route = turf.lineString(coordinates);
|
||||||
const routeDistance = turf.length(route);
|
const routeDistance = turf.length(route);
|
||||||
|
|
||||||
let lastNearestCityId = null;
|
let lastFetchedDist = flightProgressRef.current;
|
||||||
let lastFetchedDist = 0;
|
let currentProgress = flightProgressRef.current;
|
||||||
let currentProgress = 0;
|
flightProgressRef.current = 0;
|
||||||
let lastTimestamp = performance.now();
|
let lastTimestamp = performance.now();
|
||||||
let currentSpeedMultiplier = 1.0;
|
let currentSpeedMultiplier = 1.0;
|
||||||
let frameCount = 0;
|
let frameCount = 0;
|
||||||
@@ -343,18 +375,25 @@ const APP = () => {
|
|||||||
async function animate(currentTime) {
|
async function animate(currentTime) {
|
||||||
if (!mapRef.current) return;
|
if (!mapRef.current) return;
|
||||||
|
|
||||||
|
// Apply any pending seek
|
||||||
|
if (seekRef.current !== null) {
|
||||||
|
currentProgress = seekRef.current;
|
||||||
|
lastFetchedDist = currentProgress;
|
||||||
|
lastTimestamp = currentTime;
|
||||||
|
seekRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
const deltaTime = currentTime - lastTimestamp;
|
const deltaTime = currentTime - lastTimestamp;
|
||||||
lastTimestamp = currentTime;
|
lastTimestamp = currentTime;
|
||||||
|
|
||||||
const baseKmPerMs = 0.1; // 100 km/s
|
const baseKmPerMs = 0.1;
|
||||||
const pathPoints = lineOfSightData.line_coordinates;
|
const pathPoints = lineOfSightDataRef.current.line_coordinates;
|
||||||
const pointIndex = Math.min(
|
const pointIndex = Math.min(
|
||||||
Math.floor((currentProgress / routeDistance) * pathPoints.length),
|
Math.floor((currentProgress / routeDistance) * pathPoints.length),
|
||||||
pathPoints.length - 1
|
pathPoints.length - 1
|
||||||
);
|
);
|
||||||
const isOverWater = pathPoints[pointIndex]?.is_over_water;
|
const isOverWater = pathPoints[pointIndex]?.is_over_water;
|
||||||
|
|
||||||
// Predictive land detection (look ahead 2000 km)
|
|
||||||
let futureIsOverWater = true;
|
let futureIsOverWater = true;
|
||||||
const lookAheadDistance = 2000;
|
const lookAheadDistance = 2000;
|
||||||
const lookAheadSteps = 10;
|
const lookAheadSteps = 10;
|
||||||
@@ -387,6 +426,8 @@ const APP = () => {
|
|||||||
if (phase >= 1) {
|
if (phase >= 1) {
|
||||||
setIsPlaying(false);
|
setIsPlaying(false);
|
||||||
setFlightSpeed(1.0);
|
setFlightSpeed(1.0);
|
||||||
|
setCurrentCityIndex(-1);
|
||||||
|
currentCityIndexRef.current = -1;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -396,6 +437,20 @@ const APP = () => {
|
|||||||
|
|
||||||
mapRef.current.jumpTo({ center: eye, zoom: 6, pitch: 65, bearing });
|
mapRef.current.jumpTo({ center: eye, zoom: 6, pitch: 65, bearing });
|
||||||
|
|
||||||
|
// Find nearest city to current position and update sidebar highlight
|
||||||
|
const cities = lineOfSightDataRef.current.conurbations;
|
||||||
|
let nearestIdx = -1;
|
||||||
|
let nearestDist = Infinity;
|
||||||
|
cities.forEach((city, idx) => {
|
||||||
|
const d = Math.abs(city.distance_km - currentProgress);
|
||||||
|
if (d < nearestDist) { nearestDist = d; nearestIdx = idx; }
|
||||||
|
});
|
||||||
|
if (nearestDist < 300 && nearestIdx !== currentCityIndexRef.current) {
|
||||||
|
currentCityIndexRef.current = nearestIdx;
|
||||||
|
setCurrentCityIndex(nearestIdx);
|
||||||
|
showCityPopup(cities[nearestIdx]);
|
||||||
|
}
|
||||||
|
|
||||||
if (currentProgress - lastFetchedDist > 2000) {
|
if (currentProgress - lastFetchedDist > 2000) {
|
||||||
lastFetchedDist = currentProgress;
|
lastFetchedDist = currentProgress;
|
||||||
try {
|
try {
|
||||||
@@ -422,15 +477,6 @@ const APP = () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const nearestCity = lineOfSightData.conurbations.find(city =>
|
|
||||||
Math.abs(city.distance_km - currentProgress) < 100
|
|
||||||
);
|
|
||||||
if (nearestCity && nearestCity.id !== lastNearestCityId) {
|
|
||||||
lastNearestCityId = nearestCity.id;
|
|
||||||
setSelectedCity(nearestCity);
|
|
||||||
showCityPopup(nearestCity);
|
|
||||||
}
|
|
||||||
|
|
||||||
animationRef.current = requestAnimationFrame(animate);
|
animationRef.current = requestAnimationFrame(animate);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -477,7 +523,7 @@ const APP = () => {
|
|||||||
|
|
||||||
map.addSource('line-of-sight', {
|
map.addSource('line-of-sight', {
|
||||||
type: 'geojson',
|
type: 'geojson',
|
||||||
data: buildLineGeoJSON(data.line_coordinates, projection)
|
data: buildLineGeoJSON(data.line_coordinates)
|
||||||
});
|
});
|
||||||
|
|
||||||
map.addLayer({
|
map.addLayer({
|
||||||
@@ -527,10 +573,9 @@ const APP = () => {
|
|||||||
path.push(calculateDestination(point.lat, point.lon, brng, dist));
|
path.push(calculateDestination(point.lat, point.lon, brng, dist));
|
||||||
}
|
}
|
||||||
|
|
||||||
map.getSource('preview-line').setData({
|
map.getSource('preview-line').setData(
|
||||||
type: 'Feature',
|
buildLineGeoJSON(path)
|
||||||
geometry: { type: 'LineString', coordinates: path.map(p => [p.lon, p.lat]) }
|
);
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const calculateDestination = (lat, lon, bearing, distance) => {
|
const calculateDestination = (lat, lon, bearing, distance) => {
|
||||||
@@ -578,6 +623,10 @@ const APP = () => {
|
|||||||
}]
|
}]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
if (style === 'map') {
|
||||||
|
return 'https://tiles.openfreemap.org/styles/liberty';
|
||||||
|
}
|
||||||
|
// 'basic' — clean MapLibre demo tiles, no labels
|
||||||
return 'https://demotiles.maplibre.org/style.json';
|
return 'https://demotiles.maplibre.org/style.json';
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -607,9 +656,7 @@ const APP = () => {
|
|||||||
const PROJECTIONS = [
|
const PROJECTIONS = [
|
||||||
{ id: 'globe', label: 'Globe' },
|
{ id: 'globe', label: 'Globe' },
|
||||||
{ id: 'mercator', label: 'Mercator' },
|
{ id: 'mercator', label: 'Mercator' },
|
||||||
{ id: 'equalEarth', label: 'Equal Earth' },
|
{ id: 'vertical-perspective', label: 'Perspective' }
|
||||||
{ id: 'naturalEarth', label: 'Natural Earth' },
|
|
||||||
{ id: 'winkelTripel', label: 'Winkel Tripel' }
|
|
||||||
];
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -653,8 +700,8 @@ const APP = () => {
|
|||||||
|
|
||||||
<div className="setting-row">
|
<div className="setting-row">
|
||||||
<label>Map Style:</label>
|
<label>Map Style:</label>
|
||||||
<button className={mapStyle === 'light' ? 'active-style' : ''} onClick={() => setMapStyle('light')}>Light</button>
|
<button className={mapStyle === 'basic' ? 'active-style' : ''} onClick={() => setMapStyle('basic')}>Basic</button>
|
||||||
<button className={mapStyle === 'dark' ? 'active-style' : ''} onClick={() => setMapStyle('dark')}>Dark</button>
|
<button className={mapStyle === 'map' ? 'active-style' : ''} onClick={() => setMapStyle('map')}>Map</button>
|
||||||
<button className={mapStyle === 'satellite' ? 'active-style' : ''} onClick={() => setMapStyle('satellite')}>Satellite</button>
|
<button className={mapStyle === 'satellite' ? 'active-style' : ''} onClick={() => setMapStyle('satellite')}>Satellite</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -695,34 +742,53 @@ const APP = () => {
|
|||||||
|
|
||||||
{lineOfSightData && (
|
{lineOfSightData && (
|
||||||
<div className="results-panel">
|
<div className="results-panel">
|
||||||
<h3>Conurbations Found ({lineOfSightData.conurbations.length})</h3>
|
<h3>Cities Along Route ({lineOfSightData.conurbations.length})</h3>
|
||||||
<p className="hint">Click a city for details</p>
|
{isPlaying && currentCityIndex >= 0 && (
|
||||||
|
<div className="now-passing">
|
||||||
|
Now passing: <strong>{lineOfSightData.conurbations[currentCityIndex]?.name}</strong>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<p className="hint">{isPlaying ? 'Click a city to jump to it' : 'Click a city for details'}</p>
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>#</th>
|
<th>#</th>
|
||||||
<th>City</th>
|
<th>City</th>
|
||||||
<th>Population</th>
|
<th>Pop.</th>
|
||||||
<th>Dist.</th>
|
<th>Dist.</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{lineOfSightData.conurbations.map((city, index) => (
|
{lineOfSightData.conurbations.map((city, index) => {
|
||||||
<tr
|
let rowClass = '';
|
||||||
key={city.id}
|
if (isPlaying && currentCityIndex >= 0) {
|
||||||
onClick={() => {
|
if (index === currentCityIndex) rowClass = 'current-row';
|
||||||
setSelectedCity(city);
|
else if (index < currentCityIndex) rowClass = 'passed-row';
|
||||||
showCityPopup(city);
|
else if (index <= currentCityIndex + 5) rowClass = 'upcoming-row';
|
||||||
mapRef.current.flyTo({ center: [city.lon, city.lat], zoom: 8 });
|
} else if (selectedCity?.id === city.id) {
|
||||||
}}
|
rowClass = 'selected-row';
|
||||||
className={selectedCity?.id === city.id ? 'selected-row' : ''}
|
}
|
||||||
>
|
return (
|
||||||
<td>{index + 1}</td>
|
<tr
|
||||||
<td>{city.name}</td>
|
id={`city-row-${index}`}
|
||||||
<td>{(city.population / 1000).toFixed(0)}k</td>
|
key={city.id}
|
||||||
<td>{city.distance_km}km</td>
|
onClick={() => {
|
||||||
</tr>
|
setSelectedCity(city);
|
||||||
))}
|
showCityPopup(city);
|
||||||
|
mapRef.current.flyTo({ center: [city.lon, city.lat], zoom: 8 });
|
||||||
|
if (isPlaying) {
|
||||||
|
seekRef.current = city.distance_km;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={rowClass}
|
||||||
|
>
|
||||||
|
<td>{index + 1}</td>
|
||||||
|
<td>{city.name}</td>
|
||||||
|
<td>{(city.population / 1000).toFixed(0)}k</td>
|
||||||
|
<td>{city.distance_km}km</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
|
||||||
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api';
|
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3051/api';
|
||||||
|
|
||||||
const api = axios.create({
|
const api = axios.create({
|
||||||
baseURL: API_BASE_URL,
|
baseURL: API_BASE_URL,
|
||||||
|
|||||||
@@ -446,13 +446,13 @@
|
|||||||
.app-container {
|
.app-container {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
.controls {
|
.controls {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
max-height: 40vh;
|
max-height: 40vh;
|
||||||
order: -1;
|
order: -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.map-container {
|
.map-container {
|
||||||
height: 60vh;
|
height: 60vh;
|
||||||
}
|
}
|
||||||
@@ -465,3 +465,26 @@
|
|||||||
top: auto;
|
top: auto;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.results-panel tr.passed-row {
|
||||||
|
opacity: 0.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.results-panel tr.current-row {
|
||||||
|
background: #1abc9c !important;
|
||||||
|
color: white;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.results-panel tr.upcoming-row {
|
||||||
|
background: #eaf4fb !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.now-passing {
|
||||||
|
background: #1abc9c;
|
||||||
|
color: white;
|
||||||
|
padding: 6px 10px;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 13px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user