|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace LaraGeoData\Models; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Builder; |
|
6
|
|
|
use Illuminate\Support\Facades\DB; |
|
7
|
|
|
|
|
8
|
|
|
trait HasCoordinates |
|
9
|
|
|
{ |
|
10
|
2 |
|
public function latitudeColName(): string |
|
11
|
|
|
{ |
|
12
|
2 |
|
return $this->latitudeColumnName ?? 'lat'; |
|
13
|
|
|
} |
|
14
|
|
|
|
|
15
|
2 |
|
public function longitudeColName(): string |
|
16
|
|
|
{ |
|
17
|
2 |
|
return $this->longitudeColumnName ?? 'lng'; |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
2 |
|
public function distanceColName(): string |
|
21
|
|
|
{ |
|
22
|
2 |
|
return $this->distanceColumnName ?? 'distance'; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Haversine formula (from Google solution example) |
|
27
|
|
|
* |
|
28
|
|
|
* @param Builder $query |
|
29
|
|
|
* @param float $lat |
|
30
|
|
|
* @param float $lng |
|
31
|
|
|
* @param float $radius |
|
32
|
|
|
* @param int $koef miles = 3959, kilometers = 6371 |
|
33
|
|
|
* @return Builder |
|
34
|
|
|
*/ |
|
35
|
2 |
|
public function scopeNearest(Builder $query, float $lat, float $lng, float $radius, int $koef = 6371) |
|
36
|
|
|
{ |
|
37
|
2 |
|
$latColName = $this->latitudeColName(); |
|
38
|
2 |
|
$lngColName = $this->longitudeColName(); |
|
39
|
2 |
|
$distanceFieldName = $this->distanceColName(); |
|
40
|
|
|
|
|
41
|
2 |
|
return $query->select([ |
|
42
|
2 |
|
'*', |
|
43
|
2 |
|
DB::raw(" |
|
44
|
2 |
|
( {$koef} * |
|
45
|
2 |
|
acos(cos(radians({$lat})) * |
|
46
|
2 |
|
cos(radians({$latColName})) * |
|
47
|
2 |
|
cos(radians({$lngColName}) - |
|
48
|
2 |
|
radians({$lng})) + |
|
49
|
2 |
|
sin(radians({$lat})) * |
|
50
|
2 |
|
sin(radians({$latColName}))) |
|
51
|
2 |
|
) AS {$distanceFieldName} "), |
|
52
|
2 |
|
])->having($distanceFieldName, '<=', $radius); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
2 |
|
public function scopeNearestInMiles(Builder $query, float $lat, float $lng, float $radius, int $koef = 3959) |
|
|
|
|
|
|
56
|
|
|
{ |
|
57
|
2 |
|
return $this->scopeNearest($query, $lat, $lng, $radius, 3959); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
2 |
|
public function scopeOrderByNearest(Builder $query, string $direction = 'asc') |
|
61
|
|
|
{ |
|
62
|
2 |
|
return $query->orderBy($this->distanceColName(), $direction); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
2 |
|
public function getDistanceAttribute(): float |
|
66
|
|
|
{ |
|
67
|
2 |
|
if (array_key_exists($this->distanceColName(), $this->attributes)) { |
|
68
|
2 |
|
return (float) $this->attributes[$this->distanceColName()]; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return 0; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.