Files
Siro/backend/core/osrm_routing.php
T

67 lines
2.4 KiB
PHP

<?php
// ============================================================
// osrm_routing.php
// Helper functions for OpenStreetMap Routing Machine (OSRM)
// Used to estimate accurate distance (km) and duration (mins)
// ============================================================
/**
* Get Distance and Duration between two coordinates using public OSRM server.
* Note: If you host your own OSRM, replace the $osrmBaseUrl.
*
* @param float $startLat
* @param float $startLng
* @param float $endLat
* @param float $endLng
* @param string $countryCode (e.g. 'JO', 'SY', 'EG')
* @return array|null Returns ['distance_km' => float, 'duration_min' => float] or null on failure.
*/
function getOsrmRouteDetails($startLat, $startLng, $endLat, $endLng, $countryCode = 'JO') {
// Format: longitude,latitude
$coordinates = "{$startLng},{$startLat};{$endLng},{$endLat}";
// Select Intaleq/Siro OSRM server based on country
switch (strtoupper($countryCode)) {
case 'SY':
$osrmBaseUrl = "https://routes-syria.siromove.com";
break;
case 'EG':
$osrmBaseUrl = "https://routes-egypt.siromove.com";
break;
case 'JO':
default:
$osrmBaseUrl = "https://routesjo.intaleq.xyz";
break;
}
$url = "{$osrmBaseUrl}/route/v1/driving/{$coordinates}?overview=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 5 seconds timeout
// Add a User-Agent to avoid being blocked by the public demo server
curl_setopt($ch, CURLOPT_USERAGENT, "SiroRideHailingApp/1.0");
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && $response) {
$data = json_decode($response, true);
if (isset($data['code']) && $data['code'] === 'Ok' && isset($data['routes'][0])) {
$route = $data['routes'][0];
$distanceMeters = isset($route['distance']) ? (float)$route['distance'] : 0;
$durationSeconds = isset($route['duration']) ? (float)$route['duration'] : 0;
return [
'distance_km' => round($distanceMeters / 1000, 2),
'duration_min' => round($durationSeconds / 60, 2)
];
}
}
return null;
}