Skip to content

Commit

Permalink
fixed #5, numeric value out of range with Postgres 12
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexsander Küchler committed Apr 20, 2021
1 parent f52ab6a commit 07b76c5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
4 changes: 2 additions & 2 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<env name="DB_HOST" value="localhost"/>
<env name="DB_PORT" value="5432"/>
<env name="DB_DATABASE" value="geoly_testing"/>
<env name="DB_USERNAME" value="alex"/>
<env name="DB_PASSWORD" value=""/>
<env name="DB_USERNAME" value="postgres"/>
<env name="DB_PASSWORD" value="postgres"/>
</php>
</phpunit>
6 changes: 3 additions & 3 deletions src/Geoly.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,20 @@ public function scopeRadius($query, $latitude, $longitude, $radius)
$query->select('*');

$query
->addSelect(DB::raw('acos(sin('.$lat.')*sin(radians('.$latName.')) + cos('.$lat.')*cos(radians('.$latName.'))*cos(radians('.$lonName.')'.($lng < 0 ? '+'.abs($lng) : '-'.$lng).')) * '.$r.' As distance'))
->addSelect(DB::raw('acos(least(greatest(sin('.$lat.')*sin(radians('.$latName.')) + cos('.$lat.')*cos(radians('.$latName.'))*cos(radians('.$lonName.')'.($lng < 0 ? '+'.abs($lng) : '-'.$lng).'), -1), 1)) * '.$r.' As distance'))
->fromSub(function ($query) use ($maxLat, $minLat, $maxLon, $minLon, $latName, $lonName) {
$query->from($this->getTable())
->whereBetween($latName, [$minLat, $maxLat])
->whereBetween($lonName, [$minLon, $maxLon]);
}, $this->getTable());
if ($lng < 0) {
$query->whereRaw(
'acos(sin(?)*sin(radians('.$latName.')) + cos(?)*cos(radians('.$latName.'))*cos(radians('.$lonName.')+?)) * ? < ?',
'acos(least(greatest(sin(?)*sin(radians('.$latName.')) + cos(?)*cos(radians('.$latName.'))*cos(radians('.$lonName.')+?), -1), 1)) * ? < ?',
[$lat, $lat, abs($lng), $r, $radius]
);
} else {
$query->whereRaw(
'acos(sin(?)*sin(radians('.$latName.')) + cos(?)*cos(radians('.$latName.'))*cos(radians('.$lonName.')-?)) * ? < ?',
'acos(least(greatest(sin(?)*sin(radians('.$latName.')) + cos(?)*cos(radians('.$latName.'))*cos(radians('.$lonName.')-?), -1), 1)) * ? < ?',
[$lat, $lat, $lng, $r, $radius]
);
}
Expand Down
13 changes: 13 additions & 0 deletions tests/Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,17 @@ public function it_calculates_distance_correctly_with_lat_negative_and_lng_negat
$houses = House::radius(-8.6, -8.6, 2)->get();
$this->assertCount(1, $houses);
}

/** @test */
public function it_handles_rounding_errors_correctly_in_acos_calculations()
{
House::create([
'name' => 'Test House',
'latitude' => 59.5598793,
'longitude' => 30.1385594,
]);

$houses = House::radius(59.5598793, 30.1385594, 2)->get();
$this->assertCount(1, $houses);
}
}

0 comments on commit 07b76c5

Please sign in to comment.