I have JSON
with the vehicle and route data:
$json = '[{
"carro": {
"nome": "Caravan",
"co_anterior": {
"LA": "-3.0131",
"LO": "-59.999",
"timestamp": "2018-05-07 10:30"
},
"co_atual": {
"LA": "-3.0231",
"LO": "-60.1977",
"timestamp": "2018-05-07 11:00"
}
},
"rota": {
"O Senhor dos Pastéis": {
"LA": "-3.2859",
"LO": "-60.1872"
},
"Churrassic Park": {
"LA": "-3.1433",
"LO": "-59.9895"
},
"Wesley Salgadão": {
"LA": "-3.3105",
"LO": "-60.6198"
}
}
}]';
I create an object passing this JSON
, where I do all the necessary calculations (distance traveled, average speed, distance of next stops, estimated time, etc.).
In the class, I have a function that calculates the distance between two points by Latitude and Longitude :
//https://www.geodatasource.com/developers/php
private function distancia($lat1, $lon1, $lat2, $lon2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
The return of the routes, with the distance and estimated hours according to the position and average speed of the car, are correct:
Rotas: Array
(
[Churrassic Park] => Array
(
[distancia] => 26.702
[horas] => 0.604
)
[O Senhor dos Pastéis] => Array
(
[distancia] => 29.244
[horas] => 0.662
)
[Wesley Salgadão] => Array
(
[distancia] => 56.72
[horas] => 1.284
)
)
The problem is:
When the car has already passed the first stop, or the next onwards, as the distance will always be positive, it will continue to calculate, but the distance and time will only increase, since it has already passed the point.
I would like some ideas of how they would do to determine that the point has already passed, and then do not calculate anymore, or get negative (but the car will return, so the route will serve the return too).
A possible solution would be to calculate whether the point was nearer or farther, so you know which one is "falling behind".