forked from getkirby/geo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
executable file
·100 lines (84 loc) · 3.16 KB
/
index.php
File metadata and controls
executable file
·100 lines (84 loc) · 3.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
/**
* Autoloader for all Kirby GEO Classes
*/
load([
'kirby\\geo\\geo' => __DIR__ . '/lib/geo.php',
'kirby\\geo\\point' => __DIR__ . '/lib/point.php'
]);
/**
* Creates a class alias for the GEO class, to make it more usable
*/
class_alias('Kirby\\Geo\\Geo', 'Geo');
/**
* Plugin Definition
*/
Kirby::plugin('getkirby/geo', [
'collectionFilters' => [
/**
* Adds a new radius filter to all collections
*/
'radius' => function ($collection, $field, $options) {
$origin = Geo::point($options['lat'] ?? null, $options['lng'] ?? null);
$radius = (int)($options['radius'] ?? null);
$unit = $options['unit'] ?? 'km' === 'km' ? 'km' : 'mi';
if (!$origin) {
throw new Exception('Invalid geo point for radius filter. You must specify valid lat and lng values');
}
if ($radius === 0) {
throw new Exception('Invalid radius value for radius filter. You must specify a valid integer value');
}
foreach ($collection->data as $key => $item) {
$value = $collection->getAttribute($item, $field);
// skip invalid points
if (!is_string($value) && !is_a($value, 'Kirby\\Cms\\Field')) {
unset($collection->$key);
continue;
}
try {
$point = Geo::point((string)$value);
} catch (Exception $e) {
unset($collection->$key);
continue;
}
$distance = Geo::distance($origin, $point, $unit);
if ($distance > $radius) {
unset($collection->$key);
}
}
return $collection;
}
],
'fieldMethods' => [
/**
* Adds a new field method "coordinates",
* which can be used to convert a field with
* comma separated lat and long values to a Kirby Geo Point
*/
'coordinates' => function ($field) {
return Geo::point($field->value());
},
/**
* Adds a new field method "distance",
* which can be used to calculate the distance between a
* field with comma separated lat and long values and a
* valid Kirby Geo Point
*/
'distance' => function ($field, $point, $unit = 'km') {
if (is_a($point, 'Kirby\\Geo\\Point') === false) {
throw new Exception('You must pass a valid Geo Point object to measure the distance');
}
return Geo::distance($field->coordinates(), $point, $unit);
},
/**
* Same as distance, but will return a human readable version
* of the distance instead of a long float
*/
'niceDistance' => function ($field, $point, $unit = 'km') {
if (is_a($point, 'Kirby\\Geo\\Point') === false) {
throw new Exception('You must pass a valid Geo Point object to measure the distance');
}
return Geo::niceDistance($field->coordinates(), $point, $unit);
},
],
]);