const express = require('express'); const bodyParser = require('body-parser'); require('dotenv').config(); const path = require('path'); const polyline = require('@mapbox/polyline'); // ייבוא הספרייה לפענוח const GH_KEY = process.env.GRAPHHOPPER_API_KEY; if (!GH_KEY) { console.error('Please set GRAPHHOPPER_API_KEY in .env'); process.exit(1); } const ORS_KEY = process.env.OPENROUTESERVICE_API_KEY if (!ORS_KEY) { console.error("Please set OPENROUTESERVICE_API_KEY in .env") process.exit(1) } const file = //'example.json'// 'generated-file-july-14-2025-3_06am.json' const fs = require('fs'); const forbiddenGeojson = JSON.parse(fs.readFileSync(path.join(__dirname, file), 'utf8')); const forbiddenPolygons = forbiddenGeojson.features.filter(f => f.geometry && f.geometry.type === 'Polygon'); const app = express(); app.use(bodyParser.json()); const forbiddenZonesRouter = require('./forbidden-zones'); const { type } = require('os'); app.use('/api', forbiddenZonesRouter); const clientPath = path.join(__dirname, '../client'); app.use(express.static(clientPath)); app.get('/', (req, res) => { res.sendFile(path.join(clientPath, 'index.html')); }); app.post('/route', async (req, res) => { const { points } = req.body; if (!Array.isArray(points) || points.length < 2) { return res.status(400).json({ error: 'points must be an array of at least two [lat,lon] pairs' }); } const exclusionZones = forbiddenPolygons; const avoid_polygons = { type: "MultiPolygon", coordinates: exclusionZones.map((poly) => poly.geometry.coordinates) } const orsPayloadBase = { coordinates: points, format: "geojson", instructions: true, geometry: true, } const orsPayloadWithAvoid = { ...orsPayloadBase, options:{ avoid_polygons: avoid_polygons } } try { const orsResWithAvoid = await fetch(`https://api.openrouteservice.org/v2/directions/driving-car`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: ORS_KEY, }, body: JSON.stringify(orsPayloadWithAvoid), }) const orsDataWithAvoid = await orsResWithAvoid.json() //קריאה שניה ללא אזורים חסומים const orsResWithoutAvoid = await fetch(`https://api.openrouteservice.org/v2/directions/driving-car`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: ORS_KEY, }, body: JSON.stringify(orsPayloadBase), }) const orsDataWithoutAvoid = await orsResWithoutAvoid.json() // פענוח ל-[lat, lon] const decodedWithAvoid = polyline.decode(orsDataWithAvoid.routes[0].geometry); const decodedWithoutAvoid = polyline.decode(orsDataWithoutAvoid.routes[0].geometry); res.json({ withAvoid: decodedWithAvoid, withoutAvoid: decodedWithoutAvoid, }) } catch (err) { console.error(err); res.status(500).json({ error: 'GraphHopper request failed' }); } }); const PORT = process.env.PORT || 4000; app.listen(PORT, () => console.log(`Server listening on http://localhost:${PORT}`));