File: /var/www/tracksgrid.com/app/Track.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Track extends Model
{
protected $fillable = [
'user_id',
'event_id',
'trackname',
'private',
'uuid',
'active',
];
public function locations() {
return $this->hasMany(Location::class)->where('accuracy', '<', 50)->orderBy('timestamp');
}
public function user() {
return $this->belongsTo(User::class);
}
public function users() {
return $this->hasMany(User::class);
}
public function event() {
return $this->belongsTo(Event::class);
}
public function getLastDataAttribute()
{
$lastData = ((int)$this->locations->max('timestamp') / 1000);
return date('d.m.Y H:i', $lastData);
}
public function getDurationAttribute()
{
$duration = ($this->locations->max('timestamp') / 1000) - ($this->locations->min('timestamp') / 1000);
return $duration;
}
public function getLengthAttribute()
{
$length = $this->calculate_distance($this->locations) / 1000;
return $length;
}
public function getPaceAttribute()
{
if ($this->length) {
return floor((($this->locations->max('timestamp') / 1000) - ($this->locations->min('timestamp') / 1000)) / $this->length);
}
}
protected $casts = [
'created_at' => 'datetime:d.m.Y H:i'
];
function calculate_distance($locations)
{
$oldlon = $oldocc = '';
$oldlat = false;
$distance = 0;
foreach ($locations as $row) {
if ($oldlat) {
$delta_distance = $this->distance($oldlat, $oldlon, $row['lat'], $row['lon']);
$distance += $delta_distance;
}
$oldlat = $row['lat'];
$oldlon = $row['lon'];
$oldocc = $row['created_at'];
}
return $distance;
}
function distance($lat1, $lon1, $lat2, $lon2)
{
$radius = 6371000; // meter
list($lat1, $lon1, $lat2, $lon2) = array_map('deg2rad', array($lat1, $lon1, $lat2, $lon2));
$dlat = $lat2 - $lat1;
$dlon = $lon2 - $lon1;
$a = pow(sin($dlat / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($dlon / 2), 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$d = $radius * $c;
return (int) $d;
}
}