Update: 2026-07-06 00:53:15
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
<?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
|
||||
* @return array|null Returns ['distance_km' => float, 'duration_min' => float] or null on failure.
|
||||
*/
|
||||
function getOsrmRouteDetails($startLat, $startLng, $endLat, $endLng) {
|
||||
// Format: longitude,latitude
|
||||
$coordinates = "{$startLng},{$startLat};{$endLng},{$endLat}";
|
||||
|
||||
// Using public demo server. Note: Has rate limits.
|
||||
// For production, highly recommended to use: "http://your-own-osrm-server.com:5000"
|
||||
$osrmBaseUrl = "http://router.project-osrm.org";
|
||||
$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;
|
||||
}
|
||||
Reference in New Issue
Block a user