forked from versx/RealDeviceMap-opole
-
Notifications
You must be signed in to change notification settings - Fork 0
/
geofence_service.php
86 lines (71 loc) · 1.95 KB
/
geofence_service.php
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
<?php
use Location\Coordinate;
use Location\Polygon;
class Geofence {
public $name;
public $polygon;
}
class GeofenceService {
public $geofences = [];
private $dir = "./geofences/";
function __construct() {
$this->create_directory();
$this->load_geofences();
}
function load_geofences() {
$files = scandir($this->dir);
for ($i = 0; $i < count($files); $i++) {
if ($files[$i] === '.' || $files[$i] === '..')
continue;
$geofence = $this->load_geofence($this->dir . $files[$i]);
if ($geofence != null) {
array_push($this->geofences, $geofence);
}
}
return $this->geofences;
}
function load_geofence($file) {
$lines = file($file);
$name = "Unknown";
if (count($lines) !== 0 && strpos($lines[0], '[') === 0) {
$name = str_replace('[', "", $lines[0]);
$name = str_replace(']', "", $name);
}
$geofence = new Geofence();
$geofence->name = $name;
$geofence->polygon = $this->build_polygon(array_slice($lines, 1));
return $geofence;
}
function build_polygon($lines) {
$polygon = new Polygon();
$count = count($lines);
for ($i = 0; $i < $count; $i++) {
$line = $lines[$i];
if (strpos($line, '[') === 0)
continue;
$parts = explode(',', $line);
$lat = $parts[0];
$lon = $parts[1];
$polygon->addPoint(new Coordinate((float)$lat,(float)$lon));
}
return $polygon;
}
public function get_geofence($lat, $lon) {
for ($i = 0; $i < count($this->geofences); $i++) {
if ($this->is_in_polygon($this->geofences[$i], (float)$lat, (float)$lon)) {
return $this->geofences[$i];
}
}
return null;
}
function is_in_polygon($geofence, $lat_x, $lon_y) {
$point = new Coordinate($lat_x, $lon_y);
return $geofence->polygon->contains($point);
}
function create_directory() {
if (!file_exists($this->dir)) {
mkdir($this->dir, 0777, true);
}
}
}
?>