Skip to content

Instantly share code, notes, and snippets.

@cwhite92
Created July 13, 2016 08:23
Show Gist options
  • Save cwhite92/0d80eb8dc25a837bcb01ef09d651677f to your computer and use it in GitHub Desktop.
Save cwhite92/0d80eb8dc25a837bcb01ef09d651677f to your computer and use it in GitHub Desktop.
Service class
<?php
namespace App\Polylines;
class PathCleaner
{
/**
* Cleans up the polyline's path by trying to remove any incorrect path points.
*
* @param $path
* @param int $maxDistance
* @return array
*/
public function clean($path, $maxDistance = 150)
{
$newPath = [];
foreach ($path as $index => $point) {
// First point in the original path always gets used.
if ($index === 0) {
$newPath[] = $point;
continue;
}
// Calculate the distance between this point and the last.
$previous = $path[$index - 1];
$distance = $this->haversineGreatCircleDistance($previous[0], $previous[1], $point[0], $point[1]);
// If the distance is above the threshold, we'll make this the end of the path. Otherwise keep going.
if ($distance > $maxDistance) {
break;
}
$newPath[] = $point;
}
return $newPath;
}
/**
* Calculates the Haversine distance between to lat/lng pairs.
*
* @param $latitudeFrom
* @param $longitudeFrom
* @param $latitudeTo
* @param $longitudeTo
* @param int $earthRadius
* @return int
*/
protected function haversineGreatCircleDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000) {
$latFrom = deg2rad($latitudeFrom);
$lonFrom = deg2rad($longitudeFrom);
$latTo = deg2rad($latitudeTo);
$lonTo = deg2rad($longitudeTo);
$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom;
$angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
return $angle * $earthRadius;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment