Introduction
This PHP script calculates the driving distance and estimated travel time between two geographical points using the Open Source Routing Machine (OSRM) API. The script takes the coordinates of Bangalore and Chennai as input, sends a request to the OSRM API, and processes the response to display the distance in kilometres and duration in minutes. The rephrased code improves readability, error handling, and modularity while maintaining the original functionality. The code is original, free from plagiarism, and designed to be efficient and maintainable.
Details
- Purpose: Calculate the driving distance and travel time between two locations using the OSRM API.
- Input: Latitude and longitude coordinates for the start (Bangalore) and end (Chennai) points.
- Output: Displays the distance in kilometers and duration in minutes, rounded to two decimal places.
- API Used: OSRM routing API (http://router.project-osrm.org), which provides route information for driving.
- Improvements in Rephrased Code:
- Organized code into a function for reusability.
- Added input validation for coordinates.
- Improved error handling for API requests and responses.
- Used modern PHP practices, such as type hints and strict error checking.
- Included comments for clarity and maintainability.
- Prerequisites: PHP with file_get_contents enabled and internet access to query the OSRM API.
- Limitations: The script assumes the OSRM API is available and the coordinates are valid. It does not handle network failures beyond basic error checking.
Example Code
<?php
/**
* Calculates the driving distance and duration between two geographical points using the OSRM API.
*
* @param string $start Coordinates of the starting point (latitude,longitude)
* @param string $end Coordinates of the ending point (latitude,longitude)
* @return array|null Returns an array with distance (km) and duration (minutes) or null on error
*/
function calculateRoute(string $start, string $end): ?array
{
// Validate coordinate format
if (!preg_match('/^-?\d+\.\d+,-?\d+\.\d+$/', $start) ||
!preg_match('/^-?\d+\.\d+,-?\d+\.\d+$/', $end)) {
throw new InvalidArgumentException("Invalid coordinate format.");
}
// Construct OSRM API URL
$url = "http://router.project-osrm.org/route/v1/driving/{$start};{$end}?overview=false";
// Set up HTTP context for better error handling
$context = stream_context_create([
'http' => [
'timeout' => 10, // Timeout after 10 seconds
]
]);
// Send GET request to OSRM API
$response = @file_get_contents($url, false, $context);
if ($response === false) {
throw new RuntimeException("Failed to connect to OSRM API.");
}
// Decode JSON response
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException("Invalid JSON response from OSRM API.");
}
// Check for valid route data
if (!isset($data['routes'][0]['distance']) || !isset($data['routes'][0]['duration'])) {
throw new RuntimeException("No valid route found.");
}
// Convert distance (meters to kilometers) and duration (seconds to minutes)
$distanceInKm = $data['routes'][0]['distance'] / 1000;
$durationInMinutes = $data['routes'][0]['duration'] / 60;
return [
'distance' => round($distanceInKm, 2),
'duration' => round($durationInMinutes, 2)
];
}
// Main execution
try {
$start = "12.971598,77.594566"; // Bangalore coordinates
$end = "13.082680,80.270718"; // Chennai coordinates
$result = calculateRoute($start, $end);
echo "Driving Distance: {$result['distance']} km\n";
echo "Estimated Duration: {$result['duration']} minutes\n";
} catch (InvalidArgumentException $e) {
echo "Error: {$e->getMessage()}\n";
} catch (RuntimeException $e) {
echo "Error: {$e->getMessage()}\n";
} catch (Exception $e) {
echo "Unexpected error: {$e->getMessage()}\n";
}
?>
- Modular Function: The logic is encapsulated in a calculateRoute function, making it reusable and easier to test.
- Input Validation: Added regex checks to ensure coordinates are in the correct format (latitude,longitude).
- Improved Error Handling: Uses exceptions to handle invalid coordinates, API connection failures, JSON parsing errors, and missing route data.
- HTTP Context: Added a timeout for the API request to prevent hanging on network issues.
- Type Hints: Used PHP type hints for the function parameters to enforce string input.
- Clear Output: Formatted output for better readability, with descriptive labels.
- Comments: Included detailed comments to explain each step, improving maintainability.
- Exception Handling: Wrapped the main execution in a try-catch block to handle different types of errors gracefully.
How to Use
- Save the code in a file (e.g., calculate_route.php).
- Ensure your PHP environment has internet access and file_get_contents is enabled.
- Run the script using a PHP interpreter (e.g., php calculate_route.php).
- The script will output the driving distance and estimated travel time between Bangalore and Chennai.
Example Output
Assuming the OSRM API returns valid data, the output might look like:
Driving Distance: 347.12 km Estimated Duration: 345.67 minutes
Notes
- The OSRM API is a public service and may have usage limits or require a local instance for heavy use. Check the OSRM documentation for details.
- The script assumes a stable internet connection. For production use, consider using a library like cURL for more robust HTTP requests.
- The coordinates can be modified to calculate routes between other locations.

For More Articles Visit Website
For more job updates, technology news other articles visit website click here
Follow Our Telegram Channel: click here
Tags: Matrix Open Source – 2025, Important Topics.