Skip to main content
POST
/
route
Find Route
curl --request POST \
  --url http://localhost:8080/route \
  --header 'Content-Type: <content-type>' \
  --data '
{
  "from": {
    "lat": 123,
    "lng": 123
  },
  "to": {
    "lat": 123,
    "lng": 123
  }
}
'
{
  "route": [
    {
      "id": 123,
      "branch_id": 123,
      "name": "<string>",
      "latitude": 123,
      "longitude": 123
    }
  ]
}

Overview

The /route endpoint calculates the optimal path between two geographic coordinates using the available bus routes and walking connections. The algorithm considers walking distance, bus routes, and transfers to find the best route.

Endpoint

POST /route

Request

Send a JSON payload with origin and destination coordinates.

Headers

Content-Type
string
required
Must be application/json

Body Parameters

from
object
required
Origin coordinates
to
object
required
Destination coordinates

Request Example

{
  "from": {
    "lat": 40.7128,
    "lng": -74.0060
  },
  "to": {
    "lat": 40.7580,
    "lng": -73.9855
  }
}

Response

The endpoint returns an array of stops representing the optimal route from origin to destination.
route
array
required
Array of stop objects representing the path to take

Success Response Example

[
  {
    "id": 15,
    "branch_id": 2,
    "name": "Washington Square",
    "latitude": 40.7308,
    "longitude": -73.9973
  },
  {
    "id": 16,
    "branch_id": 2,
    "name": "Union Square",
    "latitude": 40.7359,
    "longitude": -73.9911
  },
  {
    "id": 23,
    "branch_id": 3,
    "name": "Grand Central",
    "latitude": 40.7527,
    "longitude": -73.9772
  }
]

Error Responses

If no route can be found or an error occurs:
{
  "error": "No hay rutas disponibles"
}
Common error messages:
Error MessageMeaning
"No existen paradas para empezar"No bus stops within walking distance of origin
"No hay rutas disponibles"No valid route found between the coordinates
"Error message from service"External service error

Code Examples

curl -X POST http://localhost:8080/route \
  -H "Content-Type: application/json" \
  -d '{
    "from": {
      "lat": 40.7128,
      "lng": -74.0060
    },
    "to": {
      "lat": 40.7580,
      "lng": -73.9855
    }
  }'

Implementation Details

The endpoint implementation (src/server/server.js:27-38):
app.post("/route", (req, resp) => {
    const routeData = req.body
    ServerMockup()
        .then(busStopsData => {
            const route = findLogic.findRoute(busStopsData, routeData)
            resp.json(route)
        })
        .catch((err) => {
            console.error(err)
            resp.json({ error: err.message })
        })
})

Route Calculation Algorithm

The route finding algorithm (src/server/FindLogic.js:42) uses several sophisticated techniques:
  1. Distance Calculation: Uses Haversine formula for accurate geographic distance
  2. Walking Radius: Finds stops within 0.8 km walking distance
  3. Route Expansion: Explores possible paths through the bus network
  4. Optimization: Selects the path that gets closest to the destination
  5. Validation: Ensures no stop is visited twice in the same route

Algorithm Parameters

These parameters control the route calculation (defined in src/server/FindLogic.js:34-38):
ParameterValueDescription
walkKmh1 km/hWalking speed for time calculations
busKmh60 km/hAverage bus travel speed
busWaitH0.5 hoursExpected wait time at stops
maxWalkKm0.8 kmMaximum walking distance to/from stops
The algorithm will only consider stops within 0.8 km of your origin and destination. If no stops are within this range, the request will fail.

Data Flow

  1. Client sends POST request with from and to coordinates
  2. Server fetches all bus stop data via ServerMockup()
  3. findLogic.findRoute() calculates optimal path:
    • Finds stops near origin (within 0.8 km)
    • Finds stops near destination (within 0.8 km)
    • Explores possible routes using breadth-first search
    • Returns stops array for the best route
  4. Server returns the route array as JSON
  5. On error, returns error object

Error Handling

Always implement proper error handling:
async function calculateRoute(from, to) {
  const response = await fetch('http://localhost:8080/route', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ from, to })
  });
  
  const result = await response.json();
  
  if (result.error) {
    // Handle different error types
    if (result.error.includes('paradas para empezar')) {
      return {
        success: false,
        message: 'No bus stops found near your location. Try a different starting point.'
      };
    } else if (result.error.includes('No hay rutas')) {
      return {
        success: false,
        message: 'No route available between these locations. Try different points.'
      };
    } else {
      return {
        success: false,
        message: 'Unable to calculate route. Please try again.'
      };
    }
  }
  
  return {
    success: true,
    route: result
  };
}

Use Cases

Display Route on Map

async function showRouteOnMap(fromCoords, toCoords) {
  const response = await fetch('http://localhost:8080/route', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ from: fromCoords, to: toCoords })
  });
  
  const route = await response.json();
  
  if (!route.error) {
    // Draw route line on map
    const coordinates = route.map(stop => [stop.latitude, stop.longitude]);
    drawPolyline(coordinates);
    
    // Add markers for each stop
    route.forEach((stop, index) => {
      addMarker({
        lat: stop.latitude,
        lng: stop.longitude,
        title: `${index + 1}. ${stop.name}`,
        icon: 'bus-stop'
      });
    });
  }
}

Calculate Route Statistics

function analyzeRoute(route) {
  // Count unique bus routes used
  const uniqueRoutes = new Set(route.map(stop => stop.branch_id));
  const transfers = uniqueRoutes.size - 1;
  
  // Calculate total distance
  let totalDistance = 0;
  for (let i = 0; i < route.length - 1; i++) {
    totalDistance += calculateDistance(
      route[i].latitude, route[i].longitude,
      route[i + 1].latitude, route[i + 1].longitude
    );
  }
  
  return {
    stops: route.length,
    transfers: transfers,
    distance: totalDistance.toFixed(2) + ' km',
    routes: Array.from(uniqueRoutes)
  };
}

Interactive Route Planning

// React component example
function RoutePlanner() {
  const [route, setRoute] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  const findRoute = async (from, to) => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await fetch('http://localhost:8080/route', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ from, to })
      });
      
      const data = await response.json();
      
      if (data.error) {
        setError(data.error);
      } else {
        setRoute(data);
      }
    } catch (err) {
      setError('Network error. Please try again.');
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div>
      {loading && <Spinner />}
      {error && <ErrorMessage>{error}</ErrorMessage>}
      {route && <RouteDisplay stops={route} />}
    </div>
  );
}

Performance Considerations

  • The algorithm explores up to 10,000 possible routes
  • Maximum of 50 iterations to prevent infinite loops
  • Routes are sorted by distance to destination for efficiency
  • Duplicate routes are filtered to optimize memory usage
For very complex route networks, calculation may take several seconds. Consider implementing a loading indicator in your UI.

Get All Routes

Retrieve bus stop data needed for mapping

API Overview

View complete API documentation

Build docs developers (and LLMs) love