Clusterer::createMatrix()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 0
1
<?php
2
namespace MatthiasMullie\Geo;
3
4
/**
5
 * Please report bugs on https://github.com/matthiasmullie/geo/issues
6
 *
7
 * @author Matthias Mullie <[email protected]>
8
 *
9
 * @copyright Copyright (c) 2013, Matthias Mullie. All rights reserved.
10
 * @license MIT License
11
 */
12
class Clusterer
13
{
14
    /**
15
     * @var Bounds
16
     */
17
    protected $bounds;
18
19
    /**
20
     * Amount of coordinates in one cell needed to start clustering.
21
     *
22
     * @var int
23
     */
24
    protected $minLocations = 1;
25
26
    /**
27
     * @var int
28
     */
29
    protected $numberOfClusters = 50;
30
31
    /**
32
     * @var Cluster[][]
33
     */
34
    protected $clusters = array();
35
36
    /**
37
     * @var Coordinate[][][]
38
     */
39
    protected $coordinates = array();
40
41
    /**
42
     * @var int
43
     */
44
    protected $coefficientLat = 0;
45
46
    /**
47
     * @var int
48
     */
49
    protected $coefficientLng = 0;
50
51
    /**
52
     * @var bool
53
     */
54
    protected $spanBoundsLat = false;
55
56
    /**
57
     * @var bool
58
     */
59
    protected $spanBoundsLng = false;
60
61
    /**
62
     * @var bool
63
     */
64
    protected $saveCoordinates = false;
65
66
    /**
67
     * @param Bounds $bounds
68
     */
69
    public function __construct(Bounds $bounds)
70
    {
71
        // determine if bounds span 360 to -360 degrees gap
72
        $this->spanBoundsLng = $bounds->ne->longitude < $bounds->sw->longitude;
73
        $this->spanBoundsLat = $bounds->ne->latitude < $bounds->sw->latitude;
74
75
        $this->bounds = $this->fixBounds($bounds);
76
        $this->createMatrix();
77
    }
78
79
    /**
80
     * Enables coordinate saving in clusters.
81
     *
82
     * Note that while it allows you to retrieve all Coordinate objects
83
     * in a cluster, this does not scale. At some point, if you keep
84
     * adding coordinates into clusters, you'll run out of memory
85
     * because we're saving all those coordinates.
86
     * If you don't need the exact information of coordinates in a
87
     * cluster, leave this disabled.
88
     *
89
     * @param  bool      $save
90
     * @throws Exception
91
     */
92
    public function setSaveCoordinates($save)
93
    {
94
        if (count($this->clusters) || count($this->coordinates)) {
95
            throw new Exception('Sorry, it is not possible to change coordinate saving policy after you have already added coordinates.');
96
        }
97
98
        $this->saveCoordinates = $save;
99
    }
100
101
    /**
102
     * Set the minimum amount of locations before clustering.
103
     *
104
     * @param int $limit
105
     */
106
    public function setMinClusterLocations($limit)
107
    {
108
        $this->minLocations = $limit;
109
    }
110
111
    /**
112
     * Set an approximate amount of clusters.
113
     * Approximate in that it also depends on the viewport:
114
     * less square = less clusters.
115
     *
116
     * @param int $number
117
     */
118
    public function setNumberOfClusters($number)
119
    {
120
        $this->numberOfClusters = $number;
121
    }
122
123
    /**
124
     * @param Coordinate $coordinate
125
     */
126
    public function addCoordinate(Coordinate $coordinate)
127
    {
128
        list($latIndex, $lngIndex) = $this->findCell($coordinate);
129
        $coordinateCount = isset($this->coordinates[$latIndex][$lngIndex]) ? count($this->coordinates[$latIndex][$lngIndex]) : 0;
130
131
        // cluster already exists, add coordinate to it
132
        if (isset($this->clusters[$latIndex][$lngIndex])) {
133
            $this->clusters[$latIndex][$lngIndex]->addCoordinate($coordinate, $this->saveCoordinates);
134
135
        // there's no cluster yet, but entry limit reached = cluster now
136
        } elseif ($coordinateCount >= $this->minLocations - 1) {
137
            // initialise cluster with given coordinate
138
            $this->clusters[$latIndex][$lngIndex] = new Cluster();
139
            $this->clusters[$latIndex][$lngIndex]->addCoordinate($coordinate, $this->saveCoordinates);
140
141
            if ($coordinateCount) {
142
                // add existing coordinates
143
                foreach ($this->coordinates[$latIndex][$lngIndex] as $coordinate) {
144
                    $this->clusters[$latIndex][$lngIndex]->addCoordinate($coordinate, $this->saveCoordinates);
145
                }
146
147
                // save cluster & clear array of individual coordinates (to free up
148
                // memory, in case we're dealing with lots of coordinates)
149
                unset($this->coordinates[$latIndex][$lngIndex]);
150
            }
151
152
        // entry limit for clustering not yet reached, save coordinate
153
        } else {
154
            $this->coordinates[$latIndex][$lngIndex][] = $coordinate;
155
        }
156
    }
157
158
    /**
159
     * @return Coordinate[]
160
     */
161
    public function getCoordinates()
162
    {
163
        // flatten matrix of coordinates
164
        $coordinates = $this->coordinates ? call_user_func_array('array_merge', $this->coordinates) : array();
165
166
        return $coordinates ? call_user_func_array('array_merge', $coordinates) : array();
167
    }
168
169
    /**
170
     * @return Cluster[]
171
     */
172
    public function getClusters()
173
    {
174
        // flatten matrix of clusters
175
        return $this->clusters ? call_user_func_array('array_merge', $this->clusters) : array();
176
    }
177
178
    /**
179
     * Based on given bounds, determine matrix size/structure.
180
     */
181
    protected function createMatrix()
182
    {
183
        $totalLat = $this->bounds->ne->latitude - $this->bounds->sw->latitude;
184
        $totalLng = $this->bounds->ne->longitude - $this->bounds->sw->longitude;
185
186
        $approxMiddle = round(sqrt($this->numberOfClusters));
187
        // the smaller one wins
188
        $func = $totalLat > $totalLng ? 'floor' : 'ceil';
189
        $numLat = $func($totalLat / ($totalLat + $totalLng) * $approxMiddle * 2);
190
        $numLng = $approxMiddle * 2 - $numLat;
191
192
        // this will be used later to calculate exactly which sector a
193
        // coordinate falls into (see findCell)
194
        $this->coefficientLat = 1 / ($totalLat) * $numLat;
0 ignored issues
show
Documentation Bug introduced by
The property $coefficientLat was declared of type integer, but 1 / $totalLat * $numLat is of type double. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
195
        $this->coefficientLng = 1 / ($totalLng) * $numLng;
0 ignored issues
show
Documentation Bug introduced by
The property $coefficientLng was declared of type integer, but 1 / $totalLng * $numLng is of type double. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
196
    }
197
198
    /**
199
     * Find the lat & lng indices of the matrix cell
200
     * the given coordinate fits into.
201
     *
202
     * @param  Coordinate $coordinate
203
     * @return array
204
     */
205
    protected function findCell(Coordinate $coordinate)
206
    {
207
        $coordinate = $this->fixCoordinates($coordinate);
208
209
        return array(
210
            floor(($coordinate->latitude - $this->bounds->sw->latitude) * $this->coefficientLat),
211
            floor(($coordinate->longitude - $this->bounds->sw->longitude) * $this->coefficientLng),
212
        );
213
    }
214
215
    /**
216
     * "Fix" coordinates - when leaping from east 360 to west -359, increase
217
     * the west coordinated by 360 to make calculating easier.
218
     *
219
     * @param  Coordinate $coordinate
220
     * @return Coordinate
221
     */
222
    protected function fixCoordinates(Coordinate $coordinate)
223
    {
224
        // create a new copy of this object, don't just change existing one
225
        $coordinate = clone $coordinate;
226
227
        if ($this->spanBoundsLat && $coordinate->latitude < $this->bounds->sw->latitude) {
228
            $coordinate->latitude += 180;
229
        }
230
231
        if ($this->spanBoundsLng && $coordinate->longitude < $this->bounds->sw->longitude) {
232
            $coordinate->longitude += 360;
233
        }
234
235
        return $coordinate;
236
    }
237
    /**
238
     * North and east coordinates can actually be lower than south & west.
239
     * This will happen when the left side of a map is displaying east and
240
     * the right side is displaying west. At the center of the map, we'll
241
     * suddenly have coordinates jumping from 360 to -359.
242
     * To make calculating things easier, we'll just increase the west
243
     * (= negative) coordinates by 360, and consider those to now be east
244
     * (and east as west). Now, coordinates will go from 360 to 361.
245
     *
246
     * @param  Bounds $bounds
247
     * @return Bounds
248
     */
249
    protected function fixBounds(Bounds $bounds)
250
    {
251
        // create a new copy of this object, don't just change existing one
252
        $bounds = clone $bounds;
253
254 View Code Duplication
        if ($this->spanBoundsLat) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
255
            // workaround for crossover bounds being rounded too aggressively
256
            if ($bounds->sw->latitude == 0) {
257
                $bounds->sw->latitude += 180;
258
            }
259
260
            $neLat = max(180 + $bounds->ne->latitude, 180 + $bounds->sw->latitude);
261
            $bounds->sw->latitude = $bounds->ne->latitude;
262
            $bounds->ne->latitude = $neLat;
263
        }
264 View Code Duplication
        if ($this->spanBoundsLng) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
265
            // workaround for crossover bounds being rounded too aggressively
266
            if ($bounds->sw->longitude == 0) {
267
                $bounds->sw->longitude += 360;
268
            }
269
270
            $neLng = max(360 + $bounds->ne->longitude, 360 + $bounds->sw->longitude);
271
            $bounds->sw->longitude = $bounds->ne->longitude;
272
            $bounds->ne->longitude = $neLng;
273
        }
274
275
        return $bounds;
276
    }
277
}
278