belongsTo(InspectionStaff::class, 'staff_id', 'id'); } public function points() { return $this->hasMany(InspectionRecordPoint::class, 'record_id', 'id')->order('create_at', 'asc'); } public function calculateDistance() { $points = $this->points()->select(); $distance = 0; $previousPoint = null; foreach ($points as $point) { $lat = $point->latitude; $lng = $point->longitude; if ($previousPoint) { $distance += $this->calculateDistanceBetweenPoints($previousPoint[0], $previousPoint[1], $lat, $lng); } $previousPoint = [$lat, $lng]; } return $distance; } private function calculateDistanceBetweenPoints($lat1, $lng1, $lat, $lng) { $earthRadius = 6371000; // 地球半径,单位为米 $dLat = deg2rad($lat - $lat1); $dLng = deg2rad($lng - $lng1); $a = sin($dLat / 2) * sin($dLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat)) * sin($dLng / 2) * sin($dLng / 2); $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); $distance = $earthRadius * $c; return $distance; } }