Cluster.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
  2. * full list of contributors). Published under the 2-clause BSD license.
  3. * See license.txt in the OpenLayers distribution or repository for the
  4. * full text of the license. */
  5. /**
  6. * @requires OpenLayers/Strategy.js
  7. */
  8. /**
  9. * Class: OpenLayers.Strategy.Cluster
  10. * Strategy for vector feature clustering.
  11. *
  12. * Inherits from:
  13. * - <OpenLayers.Strategy>
  14. */
  15. OpenLayers.Strategy.Cluster = OpenLayers.Class(OpenLayers.Strategy, {
  16. /**
  17. * APIProperty: distance
  18. * {Integer} Pixel distance between features that should be considered a
  19. * single cluster. Default is 20 pixels.
  20. */
  21. distance: 20,
  22. /**
  23. * APIProperty: threshold
  24. * {Integer} Optional threshold below which original features will be
  25. * added to the layer instead of clusters. For example, a threshold
  26. * of 3 would mean that any time there are 2 or fewer features in
  27. * a cluster, those features will be added directly to the layer instead
  28. * of a cluster representing those features. Default is null (which is
  29. * equivalent to 1 - meaning that clusters may contain just one feature).
  30. */
  31. threshold: null,
  32. /**
  33. * Property: features
  34. * {Array(<OpenLayers.Feature.Vector>)} Cached features.
  35. */
  36. features: null,
  37. /**
  38. * Property: clusters
  39. * {Array(<OpenLayers.Feature.Vector>)} Calculated clusters.
  40. */
  41. clusters: null,
  42. /**
  43. * Property: clustering
  44. * {Boolean} The strategy is currently clustering features.
  45. */
  46. clustering: false,
  47. /**
  48. * Property: resolution
  49. * {Float} The resolution (map units per pixel) of the current cluster set.
  50. */
  51. resolution: null,
  52. /**
  53. * Constructor: OpenLayers.Strategy.Cluster
  54. * Create a new clustering strategy.
  55. *
  56. * Parameters:
  57. * options - {Object} Optional object whose properties will be set on the
  58. * instance.
  59. */
  60. /**
  61. * APIMethod: activate
  62. * Activate the strategy. Register any listeners, do appropriate setup.
  63. *
  64. * Returns:
  65. * {Boolean} The strategy was successfully activated.
  66. */
  67. activate: function() {
  68. var activated = OpenLayers.Strategy.prototype.activate.call(this);
  69. if(activated) {
  70. this.layer.events.on({
  71. "beforefeaturesadded": this.cacheFeatures,
  72. "featuresremoved": this.clearCache,
  73. "moveend": this.cluster,
  74. scope: this
  75. });
  76. }
  77. return activated;
  78. },
  79. /**
  80. * APIMethod: deactivate
  81. * Deactivate the strategy. Unregister any listeners, do appropriate
  82. * tear-down.
  83. *
  84. * Returns:
  85. * {Boolean} The strategy was successfully deactivated.
  86. */
  87. deactivate: function() {
  88. var deactivated = OpenLayers.Strategy.prototype.deactivate.call(this);
  89. if(deactivated) {
  90. this.clearCache();
  91. this.layer.events.un({
  92. "beforefeaturesadded": this.cacheFeatures,
  93. "featuresremoved": this.clearCache,
  94. "moveend": this.cluster,
  95. scope: this
  96. });
  97. }
  98. return deactivated;
  99. },
  100. /**
  101. * Method: cacheFeatures
  102. * Cache features before they are added to the layer.
  103. *
  104. * Parameters:
  105. * event - {Object} The event that this was listening for. This will come
  106. * with a batch of features to be clustered.
  107. *
  108. * Returns:
  109. * {Boolean} False to stop features from being added to the layer.
  110. */
  111. cacheFeatures: function(event) {
  112. var propagate = true;
  113. if(!this.clustering) {
  114. this.clearCache();
  115. this.features = event.features;
  116. this.cluster();
  117. propagate = false;
  118. }
  119. return propagate;
  120. },
  121. /**
  122. * Method: clearCache
  123. * Clear out the cached features.
  124. */
  125. clearCache: function() {
  126. if(!this.clustering) {
  127. this.features = null;
  128. }
  129. },
  130. /**
  131. * Method: cluster
  132. * Cluster features based on some threshold distance.
  133. *
  134. * Parameters:
  135. * event - {Object} The event received when cluster is called as a
  136. * result of a moveend event.
  137. */
  138. cluster: function(event) {
  139. if((!event || event.zoomChanged) && this.features) {
  140. var resolution = this.layer.map.getResolution();
  141. if(resolution != this.resolution || !this.clustersExist()) {
  142. this.resolution = resolution;
  143. var clusters = [];
  144. var feature, clustered, cluster;
  145. for(var i=0; i<this.features.length; ++i) {
  146. feature = this.features[i];
  147. if(feature.geometry) {
  148. clustered = false;
  149. for(var j=clusters.length-1; j>=0; --j) {
  150. cluster = clusters[j];
  151. if(this.shouldCluster(cluster, feature)) {
  152. this.addToCluster(cluster, feature);
  153. clustered = true;
  154. break;
  155. }
  156. }
  157. if(!clustered) {
  158. clusters.push(this.createCluster(this.features[i]));
  159. }
  160. }
  161. }
  162. this.clustering = true;
  163. this.layer.removeAllFeatures();
  164. this.clustering = false;
  165. if(clusters.length > 0) {
  166. if(this.threshold > 1) {
  167. var clone = clusters.slice();
  168. clusters = [];
  169. var candidate;
  170. for(var i=0, len=clone.length; i<len; ++i) {
  171. candidate = clone[i];
  172. if(candidate.attributes.count < this.threshold) {
  173. Array.prototype.push.apply(clusters, candidate.cluster);
  174. } else {
  175. clusters.push(candidate);
  176. }
  177. }
  178. }
  179. this.clustering = true;
  180. // A legitimate feature addition could occur during this
  181. // addFeatures call. For clustering to behave well, features
  182. // should be removed from a layer before requesting a new batch.
  183. this.layer.addFeatures(clusters);
  184. this.clustering = false;
  185. }
  186. this.clusters = clusters;
  187. }
  188. }
  189. },
  190. /**
  191. * Method: clustersExist
  192. * Determine whether calculated clusters are already on the layer.
  193. *
  194. * Returns:
  195. * {Boolean} The calculated clusters are already on the layer.
  196. */
  197. clustersExist: function() {
  198. var exist = false;
  199. if(this.clusters && this.clusters.length > 0 &&
  200. this.clusters.length == this.layer.features.length) {
  201. exist = true;
  202. for(var i=0; i<this.clusters.length; ++i) {
  203. if(this.clusters[i] != this.layer.features[i]) {
  204. exist = false;
  205. break;
  206. }
  207. }
  208. }
  209. return exist;
  210. },
  211. /**
  212. * Method: shouldCluster
  213. * Determine whether to include a feature in a given cluster.
  214. *
  215. * Parameters:
  216. * cluster - {<OpenLayers.Feature.Vector>} A cluster.
  217. * feature - {<OpenLayers.Feature.Vector>} A feature.
  218. *
  219. * Returns:
  220. * {Boolean} The feature should be included in the cluster.
  221. */
  222. shouldCluster: function(cluster, feature) {
  223. var cc = cluster.geometry.getBounds().getCenterLonLat();
  224. var fc = feature.geometry.getBounds().getCenterLonLat();
  225. var distance = (
  226. Math.sqrt(
  227. Math.pow((cc.lon - fc.lon), 2) + Math.pow((cc.lat - fc.lat), 2)
  228. ) / this.resolution
  229. );
  230. return (distance <= this.distance);
  231. },
  232. /**
  233. * Method: addToCluster
  234. * Add a feature to a cluster.
  235. *
  236. * Parameters:
  237. * cluster - {<OpenLayers.Feature.Vector>} A cluster.
  238. * feature - {<OpenLayers.Feature.Vector>} A feature.
  239. */
  240. addToCluster: function(cluster, feature) {
  241. cluster.cluster.push(feature);
  242. cluster.attributes.count += 1;
  243. },
  244. /**
  245. * Method: createCluster
  246. * Given a feature, create a cluster.
  247. *
  248. * Parameters:
  249. * feature - {<OpenLayers.Feature.Vector>}
  250. *
  251. * Returns:
  252. * {<OpenLayers.Feature.Vector>} A cluster.
  253. */
  254. createCluster: function(feature) {
  255. var center = feature.geometry.getBounds().getCenterLonLat();
  256. var cluster = new OpenLayers.Feature.Vector(
  257. new OpenLayers.Geometry.Point(center.lon, center.lat),
  258. {count: 1}
  259. );
  260. cluster.cluster = [feature];
  261. return cluster;
  262. },
  263. CLASS_NAME: "OpenLayers.Strategy.Cluster"
  264. });