markerclusterer.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. // ==ClosureCompiler==
  2. // @compilation_level ADVANCED_OPTIMIZATIONS
  3. // @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/maps/google_maps_api_v3_3.js
  4. // ==/ClosureCompiler==
  5. /**
  6. * @name MarkerClusterer for Google Maps v3
  7. * @version version 1.0.1
  8. * @author Luke Mahe
  9. * @fileoverview
  10. * The library creates and manages per-zoom-level clusters for large amounts of
  11. * markers.
  12. */
  13. /**
  14. * Licensed under the Apache License, Version 2.0 (the "License");
  15. * you may not use this file except in compliance with the License.
  16. * You may obtain a copy of the License at
  17. *
  18. * http://www.apache.org/licenses/LICENSE-2.0
  19. *
  20. * Unless required by applicable law or agreed to in writing, software
  21. * distributed under the License is distributed on an "AS IS" BASIS,
  22. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. * See the License for the specific language governing permissions and
  24. * limitations under the License.
  25. */
  26. /**
  27. * A Marker Clusterer that clusters markers.
  28. *
  29. * @param {google.maps.Map} map The Google map to attach to.
  30. * @param {Array.<google.maps.Marker>=} opt_markers Optional markers to add to
  31. * the cluster.
  32. * @param {Object=} opt_options support the following options:
  33. * 'gridSize': (number) The grid size of a cluster in pixels.
  34. * 'maxZoom': (number) The maximum zoom level that a marker can be part of a
  35. * cluster.
  36. * 'zoomOnClick': (boolean) Whether the default behaviour of clicking on a
  37. * cluster is to zoom into it.
  38. * 'imagePath': (string) The base URL where the images representing
  39. * clusters will be found. The full URL will be:
  40. * {imagePath}[1-5].{imageExtension}
  41. * Default: '../images/m'.
  42. * 'imageExtension': (string) The suffix for images URL representing
  43. * clusters will be found. See _imagePath_ for details.
  44. * Default: 'png'.
  45. * 'averageCenter': (boolean) Whether the center of each cluster should be
  46. * the average of all markers in the cluster.
  47. * 'minimumClusterSize': (number) The minimum number of markers to be in a
  48. * cluster before the markers are hidden and a count
  49. * is shown.
  50. * 'styles': (object) An object that has style properties:
  51. * 'url': (string) The image url.
  52. * 'height': (number) The image height.
  53. * 'width': (number) The image width.
  54. * 'anchor': (Array) The anchor position of the label text.
  55. * 'textColor': (string) The text color.
  56. * 'textSize': (number) The text size.
  57. * 'backgroundPosition': (string) The position of the backgound x, y.
  58. * @constructor
  59. * @extends google.maps.OverlayView
  60. */
  61. function MarkerClusterer(map, opt_markers, opt_options) {
  62. // MarkerClusterer implements google.maps.OverlayView interface. We use the
  63. // extend function to extend MarkerClusterer with google.maps.OverlayView
  64. // because it might not always be available when the code is defined so we
  65. // look for it at the last possible moment. If it doesn't exist now then
  66. // there is no point going ahead :)
  67. this.extend(MarkerClusterer, google.maps.OverlayView);
  68. this.map_ = map;
  69. /**
  70. * @type {Array.<google.maps.Marker>}
  71. * @private
  72. */
  73. this.markers_ = [];
  74. /**
  75. * @type {Array.<Cluster>}
  76. */
  77. this.clusters_ = [];
  78. this.sizes = [53, 56, 66, 78, 90];
  79. /**
  80. * @private
  81. */
  82. this.styles_ = [];
  83. /**
  84. * @type {boolean}
  85. * @private
  86. */
  87. this.ready_ = false;
  88. var options = opt_options || {};
  89. /**
  90. * @type {number}
  91. * @private
  92. */
  93. this.gridSize_ = options['gridSize'] || 60;
  94. /**
  95. * @private
  96. */
  97. this.minClusterSize_ = options['minimumClusterSize'] || 2;
  98. /**
  99. * @type {?number}
  100. * @private
  101. */
  102. this.maxZoom_ = options['maxZoom'] || null;
  103. this.styles_ = options['styles'] || [];
  104. /**
  105. * @type {string}
  106. * @private
  107. */
  108. this.imagePath_ = options['imagePath'] ||
  109. this.MARKER_CLUSTER_IMAGE_PATH_;
  110. /**
  111. * @type {string}
  112. * @private
  113. */
  114. this.imageExtension_ = options['imageExtension'] ||
  115. this.MARKER_CLUSTER_IMAGE_EXTENSION_;
  116. /**
  117. * @type {boolean}
  118. * @private
  119. */
  120. this.zoomOnClick_ = true;
  121. if (options['zoomOnClick'] != undefined) {
  122. this.zoomOnClick_ = options['zoomOnClick'];
  123. }
  124. /**
  125. * @type {boolean}
  126. * @private
  127. */
  128. this.averageCenter_ = false;
  129. if (options['averageCenter'] != undefined) {
  130. this.averageCenter_ = options['averageCenter'];
  131. }
  132. this.setupStyles_();
  133. this.setMap(map);
  134. /**
  135. * @type {number}
  136. * @private
  137. */
  138. this.prevZoom_ = this.map_.getZoom();
  139. // Add the map event listeners
  140. var that = this;
  141. google.maps.event.addListener(this.map_, 'zoom_changed', function() {
  142. // Determines map type and prevent illegal zoom levels
  143. var zoom = that.map_.getZoom();
  144. var minZoom = that.map_.minZoom || 0;
  145. var maxZoom = Math.min(that.map_.maxZoom || 100,
  146. that.map_.mapTypes[that.map_.getMapTypeId()].maxZoom);
  147. zoom = Math.min(Math.max(zoom,minZoom),maxZoom);
  148. if (that.prevZoom_ != zoom) {
  149. that.prevZoom_ = zoom;
  150. that.resetViewport();
  151. }
  152. });
  153. google.maps.event.addListener(this.map_, 'idle', function() {
  154. that.redraw();
  155. });
  156. // Finally, add the markers
  157. if (opt_markers && (opt_markers.length || Object.keys(opt_markers).length)) {
  158. this.addMarkers(opt_markers, false);
  159. }
  160. }
  161. /**
  162. * The marker cluster image path.
  163. *
  164. * @type {string}
  165. * @private
  166. */
  167. MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_PATH_ = '../images/m';
  168. /**
  169. * The marker cluster image path.
  170. *
  171. * @type {string}
  172. * @private
  173. */
  174. MarkerClusterer.prototype.MARKER_CLUSTER_IMAGE_EXTENSION_ = 'png';
  175. /**
  176. * Extends a objects prototype by anothers.
  177. *
  178. * @param {Object} obj1 The object to be extended.
  179. * @param {Object} obj2 The object to extend with.
  180. * @return {Object} The new extended object.
  181. * @ignore
  182. */
  183. MarkerClusterer.prototype.extend = function(obj1, obj2) {
  184. return (function(object) {
  185. for (var property in object.prototype) {
  186. this.prototype[property] = object.prototype[property];
  187. }
  188. return this;
  189. }).apply(obj1, [obj2]);
  190. };
  191. /**
  192. * Implementaion of the interface method.
  193. * @ignore
  194. */
  195. MarkerClusterer.prototype.onAdd = function() {
  196. this.setReady_(true);
  197. };
  198. /**
  199. * Implementaion of the interface method.
  200. * @ignore
  201. */
  202. MarkerClusterer.prototype.draw = function() {};
  203. /**
  204. * Sets up the styles object.
  205. *
  206. * @private
  207. */
  208. MarkerClusterer.prototype.setupStyles_ = function() {
  209. if (this.styles_.length) {
  210. return;
  211. }
  212. for (var i = 0, size; size = this.sizes[i]; i++) {
  213. this.styles_.push({
  214. url: this.imagePath_ + (i + 1) + '.' + this.imageExtension_,
  215. height: size,
  216. width: size
  217. });
  218. }
  219. };
  220. /**
  221. * Fit the map to the bounds of the markers in the clusterer.
  222. */
  223. MarkerClusterer.prototype.fitMapToMarkers = function() {
  224. var markers = this.getMarkers();
  225. var bounds = new google.maps.LatLngBounds();
  226. for (var i = 0, marker; marker = markers[i]; i++) {
  227. bounds.extend(marker.getPosition());
  228. }
  229. this.map_.fitBounds(bounds);
  230. };
  231. /**
  232. * Sets the styles.
  233. *
  234. * @param {Object} styles The style to set.
  235. */
  236. MarkerClusterer.prototype.setStyles = function(styles) {
  237. this.styles_ = styles;
  238. };
  239. /**
  240. * Gets the styles.
  241. *
  242. * @return {Object} The styles object.
  243. */
  244. MarkerClusterer.prototype.getStyles = function() {
  245. return this.styles_;
  246. };
  247. /**
  248. * Whether zoom on click is set.
  249. *
  250. * @return {boolean} True if zoomOnClick_ is set.
  251. */
  252. MarkerClusterer.prototype.isZoomOnClick = function() {
  253. return this.zoomOnClick_;
  254. };
  255. /**
  256. * Whether average center is set.
  257. *
  258. * @return {boolean} True if averageCenter_ is set.
  259. */
  260. MarkerClusterer.prototype.isAverageCenter = function() {
  261. return this.averageCenter_;
  262. };
  263. /**
  264. * Returns the array of markers in the clusterer.
  265. *
  266. * @return {Array.<google.maps.Marker>} The markers.
  267. */
  268. MarkerClusterer.prototype.getMarkers = function() {
  269. return this.markers_;
  270. };
  271. /**
  272. * Returns the number of markers in the clusterer
  273. *
  274. * @return {Number} The number of markers.
  275. */
  276. MarkerClusterer.prototype.getTotalMarkers = function() {
  277. return this.markers_.length;
  278. };
  279. /**
  280. * Sets the max zoom for the clusterer.
  281. *
  282. * @param {number} maxZoom The max zoom level.
  283. */
  284. MarkerClusterer.prototype.setMaxZoom = function(maxZoom) {
  285. this.maxZoom_ = maxZoom;
  286. };
  287. /**
  288. * Gets the max zoom for the clusterer.
  289. *
  290. * @return {number} The max zoom level.
  291. */
  292. MarkerClusterer.prototype.getMaxZoom = function() {
  293. return this.maxZoom_;
  294. };
  295. /**
  296. * The function for calculating the cluster icon image.
  297. *
  298. * @param {Array.<google.maps.Marker>} markers The markers in the clusterer.
  299. * @param {number} numStyles The number of styles available.
  300. * @return {Object} A object properties: 'text' (string) and 'index' (number).
  301. * @private
  302. */
  303. MarkerClusterer.prototype.calculator_ = function(markers, numStyles) {
  304. var index = 0;
  305. var count = markers.length;
  306. var dv = count;
  307. while (dv !== 0) {
  308. dv = parseInt(dv / 10, 10);
  309. index++;
  310. }
  311. index = Math.min(index, numStyles);
  312. return {
  313. text: count,
  314. index: index
  315. };
  316. };
  317. /**
  318. * Set the calculator function.
  319. *
  320. * @param {function(Array, number)} calculator The function to set as the
  321. * calculator. The function should return a object properties:
  322. * 'text' (string) and 'index' (number).
  323. *
  324. */
  325. MarkerClusterer.prototype.setCalculator = function(calculator) {
  326. this.calculator_ = calculator;
  327. };
  328. /**
  329. * Get the calculator function.
  330. *
  331. * @return {function(Array, number)} the calculator function.
  332. */
  333. MarkerClusterer.prototype.getCalculator = function() {
  334. return this.calculator_;
  335. };
  336. /**
  337. * Add an array of markers to the clusterer.
  338. *
  339. * @param {Array.<google.maps.Marker>} markers The markers to add.
  340. * @param {boolean=} opt_nodraw Whether to redraw the clusters.
  341. */
  342. MarkerClusterer.prototype.addMarkers = function(markers, opt_nodraw) {
  343. if (markers.length) {
  344. for (var i = 0, marker; marker = markers[i]; i++) {
  345. this.pushMarkerTo_(marker);
  346. }
  347. } else if (Object.keys(markers).length) {
  348. for (var marker in markers) {
  349. this.pushMarkerTo_(markers[marker]);
  350. }
  351. }
  352. if (!opt_nodraw) {
  353. this.redraw();
  354. }
  355. };
  356. /**
  357. * Pushes a marker to the clusterer.
  358. *
  359. * @param {google.maps.Marker} marker The marker to add.
  360. * @private
  361. */
  362. MarkerClusterer.prototype.pushMarkerTo_ = function(marker) {
  363. marker.isAdded = false;
  364. if (marker['draggable']) {
  365. // If the marker is draggable add a listener so we update the clusters on
  366. // the drag end.
  367. var that = this;
  368. google.maps.event.addListener(marker, 'dragend', function() {
  369. marker.isAdded = false;
  370. that.repaint();
  371. });
  372. }
  373. this.markers_.push(marker);
  374. };
  375. /**
  376. * Adds a marker to the clusterer and redraws if needed.
  377. *
  378. * @param {google.maps.Marker} marker The marker to add.
  379. * @param {boolean=} opt_nodraw Whether to redraw the clusters.
  380. */
  381. MarkerClusterer.prototype.addMarker = function(marker, opt_nodraw) {
  382. this.pushMarkerTo_(marker);
  383. if (!opt_nodraw) {
  384. this.redraw();
  385. }
  386. };
  387. /**
  388. * Removes a marker and returns true if removed, false if not
  389. *
  390. * @param {google.maps.Marker} marker The marker to remove
  391. * @return {boolean} Whether the marker was removed or not
  392. * @private
  393. */
  394. MarkerClusterer.prototype.removeMarker_ = function(marker) {
  395. var index = -1;
  396. if (this.markers_.indexOf) {
  397. index = this.markers_.indexOf(marker);
  398. } else {
  399. for (var i = 0, m; m = this.markers_[i]; i++) {
  400. if (m == marker) {
  401. index = i;
  402. break;
  403. }
  404. }
  405. }
  406. if (index == -1) {
  407. // Marker is not in our list of markers.
  408. return false;
  409. }
  410. marker.setMap(null);
  411. this.markers_.splice(index, 1);
  412. return true;
  413. };
  414. /**
  415. * Remove a marker from the cluster.
  416. *
  417. * @param {google.maps.Marker} marker The marker to remove.
  418. * @param {boolean=} opt_nodraw Optional boolean to force no redraw.
  419. * @return {boolean} True if the marker was removed.
  420. */
  421. MarkerClusterer.prototype.removeMarker = function(marker, opt_nodraw) {
  422. var removed = this.removeMarker_(marker);
  423. if (!opt_nodraw && removed) {
  424. this.resetViewport();
  425. this.redraw();
  426. return true;
  427. } else {
  428. return false;
  429. }
  430. };
  431. /**
  432. * Removes an array of markers from the cluster.
  433. *
  434. * @param {Array.<google.maps.Marker>} markers The markers to remove.
  435. * @param {boolean=} opt_nodraw Optional boolean to force no redraw.
  436. */
  437. MarkerClusterer.prototype.removeMarkers = function(markers, opt_nodraw) {
  438. // create a local copy of markers if required
  439. // (removeMarker_ modifies the getMarkers() array in place)
  440. var markersCopy = markers === this.getMarkers() ? markers.slice() : markers;
  441. var removed = false;
  442. for (var i = 0, marker; marker = markersCopy[i]; i++) {
  443. var r = this.removeMarker_(marker);
  444. removed = removed || r;
  445. }
  446. if (!opt_nodraw && removed) {
  447. this.resetViewport();
  448. this.redraw();
  449. return true;
  450. }
  451. };
  452. /**
  453. * Sets the clusterer's ready state.
  454. *
  455. * @param {boolean} ready The state.
  456. * @private
  457. */
  458. MarkerClusterer.prototype.setReady_ = function(ready) {
  459. if (!this.ready_) {
  460. this.ready_ = ready;
  461. this.createClusters_();
  462. }
  463. };
  464. /**
  465. * Returns the number of clusters in the clusterer.
  466. *
  467. * @return {number} The number of clusters.
  468. */
  469. MarkerClusterer.prototype.getTotalClusters = function() {
  470. return this.clusters_.length;
  471. };
  472. /**
  473. * Returns the google map that the clusterer is associated with.
  474. *
  475. * @return {google.maps.Map} The map.
  476. */
  477. MarkerClusterer.prototype.getMap = function() {
  478. return this.map_;
  479. };
  480. /**
  481. * Sets the google map that the clusterer is associated with.
  482. *
  483. * @param {google.maps.Map} map The map.
  484. */
  485. MarkerClusterer.prototype.setMap = function(map) {
  486. this.map_ = map;
  487. };
  488. /**
  489. * Returns the size of the grid.
  490. *
  491. * @return {number} The grid size.
  492. */
  493. MarkerClusterer.prototype.getGridSize = function() {
  494. return this.gridSize_;
  495. };
  496. /**
  497. * Sets the size of the grid.
  498. *
  499. * @param {number} size The grid size.
  500. */
  501. MarkerClusterer.prototype.setGridSize = function(size) {
  502. this.gridSize_ = size;
  503. };
  504. /**
  505. * Returns the min cluster size.
  506. *
  507. * @return {number} The grid size.
  508. */
  509. MarkerClusterer.prototype.getMinClusterSize = function() {
  510. return this.minClusterSize_;
  511. };
  512. /**
  513. * Sets the min cluster size.
  514. *
  515. * @param {number} size The grid size.
  516. */
  517. MarkerClusterer.prototype.setMinClusterSize = function(size) {
  518. this.minClusterSize_ = size;
  519. };
  520. /**
  521. * Extends a bounds object by the grid size.
  522. *
  523. * @param {google.maps.LatLngBounds} bounds The bounds to extend.
  524. * @return {google.maps.LatLngBounds} The extended bounds.
  525. */
  526. MarkerClusterer.prototype.getExtendedBounds = function(bounds) {
  527. var projection = this.getProjection();
  528. // Turn the bounds into latlng.
  529. var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
  530. bounds.getNorthEast().lng());
  531. var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
  532. bounds.getSouthWest().lng());
  533. // Convert the points to pixels and the extend out by the grid size.
  534. var trPix = projection.fromLatLngToDivPixel(tr);
  535. trPix.x += this.gridSize_;
  536. trPix.y -= this.gridSize_;
  537. var blPix = projection.fromLatLngToDivPixel(bl);
  538. blPix.x -= this.gridSize_;
  539. blPix.y += this.gridSize_;
  540. // Convert the pixel points back to LatLng
  541. var ne = projection.fromDivPixelToLatLng(trPix);
  542. var sw = projection.fromDivPixelToLatLng(blPix);
  543. // Extend the bounds to contain the new bounds.
  544. bounds.extend(ne);
  545. bounds.extend(sw);
  546. return bounds;
  547. };
  548. /**
  549. * Determins if a marker is contained in a bounds.
  550. *
  551. * @param {google.maps.Marker} marker The marker to check.
  552. * @param {google.maps.LatLngBounds} bounds The bounds to check against.
  553. * @return {boolean} True if the marker is in the bounds.
  554. * @private
  555. */
  556. MarkerClusterer.prototype.isMarkerInBounds_ = function(marker, bounds) {
  557. return bounds.contains(marker.getPosition());
  558. };
  559. /**
  560. * Clears all clusters and markers from the clusterer.
  561. */
  562. MarkerClusterer.prototype.clearMarkers = function() {
  563. this.resetViewport(true);
  564. // Set the markers a empty array.
  565. this.markers_ = [];
  566. };
  567. /**
  568. * Clears all existing clusters and recreates them.
  569. * @param {boolean} opt_hide To also hide the marker.
  570. */
  571. MarkerClusterer.prototype.resetViewport = function(opt_hide) {
  572. // Remove all the clusters
  573. for (var i = 0, cluster; cluster = this.clusters_[i]; i++) {
  574. cluster.remove();
  575. }
  576. // Reset the markers to not be added and to be invisible.
  577. for (var i = 0, marker; marker = this.markers_[i]; i++) {
  578. marker.isAdded = false;
  579. if (opt_hide) {
  580. marker.setMap(null);
  581. }
  582. }
  583. this.clusters_ = [];
  584. };
  585. /**
  586. *
  587. */
  588. MarkerClusterer.prototype.repaint = function() {
  589. var oldClusters = this.clusters_.slice();
  590. this.clusters_.length = 0;
  591. this.resetViewport();
  592. this.redraw();
  593. // Remove the old clusters.
  594. // Do it in a timeout so the other clusters have been drawn first.
  595. window.setTimeout(function() {
  596. for (var i = 0, cluster; cluster = oldClusters[i]; i++) {
  597. cluster.remove();
  598. }
  599. }, 0);
  600. };
  601. /**
  602. * Redraws the clusters.
  603. */
  604. MarkerClusterer.prototype.redraw = function() {
  605. this.createClusters_();
  606. };
  607. /**
  608. * Calculates the distance between two latlng locations in km.
  609. * @see http://www.movable-type.co.uk/scripts/latlong.html
  610. *
  611. * @param {google.maps.LatLng} p1 The first lat lng point.
  612. * @param {google.maps.LatLng} p2 The second lat lng point.
  613. * @return {number} The distance between the two points in km.
  614. * @private
  615. */
  616. MarkerClusterer.prototype.distanceBetweenPoints_ = function(p1, p2) {
  617. if (!p1 || !p2) {
  618. return 0;
  619. }
  620. var R = 6371; // Radius of the Earth in km
  621. var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
  622. var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
  623. var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
  624. Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
  625. Math.sin(dLon / 2) * Math.sin(dLon / 2);
  626. var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  627. var d = R * c;
  628. return d;
  629. };
  630. /**
  631. * Add a marker to a cluster, or creates a new cluster.
  632. *
  633. * @param {google.maps.Marker} marker The marker to add.
  634. * @private
  635. */
  636. MarkerClusterer.prototype.addToClosestCluster_ = function(marker) {
  637. var distance = 40000; // Some large number
  638. var clusterToAddTo = null;
  639. var pos = marker.getPosition();
  640. for (var i = 0, cluster; cluster = this.clusters_[i]; i++) {
  641. var center = cluster.getCenter();
  642. if (center) {
  643. var d = this.distanceBetweenPoints_(center, marker.getPosition());
  644. if (d < distance) {
  645. distance = d;
  646. clusterToAddTo = cluster;
  647. }
  648. }
  649. }
  650. if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
  651. clusterToAddTo.addMarker(marker);
  652. } else {
  653. var cluster = new Cluster(this);
  654. cluster.addMarker(marker);
  655. this.clusters_.push(cluster);
  656. }
  657. };
  658. /**
  659. * Creates the clusters.
  660. *
  661. * @private
  662. */
  663. MarkerClusterer.prototype.createClusters_ = function() {
  664. if (!this.ready_) {
  665. return;
  666. }
  667. // Get our current map view bounds.
  668. // Create a new bounds object so we don't affect the map.
  669. var mapBounds = new google.maps.LatLngBounds(this.map_.getBounds().getSouthWest(),
  670. this.map_.getBounds().getNorthEast());
  671. var bounds = this.getExtendedBounds(mapBounds);
  672. for (var i = 0, marker; marker = this.markers_[i]; i++) {
  673. if (!marker.isAdded && this.isMarkerInBounds_(marker, bounds)) {
  674. this.addToClosestCluster_(marker);
  675. }
  676. }
  677. };
  678. /**
  679. * A cluster that contains markers.
  680. *
  681. * @param {MarkerClusterer} markerClusterer The markerclusterer that this
  682. * cluster is associated with.
  683. * @constructor
  684. * @ignore
  685. */
  686. function Cluster(markerClusterer) {
  687. this.markerClusterer_ = markerClusterer;
  688. this.map_ = markerClusterer.getMap();
  689. this.gridSize_ = markerClusterer.getGridSize();
  690. this.minClusterSize_ = markerClusterer.getMinClusterSize();
  691. this.averageCenter_ = markerClusterer.isAverageCenter();
  692. this.center_ = null;
  693. this.markers_ = [];
  694. this.bounds_ = null;
  695. this.clusterIcon_ = new ClusterIcon(this, markerClusterer.getStyles(),
  696. markerClusterer.getGridSize());
  697. }
  698. /**
  699. * Determins if a marker is already added to the cluster.
  700. *
  701. * @param {google.maps.Marker} marker The marker to check.
  702. * @return {boolean} True if the marker is already added.
  703. */
  704. Cluster.prototype.isMarkerAlreadyAdded = function(marker) {
  705. if (this.markers_.indexOf) {
  706. return this.markers_.indexOf(marker) != -1;
  707. } else {
  708. for (var i = 0, m; m = this.markers_[i]; i++) {
  709. if (m == marker) {
  710. return true;
  711. }
  712. }
  713. }
  714. return false;
  715. };
  716. /**
  717. * Add a marker the cluster.
  718. *
  719. * @param {google.maps.Marker} marker The marker to add.
  720. * @return {boolean} True if the marker was added.
  721. */
  722. Cluster.prototype.addMarker = function(marker) {
  723. if (this.isMarkerAlreadyAdded(marker)) {
  724. return false;
  725. }
  726. if (!this.center_) {
  727. this.center_ = marker.getPosition();
  728. this.calculateBounds_();
  729. } else {
  730. if (this.averageCenter_) {
  731. var l = this.markers_.length + 1;
  732. var lat = (this.center_.lat() * (l-1) + marker.getPosition().lat()) / l;
  733. var lng = (this.center_.lng() * (l-1) + marker.getPosition().lng()) / l;
  734. this.center_ = new google.maps.LatLng(lat, lng);
  735. this.calculateBounds_();
  736. }
  737. }
  738. marker.isAdded = true;
  739. this.markers_.push(marker);
  740. var len = this.markers_.length;
  741. if (len < this.minClusterSize_ && marker.getMap() != this.map_) {
  742. // Min cluster size not reached so show the marker.
  743. marker.setMap(this.map_);
  744. }
  745. if (len == this.minClusterSize_) {
  746. // Hide the markers that were showing.
  747. for (var i = 0; i < len; i++) {
  748. this.markers_[i].setMap(null);
  749. }
  750. }
  751. if (len >= this.minClusterSize_) {
  752. marker.setMap(null);
  753. }
  754. this.updateIcon();
  755. return true;
  756. };
  757. /**
  758. * Returns the marker clusterer that the cluster is associated with.
  759. *
  760. * @return {MarkerClusterer} The associated marker clusterer.
  761. */
  762. Cluster.prototype.getMarkerClusterer = function() {
  763. return this.markerClusterer_;
  764. };
  765. /**
  766. * Returns the bounds of the cluster.
  767. *
  768. * @return {google.maps.LatLngBounds} the cluster bounds.
  769. */
  770. Cluster.prototype.getBounds = function() {
  771. var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
  772. var markers = this.getMarkers();
  773. for (var i = 0, marker; marker = markers[i]; i++) {
  774. bounds.extend(marker.getPosition());
  775. }
  776. return bounds;
  777. };
  778. /**
  779. * Removes the cluster
  780. */
  781. Cluster.prototype.remove = function() {
  782. this.clusterIcon_.remove();
  783. this.markers_.length = 0;
  784. delete this.markers_;
  785. };
  786. /**
  787. * Returns the number of markers in the cluster.
  788. *
  789. * @return {number} The number of markers in the cluster.
  790. */
  791. Cluster.prototype.getSize = function() {
  792. return this.markers_.length;
  793. };
  794. /**
  795. * Returns a list of the markers in the cluster.
  796. *
  797. * @return {Array.<google.maps.Marker>} The markers in the cluster.
  798. */
  799. Cluster.prototype.getMarkers = function() {
  800. return this.markers_;
  801. };
  802. /**
  803. * Returns the center of the cluster.
  804. *
  805. * @return {google.maps.LatLng} The cluster center.
  806. */
  807. Cluster.prototype.getCenter = function() {
  808. return this.center_;
  809. };
  810. /**
  811. * Calculated the extended bounds of the cluster with the grid.
  812. *
  813. * @private
  814. */
  815. Cluster.prototype.calculateBounds_ = function() {
  816. var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
  817. this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
  818. };
  819. /**
  820. * Determines if a marker lies in the clusters bounds.
  821. *
  822. * @param {google.maps.Marker} marker The marker to check.
  823. * @return {boolean} True if the marker lies in the bounds.
  824. */
  825. Cluster.prototype.isMarkerInClusterBounds = function(marker) {
  826. return this.bounds_.contains(marker.getPosition());
  827. };
  828. /**
  829. * Returns the map that the cluster is associated with.
  830. *
  831. * @return {google.maps.Map} The map.
  832. */
  833. Cluster.prototype.getMap = function() {
  834. return this.map_;
  835. };
  836. /**
  837. * Updates the cluster icon
  838. */
  839. Cluster.prototype.updateIcon = function() {
  840. var zoom = this.map_.getZoom();
  841. var mz = this.markerClusterer_.getMaxZoom();
  842. if (mz && zoom > mz) {
  843. // The zoom is greater than our max zoom so show all the markers in cluster.
  844. for (var i = 0, marker; marker = this.markers_[i]; i++) {
  845. marker.setMap(this.map_);
  846. }
  847. return;
  848. }
  849. if (this.markers_.length < this.minClusterSize_) {
  850. // Min cluster size not yet reached.
  851. this.clusterIcon_.hide();
  852. return;
  853. }
  854. var numStyles = this.markerClusterer_.getStyles().length;
  855. var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
  856. this.clusterIcon_.setCenter(this.center_);
  857. this.clusterIcon_.setSums(sums);
  858. this.clusterIcon_.show();
  859. };
  860. /**
  861. * A cluster icon
  862. *
  863. * @param {Cluster} cluster The cluster to be associated with.
  864. * @param {Object} styles An object that has style properties:
  865. * 'url': (string) The image url.
  866. * 'height': (number) The image height.
  867. * 'width': (number) The image width.
  868. * 'anchor': (Array) The anchor position of the label text.
  869. * 'textColor': (string) The text color.
  870. * 'textSize': (number) The text size.
  871. * 'backgroundPosition: (string) The background postition x, y.
  872. * @param {number=} opt_padding Optional padding to apply to the cluster icon.
  873. * @constructor
  874. * @extends google.maps.OverlayView
  875. * @ignore
  876. */
  877. function ClusterIcon(cluster, styles, opt_padding) {
  878. cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);
  879. this.styles_ = styles;
  880. this.padding_ = opt_padding || 0;
  881. this.cluster_ = cluster;
  882. this.center_ = null;
  883. this.map_ = cluster.getMap();
  884. this.div_ = null;
  885. this.sums_ = null;
  886. this.visible_ = false;
  887. this.setMap(this.map_);
  888. }
  889. /**
  890. * Triggers the clusterclick event and zoom's if the option is set.
  891. */
  892. ClusterIcon.prototype.triggerClusterClick = function() {
  893. var markerClusterer = this.cluster_.getMarkerClusterer();
  894. // Trigger the clusterclick event.
  895. google.maps.event.trigger(markerClusterer.map_, 'clusterclick', this.cluster_);
  896. if (markerClusterer.isZoomOnClick()) {
  897. // Zoom into the cluster.
  898. this.map_.fitBounds(this.cluster_.getBounds());
  899. }
  900. };
  901. /**
  902. * Adding the cluster icon to the dom.
  903. * @ignore
  904. */
  905. ClusterIcon.prototype.onAdd = function() {
  906. this.div_ = document.createElement('DIV');
  907. if (this.visible_) {
  908. var pos = this.getPosFromLatLng_(this.center_);
  909. this.div_.style.cssText = this.createCss(pos);
  910. this.div_.innerHTML = this.sums_.text;
  911. }
  912. var panes = this.getPanes();
  913. panes.overlayMouseTarget.appendChild(this.div_);
  914. var that = this;
  915. google.maps.event.addDomListener(this.div_, 'click', function() {
  916. that.triggerClusterClick();
  917. });
  918. };
  919. /**
  920. * Returns the position to place the div dending on the latlng.
  921. *
  922. * @param {google.maps.LatLng} latlng The position in latlng.
  923. * @return {google.maps.Point} The position in pixels.
  924. * @private
  925. */
  926. ClusterIcon.prototype.getPosFromLatLng_ = function(latlng) {
  927. var pos = this.getProjection().fromLatLngToDivPixel(latlng);
  928. pos.x -= parseInt(this.width_ / 2, 10);
  929. pos.y -= parseInt(this.height_ / 2, 10);
  930. return pos;
  931. };
  932. /**
  933. * Draw the icon.
  934. * @ignore
  935. */
  936. ClusterIcon.prototype.draw = function() {
  937. if (this.visible_) {
  938. var pos = this.getPosFromLatLng_(this.center_);
  939. this.div_.style.top = pos.y + 'px';
  940. this.div_.style.left = pos.x + 'px';
  941. this.div_.style.zIndex = google.maps.Marker.MAX_ZINDEX + 1;
  942. }
  943. };
  944. /**
  945. * Hide the icon.
  946. */
  947. ClusterIcon.prototype.hide = function() {
  948. if (this.div_) {
  949. this.div_.style.display = 'none';
  950. }
  951. this.visible_ = false;
  952. };
  953. /**
  954. * Position and show the icon.
  955. */
  956. ClusterIcon.prototype.show = function() {
  957. if (this.div_) {
  958. var pos = this.getPosFromLatLng_(this.center_);
  959. this.div_.style.cssText = this.createCss(pos);
  960. this.div_.style.display = '';
  961. }
  962. this.visible_ = true;
  963. };
  964. /**
  965. * Remove the icon from the map
  966. */
  967. ClusterIcon.prototype.remove = function() {
  968. this.setMap(null);
  969. };
  970. /**
  971. * Implementation of the onRemove interface.
  972. * @ignore
  973. */
  974. ClusterIcon.prototype.onRemove = function() {
  975. if (this.div_ && this.div_.parentNode) {
  976. this.hide();
  977. this.div_.parentNode.removeChild(this.div_);
  978. this.div_ = null;
  979. }
  980. };
  981. /**
  982. * Set the sums of the icon.
  983. *
  984. * @param {Object} sums The sums containing:
  985. * 'text': (string) The text to display in the icon.
  986. * 'index': (number) The style index of the icon.
  987. */
  988. ClusterIcon.prototype.setSums = function(sums) {
  989. this.sums_ = sums;
  990. this.text_ = sums.text;
  991. this.index_ = sums.index;
  992. if (this.div_) {
  993. this.div_.innerHTML = sums.text;
  994. }
  995. this.useStyle();
  996. };
  997. /**
  998. * Sets the icon to the the styles.
  999. */
  1000. ClusterIcon.prototype.useStyle = function() {
  1001. var index = Math.max(0, this.sums_.index - 1);
  1002. index = Math.min(this.styles_.length - 1, index);
  1003. var style = this.styles_[index];
  1004. this.url_ = style['url'];
  1005. this.height_ = style['height'];
  1006. this.width_ = style['width'];
  1007. this.textColor_ = style['textColor'];
  1008. this.anchor_ = style['anchor'];
  1009. this.textSize_ = style['textSize'];
  1010. this.backgroundPosition_ = style['backgroundPosition'];
  1011. };
  1012. /**
  1013. * Sets the center of the icon.
  1014. *
  1015. * @param {google.maps.LatLng} center The latlng to set as the center.
  1016. */
  1017. ClusterIcon.prototype.setCenter = function(center) {
  1018. this.center_ = center;
  1019. };
  1020. /**
  1021. * Create the css text based on the position of the icon.
  1022. *
  1023. * @param {google.maps.Point} pos The position.
  1024. * @return {string} The css style text.
  1025. */
  1026. ClusterIcon.prototype.createCss = function(pos) {
  1027. var style = [];
  1028. style.push('background-image:url(' + this.url_ + ');');
  1029. var backgroundPosition = this.backgroundPosition_ ? this.backgroundPosition_ : '0 0';
  1030. style.push('background-position:' + backgroundPosition + ';');
  1031. if (typeof this.anchor_ === 'object') {
  1032. if (typeof this.anchor_[0] === 'number' && this.anchor_[0] > 0 &&
  1033. this.anchor_[0] < this.height_) {
  1034. style.push('height:' + (this.height_ - this.anchor_[0]) +
  1035. 'px; padding-top:' + this.anchor_[0] + 'px;');
  1036. } else {
  1037. style.push('height:' + this.height_ + 'px; line-height:' + this.height_ +
  1038. 'px;');
  1039. }
  1040. if (typeof this.anchor_[1] === 'number' && this.anchor_[1] > 0 &&
  1041. this.anchor_[1] < this.width_) {
  1042. style.push('width:' + (this.width_ - this.anchor_[1]) +
  1043. 'px; padding-left:' + this.anchor_[1] + 'px;');
  1044. } else {
  1045. style.push('width:' + this.width_ + 'px; text-align:center;');
  1046. }
  1047. } else {
  1048. style.push('height:' + this.height_ + 'px; line-height:' +
  1049. this.height_ + 'px; width:' + this.width_ + 'px; text-align:center;');
  1050. }
  1051. var txtColor = this.textColor_ ? this.textColor_ : 'black';
  1052. var txtSize = this.textSize_ ? this.textSize_ : 11;
  1053. style.push('cursor:pointer; top:' + pos.y + 'px; left:' +
  1054. pos.x + 'px; color:' + txtColor + '; position:absolute; font-size:' +
  1055. txtSize + 'px; font-family:Arial,sans-serif; font-weight:bold');
  1056. return style.join('');
  1057. };
  1058. // Export Symbols for Closure
  1059. // If you are not going to compile with closure then you can remove the
  1060. // code below.
  1061. window['MarkerClusterer'] = MarkerClusterer;
  1062. MarkerClusterer.prototype['addMarker'] = MarkerClusterer.prototype.addMarker;
  1063. MarkerClusterer.prototype['addMarkers'] = MarkerClusterer.prototype.addMarkers;
  1064. MarkerClusterer.prototype['clearMarkers'] =
  1065. MarkerClusterer.prototype.clearMarkers;
  1066. MarkerClusterer.prototype['fitMapToMarkers'] =
  1067. MarkerClusterer.prototype.fitMapToMarkers;
  1068. MarkerClusterer.prototype['getCalculator'] =
  1069. MarkerClusterer.prototype.getCalculator;
  1070. MarkerClusterer.prototype['getGridSize'] =
  1071. MarkerClusterer.prototype.getGridSize;
  1072. MarkerClusterer.prototype['getExtendedBounds'] =
  1073. MarkerClusterer.prototype.getExtendedBounds;
  1074. MarkerClusterer.prototype['getMap'] = MarkerClusterer.prototype.getMap;
  1075. MarkerClusterer.prototype['getMarkers'] = MarkerClusterer.prototype.getMarkers;
  1076. MarkerClusterer.prototype['getMaxZoom'] = MarkerClusterer.prototype.getMaxZoom;
  1077. MarkerClusterer.prototype['getStyles'] = MarkerClusterer.prototype.getStyles;
  1078. MarkerClusterer.prototype['getTotalClusters'] =
  1079. MarkerClusterer.prototype.getTotalClusters;
  1080. MarkerClusterer.prototype['getTotalMarkers'] =
  1081. MarkerClusterer.prototype.getTotalMarkers;
  1082. MarkerClusterer.prototype['redraw'] = MarkerClusterer.prototype.redraw;
  1083. MarkerClusterer.prototype['removeMarker'] =
  1084. MarkerClusterer.prototype.removeMarker;
  1085. MarkerClusterer.prototype['removeMarkers'] =
  1086. MarkerClusterer.prototype.removeMarkers;
  1087. MarkerClusterer.prototype['resetViewport'] =
  1088. MarkerClusterer.prototype.resetViewport;
  1089. MarkerClusterer.prototype['repaint'] =
  1090. MarkerClusterer.prototype.repaint;
  1091. MarkerClusterer.prototype['setCalculator'] =
  1092. MarkerClusterer.prototype.setCalculator;
  1093. MarkerClusterer.prototype['setGridSize'] =
  1094. MarkerClusterer.prototype.setGridSize;
  1095. MarkerClusterer.prototype['setMaxZoom'] =
  1096. MarkerClusterer.prototype.setMaxZoom;
  1097. MarkerClusterer.prototype['onAdd'] = MarkerClusterer.prototype.onAdd;
  1098. MarkerClusterer.prototype['draw'] = MarkerClusterer.prototype.draw;
  1099. Cluster.prototype['getCenter'] = Cluster.prototype.getCenter;
  1100. Cluster.prototype['getSize'] = Cluster.prototype.getSize;
  1101. Cluster.prototype['getMarkers'] = Cluster.prototype.getMarkers;
  1102. ClusterIcon.prototype['onAdd'] = ClusterIcon.prototype.onAdd;
  1103. ClusterIcon.prototype['draw'] = ClusterIcon.prototype.draw;
  1104. ClusterIcon.prototype['onRemove'] = ClusterIcon.prototype.onRemove;
  1105. Object.keys = Object.keys || function(o) {
  1106. var result = [];
  1107. for(var name in o) {
  1108. if (o.hasOwnProperty(name))
  1109. result.push(name);
  1110. }
  1111. return result;
  1112. };