Source: MarkerClusterer.js

  1. /**
  2. * @name MarkerClustererPlus for Google Maps V3
  3. * @version 2.1.1 [November 4, 2013]
  4. * @author Gary Little
  5. * @fileoverview
  6. * The library creates and manages per-zoom-level clusters for large amounts of markers.
  7. * <p>
  8. * This is an enhanced V3 implementation of the
  9. * <a href="http://gmaps-utility-library-dev.googlecode.com/svn/tags/markerclusterer/"
  10. * >V2 MarkerClusterer</a> by Xiaoxi Wu. It is based on the
  11. * <a href="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerclusterer/"
  12. * >V3 MarkerClusterer</a> port by Luke Mahe. MarkerClustererPlus was created by Gary Little.
  13. * <p>
  14. * v2.0 release: MarkerClustererPlus v2.0 is backward compatible with MarkerClusterer v1.0. It
  15. * adds support for the <code>ignoreHidden</code>, <code>title</code>, <code>batchSizeIE</code>,
  16. * and <code>calculator</code> properties as well as support for four more events. It also allows
  17. * greater control over the styling of the text that appears on the cluster marker. The
  18. * documentation has been significantly improved and the overall code has been simplified and
  19. * polished. Very large numbers of markers can now be managed without causing Javascript timeout
  20. * errors on Internet Explorer. Note that the name of the <code>clusterclick</code> event has been
  21. * deprecated. The new name is <code>click</code>, so please change your application code now.
  22. */
  23. /**
  24. * Licensed under the Apache License, Version 2.0 (the "License");
  25. * you may not use this file except in compliance with the License.
  26. * You may obtain a copy of the License at
  27. *
  28. * http://www.apache.org/licenses/LICENSE-2.0
  29. *
  30. * Unless required by applicable law or agreed to in writing, software
  31. * distributed under the License is distributed on an "AS IS" BASIS,
  32. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  33. * See the License for the specific language governing permissions and
  34. * limitations under the License.
  35. */
  36. /**
  37. * @name ClusterIconStyle
  38. * @class This class represents the object for values in the <code>styles</code> array passed
  39. * to the {@link MarkerClusterer} constructor. The element in this array that is used to
  40. * style the cluster icon is determined by calling the <code>calculator</code> function.
  41. *
  42. * @property {string} url The URL of the cluster icon image file. Required.
  43. * @property {number} height The display height (in pixels) of the cluster icon. Required.
  44. * @property {number} width The display width (in pixels) of the cluster icon. Required.
  45. * @property {Array} [anchorText] The position (in pixels) from the center of the cluster icon to
  46. * where the text label is to be centered and drawn. The format is <code>[yoffset, xoffset]</code>
  47. * where <code>yoffset</code> increases as you go down from center and <code>xoffset</code>
  48. * increases to the right of center. The default is <code>[0, 0]</code>.
  49. * @property {Array} [anchorIcon] The anchor position (in pixels) of the cluster icon. This is the
  50. * spot on the cluster icon that is to be aligned with the cluster position. The format is
  51. * <code>[yoffset, xoffset]</code> where <code>yoffset</code> increases as you go down and
  52. * <code>xoffset</code> increases to the right of the top-left corner of the icon. The default
  53. * anchor position is the center of the cluster icon.
  54. * @property {string} [textColor="black"] The color of the label text shown on the
  55. * cluster icon.
  56. * @property {number} [textSize=11] The size (in pixels) of the label text shown on the
  57. * cluster icon.
  58. * @property {string} [textDecoration="none"] The value of the CSS <code>text-decoration</code>
  59. * property for the label text shown on the cluster icon.
  60. * @property {string} [fontWeight="bold"] The value of the CSS <code>font-weight</code>
  61. * property for the label text shown on the cluster icon.
  62. * @property {string} [fontStyle="normal"] The value of the CSS <code>font-style</code>
  63. * property for the label text shown on the cluster icon.
  64. * @property {string} [fontFamily="Arial,sans-serif"] The value of the CSS <code>font-family</code>
  65. * property for the label text shown on the cluster icon.
  66. * @property {string} [backgroundPosition="0 0"] The position of the cluster icon image
  67. * within the image defined by <code>url</code>. The format is <code>"xpos ypos"</code>
  68. * (the same format as for the CSS <code>background-position</code> property). You must set
  69. * this property appropriately when the image defined by <code>url</code> represents a sprite
  70. * containing multiple images. Note that the position <i>must</i> be specified in px units.
  71. */
  72. /**
  73. * @name ClusterIconInfo
  74. * @class This class is an object containing general information about a cluster icon. This is
  75. * the object that a <code>calculator</code> function returns.
  76. *
  77. * @property {string} text The text of the label to be shown on the cluster icon.
  78. * @property {number} index The index plus 1 of the element in the <code>styles</code>
  79. * array to be used to style the cluster icon.
  80. * @property {string} title The tooltip to display when the mouse moves over the cluster icon.
  81. * If this value is <code>undefined</code> or <code>""</code>, <code>title</code> is set to the
  82. * value of the <code>title</code> property passed to the MarkerClusterer.
  83. */
  84. /**
  85. * A cluster icon.
  86. *
  87. * @constructor
  88. * @extends google.maps.OverlayView
  89. * @param {Cluster} cluster The cluster with which the icon is to be associated.
  90. * @param {Array} [styles] An array of {@link ClusterIconStyle} defining the cluster icons
  91. * to use for various cluster sizes.
  92. * @private
  93. */
  94. function ClusterIcon(cluster, styles) {
  95. cluster.getMarkerClusterer().extend(ClusterIcon, google.maps.OverlayView);
  96. this.cluster_ = cluster;
  97. this.className_ = cluster.getMarkerClusterer().getClusterClass();
  98. this.styles_ = styles;
  99. this.center_ = null;
  100. this.div_ = null;
  101. this.sums_ = null;
  102. this.visible_ = false;
  103. this.setMap(cluster.getMap()); // Note: this causes onAdd to be called
  104. }
  105. /**
  106. * Adds the icon to the DOM.
  107. */
  108. ClusterIcon.prototype.onAdd = function() {
  109. var cClusterIcon = this;
  110. var cMouseDownInCluster;
  111. var cDraggingMapByCluster;
  112. this.div_ = document.createElement("div");
  113. this.div_.className = this.className_;
  114. if (this.visible_) {
  115. this.show();
  116. }
  117. this.getPanes().overlayMouseTarget.appendChild(this.div_);
  118. // Fix for Issue 157
  119. this.boundsChangedListener_ = google.maps.event.addListener(this.getMap(), "bounds_changed", function() {
  120. cDraggingMapByCluster = cMouseDownInCluster;
  121. });
  122. this.div_.addEventListener("mousedown", function() {
  123. cMouseDownInCluster = true;
  124. cDraggingMapByCluster = false;
  125. });
  126. this.div_.addEventListener("click", function(e) {
  127. cMouseDownInCluster = false;
  128. if (!cDraggingMapByCluster) {
  129. var theBounds;
  130. var mz;
  131. var mc = cClusterIcon.cluster_.getMarkerClusterer();
  132. /**
  133. * This event is fired when a cluster marker is clicked.
  134. * @name MarkerClusterer#click
  135. * @param {Cluster} c The cluster that was clicked.
  136. * @event
  137. */
  138. google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
  139. google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
  140. // The default click handler follows. Disable it by setting
  141. // the zoomOnClick property to false.
  142. if (mc.getZoomOnClick()) {
  143. // Zoom into the cluster.
  144. mz = mc.getMaxZoom();
  145. theBounds = cClusterIcon.cluster_.getBounds();
  146. mc.getMap().fitBounds(theBounds);
  147. // There is a fix for Issue 170 here:
  148. setTimeout(function() {
  149. mc.getMap().fitBounds(theBounds);
  150. // Don't zoom beyond the max zoom level
  151. if (mz !== null && (mc.getMap().getZoom() > mz)) {
  152. mc.getMap().setZoom(mz + 1);
  153. }
  154. }, 100);
  155. }
  156. // Prevent event propagation to the map:
  157. e.cancelBubble = true;
  158. if (e.stopPropagation) {
  159. e.stopPropagation();
  160. }
  161. }
  162. });
  163. this.div_.addEventListener("mouseover", function() {
  164. var mc = cClusterIcon.cluster_.getMarkerClusterer();
  165. /**
  166. * This event is fired when the mouse moves over a cluster marker.
  167. * @name MarkerClusterer#mouseover
  168. * @param {Cluster} c The cluster that the mouse moved over.
  169. * @event
  170. */
  171. google.maps.event.trigger(mc, "mouseover", cClusterIcon.cluster_);
  172. google.maps.event.trigger(cClusterIcon.cluster_, "mouseover");
  173. });
  174. this.div_.addEventListener( "mouseout", function() {
  175. var mc = cClusterIcon.cluster_.getMarkerClusterer();
  176. /**
  177. * This event is fired when the mouse moves out of a cluster marker.
  178. * @name MarkerClusterer#mouseout
  179. * @param {Cluster} c The cluster that the mouse moved out of.
  180. * @event
  181. */
  182. google.maps.event.trigger(mc, "mouseout", cClusterIcon.cluster_);
  183. google.maps.event.trigger(cClusterIcon.cluster_, "mouseout");
  184. });
  185. var mc = this.cluster_.getMarkerClusterer();
  186. if (mc.markers_.caculateSum !== undefined) {
  187. var infowindow = new google.maps.InfoWindow({
  188. maxWidth: 350
  189. });
  190. google.maps.event.addListener(this.cluster_, 'mouseover', function(event) {
  191. var tooltip = mc.markers_.caculateSum(this.cluster_.markers_);
  192. var content, style;
  193. if (typeof tooltip == "object") {
  194. if (tooltip.style)
  195. style = tooltip.style;
  196. if (tooltip.element)
  197. content = tooltip.element;
  198. } else
  199. content = tooltip;
  200. if (style !== undefined)
  201. infowindow.setOptions(style);
  202. infowindow.setContent(content);
  203. var info = new google.maps.MVCObject;
  204. info.set('position', this.center_);
  205. info.set('anchorPoint', new google.maps.Point(0, -12));
  206. infowindow.open(mc.map, info);
  207. }.bind(this));
  208. google.maps.event.addListener(this.cluster_, 'mouseout', function(event) {
  209. infowindow.close();
  210. }.bind(this));
  211. google.maps.event.addListener(mc.map, "zoom_changed", function() {
  212. infowindow.close();
  213. })
  214. }
  215. };
  216. /**
  217. * Removes the icon from the DOM.
  218. */
  219. ClusterIcon.prototype.onRemove = function() {
  220. if (this.div_ && this.div_.parentNode) {
  221. this.hide();
  222. google.maps.event.removeListener(this.boundsChangedListener_);
  223. google.maps.event.clearInstanceListeners(this.div_);
  224. this.div_.parentNode.removeChild(this.div_);
  225. this.div_ = null;
  226. }
  227. };
  228. /**
  229. * Draws the icon.
  230. */
  231. ClusterIcon.prototype.draw = function() {
  232. if (this.visible_) {
  233. var pos = this.getPosFromLatLng_(this.center_);
  234. this.div_.style.top = pos.y + "px";
  235. this.div_.style.left = pos.x + "px";
  236. }
  237. };
  238. /**
  239. * Hides the icon.
  240. */
  241. ClusterIcon.prototype.hide = function() {
  242. if (this.div_) {
  243. this.div_.style.display = "none";
  244. }
  245. this.visible_ = false;
  246. };
  247. /**
  248. * Positions and shows the icon.
  249. */
  250. ClusterIcon.prototype.show = function() {
  251. if (this.div_) {
  252. var img = "";
  253. // NOTE: values must be specified in px units
  254. var bp = this.backgroundPosition_.split(" ");
  255. var spriteH = parseInt(bp[0].trim(), 10);
  256. var spriteV = parseInt(bp[1].trim(), 10);
  257. var pos = this.getPosFromLatLng_(this.center_);
  258. this.div_.style.cssText = this.createCss(pos);
  259. img = "<img src='" + this.url_ + "' style='position: absolute; top: " + spriteV + "px; left: " + spriteH + "px; ";
  260. if (!this.cluster_.getMarkerClusterer().enableRetinaIcons_) {
  261. img += "clip: rect(" + (-1 * spriteV) + "px, " + ((-1 * spriteH) + this.width_) + "px, " +
  262. ((-1 * spriteV) + this.height_) + "px, " + (-1 * spriteH) + "px);";
  263. } else {
  264. img += "width: " + this.width_ + "px;" + "height: " + this.height_ + "px;";
  265. }
  266. img += "'>";
  267. this.div_.innerHTML = img + "<div style='" +
  268. "position: absolute;" +
  269. "top: " + this.anchorText_[0] + "px;" +
  270. "left: " + this.anchorText_[1] + "px;" +
  271. "color: " + this.textColor_ + ";" +
  272. "font-size: " + this.textSize_ + "px;" +
  273. "font-family: " + this.fontFamily_ + ";" +
  274. "font-weight: " + this.fontWeight_ + ";" +
  275. "font-style: " + this.fontStyle_ + ";" +
  276. "text-decoration: " + this.textDecoration_ + ";" +
  277. "text-align: center;" +
  278. "width: " + this.width_ + "px;" +
  279. "line-height:" + this.height_ + "px;" +
  280. "'>" + (this.cluster_.hideLabel_ ? ' ' : this.sums_.text) + "</div>";
  281. if (typeof this.sums_.title === "undefined" || this.sums_.title === "") {
  282. this.div_.title = this.cluster_.getMarkerClusterer().getTitle();
  283. } else {
  284. this.div_.title = this.sums_.title;
  285. }
  286. this.div_.style.display = "";
  287. }
  288. this.visible_ = true;
  289. };
  290. /**
  291. * Sets the icon styles to the appropriate element in the styles array.
  292. *
  293. * @param {ClusterIconInfo} sums The icon label text and styles index.
  294. */
  295. ClusterIcon.prototype.useStyle = function(sums) {
  296. this.sums_ = sums;
  297. var index = Math.max(0, sums.index - 1);
  298. index = Math.min(this.styles_.length - 1, index);
  299. var style = this.styles_[index];
  300. this.url_ = style.url;
  301. this.height_ = style.height;
  302. this.width_ = style.width;
  303. this.anchorText_ = style.anchorText || [0, 0];
  304. this.anchorIcon_ = style.anchorIcon || [parseInt(this.height_ / 2, 10), parseInt(this.width_ / 2, 10)];
  305. this.textColor_ = style.textColor || "black";
  306. this.textSize_ = style.textSize || 11;
  307. this.textDecoration_ = style.textDecoration || "none";
  308. this.fontWeight_ = style.fontWeight || "bold";
  309. this.fontStyle_ = style.fontStyle || "normal";
  310. this.fontFamily_ = style.fontFamily || "Arial,sans-serif";
  311. this.backgroundPosition_ = style.backgroundPosition || "0 0";
  312. };
  313. /**
  314. * Sets the position at which to center the icon.
  315. *
  316. * @param {google.maps.LatLng} center The latlng to set as the center.
  317. */
  318. ClusterIcon.prototype.setCenter = function(center) {
  319. this.center_ = center;
  320. };
  321. /**
  322. * Creates the cssText style parameter based on the position of the icon.
  323. *
  324. * @param {google.maps.Point} pos The position of the icon.
  325. * @return {string} The CSS style text.
  326. */
  327. ClusterIcon.prototype.createCss = function(pos) {
  328. var style = [];
  329. style.push("cursor: pointer;");
  330. style.push("position: absolute; top: " + pos.y + "px; left: " + pos.x + "px;");
  331. style.push("width: " + this.width_ + "px; height: " + this.height_ + "px;");
  332. return style.join("");
  333. };
  334. /**
  335. * Returns the position at which to place the DIV depending on the latlng.
  336. *
  337. * @param {google.maps.LatLng} latlng The position in latlng.
  338. * @return {google.maps.Point} The position in pixels.
  339. */
  340. ClusterIcon.prototype.getPosFromLatLng_ = function(latlng) {
  341. var pos = this.getProjection().fromLatLngToDivPixel(latlng);
  342. pos.x -= this.anchorIcon_[1];
  343. pos.y -= this.anchorIcon_[0];
  344. pos.x = parseInt(pos.x, 10);
  345. pos.y = parseInt(pos.y, 10);
  346. return pos;
  347. };
  348. /**
  349. * Creates a single cluster that manages a group of proximate markers.
  350. * Used internally, do not call this constructor directly.
  351. * @constructor
  352. * @param {MarkerClusterer} mc The <code>MarkerClusterer</code> object with which this
  353. * cluster is associated.
  354. */
  355. function Cluster(mc) {
  356. this.markerClusterer_ = mc;
  357. this.map_ = mc.getMap();
  358. this.gridSize_ = mc.getGridSize();
  359. this.minClusterSize_ = mc.getMinimumClusterSize();
  360. this.averageCenter_ = mc.getAverageCenter();
  361. this.hideLabel_ = mc.getHideLabel();
  362. this.markers_ = [];
  363. this.center_ = null;
  364. this.bounds_ = null;
  365. this.clusterIcon_ = new ClusterIcon(this, mc.getStyles());
  366. }
  367. /**
  368. * Returns the number of markers managed by the cluster. You can call this from
  369. * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
  370. * for the <code>MarkerClusterer</code> object.
  371. *
  372. * @return {number} The number of markers in the cluster.
  373. */
  374. Cluster.prototype.getSize = function() {
  375. return this.markers_.length;
  376. };
  377. /**
  378. * Returns the array of markers managed by the cluster. You can call this from
  379. * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
  380. * for the <code>MarkerClusterer</code> object.
  381. *
  382. * @return {Array} The array of markers in the cluster.
  383. */
  384. Cluster.prototype.getMarkers = function() {
  385. return this.markers_;
  386. };
  387. /**
  388. * Returns the center of the cluster. You can call this from
  389. * a <code>click</code>, <code>mouseover</code>, or <code>mouseout</code> event handler
  390. * for the <code>MarkerClusterer</code> object.
  391. *
  392. * @return {google.maps.LatLng} The center of the cluster.
  393. */
  394. Cluster.prototype.getCenter = function() {
  395. return this.center_;
  396. };
  397. /**
  398. * Returns the map with which the cluster is associated.
  399. *
  400. * @return {google.maps.Map} The map.
  401. * @ignore
  402. */
  403. Cluster.prototype.getMap = function() {
  404. return this.map_;
  405. };
  406. /**
  407. * Returns the <code>MarkerClusterer</code> object with which the cluster is associated.
  408. *
  409. * @return {MarkerClusterer} The associated marker clusterer.
  410. * @ignore
  411. */
  412. Cluster.prototype.getMarkerClusterer = function() {
  413. return this.markerClusterer_;
  414. };
  415. /**
  416. * Returns the bounds of the cluster.
  417. *
  418. * @return {google.maps.LatLngBounds} the cluster bounds.
  419. * @ignore
  420. */
  421. Cluster.prototype.getBounds = function() {
  422. var i;
  423. var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
  424. var markers = this.getMarkers();
  425. for (i = 0; i < markers.length; i++) {
  426. bounds.extend(markers[i].getPosition());
  427. }
  428. return bounds;
  429. };
  430. /**
  431. * Removes the cluster from the map.
  432. *
  433. * @ignore
  434. */
  435. Cluster.prototype.remove = function() {
  436. this.clusterIcon_.setMap(null);
  437. this.markers_ = [];
  438. delete this.markers_;
  439. };
  440. /**
  441. * Adds a marker to the cluster.
  442. *
  443. * @param {google.maps.Marker} marker The marker to be added.
  444. * @return {boolean} True if the marker was added.
  445. * @ignore
  446. */
  447. Cluster.prototype.addMarker = function(marker) {
  448. var i;
  449. var mCount;
  450. var mz;
  451. if (this.isMarkerAlreadyAdded_(marker)) {
  452. return false;
  453. }
  454. if (!this.center_) {
  455. this.center_ = marker.getPosition();
  456. this.calculateBounds_();
  457. } else {
  458. if (this.averageCenter_) {
  459. var l = this.markers_.length + 1;
  460. var lat = (this.center_.lat() * (l - 1) + marker.getPosition().lat()) / l;
  461. var lng = (this.center_.lng() * (l - 1) + marker.getPosition().lng()) / l;
  462. this.center_ = new google.maps.LatLng(lat, lng);
  463. this.calculateBounds_();
  464. }
  465. }
  466. marker.isAdded = true;
  467. this.markers_.push(marker);
  468. mCount = this.markers_.length;
  469. mz = this.markerClusterer_.getMaxZoom();
  470. if (mz !== null && this.map_.getZoom() > mz) {
  471. // Zoomed in past max zoom, so show the marker.
  472. if (marker.getMap() !== this.map_) {
  473. marker.setMap(this.map_);
  474. }
  475. } else if (mCount < this.minClusterSize_) {
  476. // Min cluster size not reached so show the marker.
  477. if (marker.getMap() !== this.map_) {
  478. marker.setMap(this.map_);
  479. }
  480. } else if (mCount === this.minClusterSize_) {
  481. // Hide the markers that were showing.
  482. for (i = 0; i < mCount; i++) {
  483. this.markers_[i].setMap(null);
  484. }
  485. } else {
  486. marker.setMap(null);
  487. }
  488. return true;
  489. };
  490. /**
  491. * Determines if a marker lies within the cluster's bounds.
  492. *
  493. * @param {google.maps.Marker} marker The marker to check.
  494. * @return {boolean} True if the marker lies in the bounds.
  495. * @ignore
  496. */
  497. Cluster.prototype.isMarkerInClusterBounds = function(marker) {
  498. return this.bounds_.contains(marker.getPosition());
  499. };
  500. /**
  501. * Calculates the extended bounds of the cluster with the grid.
  502. */
  503. Cluster.prototype.calculateBounds_ = function() {
  504. var bounds = new google.maps.LatLngBounds(this.center_, this.center_);
  505. this.bounds_ = this.markerClusterer_.getExtendedBounds(bounds);
  506. };
  507. /**
  508. * Updates the cluster icon.
  509. */
  510. Cluster.prototype.updateIcon_ = function() {
  511. var mCount = this.markers_.length;
  512. var mz = this.markerClusterer_.getMaxZoom();
  513. if (mz !== null && this.map_.getZoom() > mz) {
  514. this.clusterIcon_.hide();
  515. return;
  516. }
  517. if (mCount < this.minClusterSize_) {
  518. // Min cluster size not yet reached.
  519. this.clusterIcon_.hide();
  520. return;
  521. }
  522. var numStyles = this.markerClusterer_.getStyles().length;
  523. var sums = this.markerClusterer_.getCalculator()(this.markers_, numStyles);
  524. this.clusterIcon_.setCenter(this.center_);
  525. this.clusterIcon_.useStyle(sums);
  526. this.clusterIcon_.show();
  527. };
  528. /**
  529. * Determines if a marker has already been added to the cluster.
  530. *
  531. * @param {google.maps.Marker} marker The marker to check.
  532. * @return {boolean} True if the marker has already been added.
  533. */
  534. Cluster.prototype.isMarkerAlreadyAdded_ = function(marker) {
  535. for (var i = 0, n = this.markers_.length; i < n; i++) {
  536. if (marker === this.markers_[i]) {
  537. return true;
  538. }
  539. }
  540. return false;
  541. };
  542. /**
  543. * @name MarkerClustererOptions
  544. * @class This class represents the optional parameter passed to
  545. * the {@link MarkerClusterer} constructor.
  546. * @property {number} [gridSize=60] The grid size of a cluster in pixels. The grid is a square.
  547. * @property {number} [maxZoom=null] The maximum zoom level at which clustering is enabled or
  548. * <code>null</code> if clustering is to be enabled at all zoom levels.
  549. * @property {boolean} [zoomOnClick=true] Whether to zoom the map when a cluster marker is
  550. * clicked. You may want to set this to <code>false</code> if you have installed a handler
  551. * for the <code>click</code> event and it deals with zooming on its own.
  552. * @property {boolean} [averageCenter=false] Whether the position of a cluster marker should be
  553. * the average position of all markers in the cluster. If set to <code>false</code>, the
  554. * cluster marker is positioned at the location of the first marker added to the cluster.
  555. * @property {number} [minimumClusterSize=2] The minimum number of markers needed in a cluster
  556. * before the markers are hidden and a cluster marker appears.
  557. * @property {boolean} [ignoreHidden=false] Whether to ignore hidden markers in clusters. You
  558. * may want to set this to <code>true</code> to ensure that hidden markers are not included
  559. * in the marker count that appears on a cluster marker (this count is the value of the
  560. * <code>text</code> property of the result returned by the default <code>calculator</code>).
  561. * If set to <code>true</code> and you change the visibility of a marker being clustered, be
  562. * sure to also call <code>MarkerClusterer.repaint()</code>.
  563. * @property {string} [title=""] The tooltip to display when the mouse moves over a cluster
  564. * marker. (Alternatively, you can use a custom <code>calculator</code> function to specify a
  565. * different tooltip for each cluster marker.)
  566. * @property {function} [calculator=MarkerClusterer.CALCULATOR] The function used to determine
  567. * the text to be displayed on a cluster marker and the index indicating which style to use
  568. * for the cluster marker. The input parameters for the function are (1) the array of markers
  569. * represented by a cluster marker and (2) the number of cluster icon styles. It returns a
  570. * {@link ClusterIconInfo} object. The default <code>calculator</code> returns a
  571. * <code>text</code> property which is the number of markers in the cluster and an
  572. * <code>index</code> property which is one higher than the lowest integer such that
  573. * <code>10^i</code> exceeds the number of markers in the cluster, or the size of the styles
  574. * array, whichever is less. The <code>styles</code> array element used has an index of
  575. * <code>index</code> minus 1. For example, the default <code>calculator</code> returns a
  576. * <code>text</code> value of <code>"125"</code> and an <code>index</code> of <code>3</code>
  577. * for a cluster icon representing 125 markers so the element used in the <code>styles</code>
  578. * array is <code>2</code>. A <code>calculator</code> may also return a <code>title</code>
  579. * property that contains the text of the tooltip to be used for the cluster marker. If
  580. * <code>title</code> is not defined, the tooltip is set to the value of the <code>title</code>
  581. * property for the MarkerClusterer.
  582. * @property {string} [clusterClass="cluster"] The name of the CSS class defining general styles
  583. * for the cluster markers. Use this class to define CSS styles that are not set up by the code
  584. * that processes the <code>styles</code> array.
  585. * @property {Array} [styles] An array of {@link ClusterIconStyle} elements defining the styles
  586. * of the cluster markers to be used. The element to be used to style a given cluster marker
  587. * is determined by the function defined by the <code>calculator</code> property.
  588. * The default is an array of {@link ClusterIconStyle} elements whose properties are derived
  589. * from the values for <code>imagePath</code>, <code>imageExtension</code>, and
  590. * <code>imageSizes</code>.
  591. * @property {boolean} [enableRetinaIcons=false] Whether to allow the use of cluster icons that
  592. * have sizes that are some multiple (typically double) of their actual display size. Icons such
  593. * as these look better when viewed on high-resolution monitors such as Apple's Retina displays.
  594. * Note: if this property is <code>true</code>, sprites cannot be used as cluster icons.
  595. * @property {number} [batchSize=MarkerClusterer.BATCH_SIZE] Set this property to the
  596. * number of markers to be processed in a single batch when using a browser other than
  597. * Internet Explorer (for Internet Explorer, use the batchSizeIE property instead).
  598. * @property {number} [batchSizeIE=MarkerClusterer.BATCH_SIZE_IE] When Internet Explorer is
  599. * being used, markers are processed in several batches with a small delay inserted between
  600. * each batch in an attempt to avoid Javascript timeout errors. Set this property to the
  601. * number of markers to be processed in a single batch; select as high a number as you can
  602. * without causing a timeout error in the browser. This number might need to be as low as 100
  603. * if 15,000 markers are being managed, for example.
  604. * @property {string} [imagePath=MarkerClusterer.IMAGE_PATH]
  605. * The full URL of the root name of the group of image files to use for cluster icons.
  606. * The complete file name is of the form <code>imagePath</code>n.<code>imageExtension</code>
  607. * where n is the image file number (1, 2, etc.).
  608. * @property {string} [imageExtension=MarkerClusterer.IMAGE_EXTENSION]
  609. * The extension name for the cluster icon image files (e.g., <code>"png"</code> or
  610. * <code>"jpg"</code>).
  611. * @property {Array} [imageSizes=MarkerClusterer.IMAGE_SIZES]
  612. * An array of numbers containing the widths of the group of
  613. * <code>imagePath</code>n.<code>imageExtension</code> image files.
  614. * (The images are assumed to be square.)
  615. */
  616. /**
  617. * Creates a MarkerClusterer object with the options specified in {@link MarkerClustererOptions}.
  618. * @constructor
  619. * @extends google.maps.OverlayView
  620. * @param {google.maps.Map} map The Google map to attach to.
  621. * @param {Array.<google.maps.Marker>} [opt_markers] The markers to be added to the cluster.
  622. * @param {MarkerClustererOptions} [opt_options] The optional parameters.
  623. */
  624. function MarkerClusterer(map, opt_markers, opt_options) {
  625. // MarkerClusterer implements google.maps.OverlayView interface. We use the
  626. // extend function to extend MarkerClusterer with google.maps.OverlayView
  627. // because it might not always be available when the code is defined so we
  628. // look for it at the last possible moment. If it doesn't exist now then
  629. // there is no point going ahead :)
  630. this.extend(MarkerClusterer, google.maps.OverlayView);
  631. opt_markers = opt_markers || [];
  632. opt_options = opt_options || {};
  633. this.markers_ = [];
  634. this.clusters_ = [];
  635. this.listeners_ = [];
  636. this.activeMap_ = null;
  637. this.ready_ = false;
  638. this.gridSize_ = opt_options.gridSize || 60;
  639. this.minClusterSize_ = opt_options.minimumClusterSize || 2;
  640. this.maxZoom_ = opt_options.maxZoom || null;
  641. this.styles_ = opt_options.styles || [];
  642. this.title_ = opt_options.title || "";
  643. this.zoomOnClick_ = true;
  644. if (opt_options.zoomOnClick !== undefined) {
  645. this.zoomOnClick_ = opt_options.zoomOnClick;
  646. }
  647. this.averageCenter_ = false;
  648. if (opt_options.averageCenter !== undefined) {
  649. this.averageCenter_ = opt_options.averageCenter;
  650. }
  651. this.ignoreHidden_ = false;
  652. if (opt_options.ignoreHidden !== undefined) {
  653. this.ignoreHidden_ = opt_options.ignoreHidden;
  654. }
  655. this.enableRetinaIcons_ = false;
  656. if (opt_options.enableRetinaIcons !== undefined) {
  657. this.enableRetinaIcons_ = opt_options.enableRetinaIcons;
  658. }
  659. this.hideLabel_ = false;
  660. if (opt_options.hideLabel !== undefined) {
  661. this.hideLabel_ = opt_options.hideLabel;
  662. }
  663. this.imagePath_ = opt_options.imagePath || MarkerClusterer.IMAGE_PATH;
  664. this.imageExtension_ = opt_options.imageExtension || MarkerClusterer.IMAGE_EXTENSION;
  665. this.imageSizes_ = opt_options.imageSizes || MarkerClusterer.IMAGE_SIZES;
  666. this.calculator_ = opt_options.calculator || MarkerClusterer.CALCULATOR;
  667. this.batchSize_ = opt_options.batchSize || MarkerClusterer.BATCH_SIZE;
  668. this.batchSizeIE_ = opt_options.batchSizeIE || MarkerClusterer.BATCH_SIZE_IE;
  669. this.clusterClass_ = opt_options.clusterClass || "cluster";
  670. if (navigator.userAgent.toLowerCase().indexOf("msie") !== -1) {
  671. // Try to avoid IE timeout when processing a huge number of markers:
  672. this.batchSize_ = this.batchSizeIE_;
  673. }
  674. this.setupStyles_();
  675. this.addMarkers(opt_markers, true);
  676. this.setMap(map); // Note: this causes onAdd to be called
  677. }
  678. /**
  679. * Implementation of the onAdd interface method.
  680. * @ignore
  681. */
  682. MarkerClusterer.prototype.onAdd = function() {
  683. var cMarkerClusterer = this;
  684. this.activeMap_ = this.getMap();
  685. this.ready_ = true;
  686. this.repaint();
  687. // Add the map event listeners
  688. this.listeners_ = [
  689. google.maps.event.addListener(this.getMap(), "zoom_changed", function() {
  690. cMarkerClusterer.resetViewport_(false);
  691. // Workaround for this Google bug: when map is at level 0 and "-" of
  692. // zoom slider is clicked, a "zoom_changed" event is fired even though
  693. // the map doesn't zoom out any further. In this situation, no "idle"
  694. // event is triggered so the cluster markers that have been removed
  695. // do not get redrawn. Same goes for a zoom in at maxZoom.
  696. if (this.getZoom() === (this.get("minZoom") || 0) || this.getZoom() === this.get("maxZoom")) {
  697. google.maps.event.trigger(this, "idle");
  698. }
  699. }),
  700. google.maps.event.addListener(this.getMap(), "idle", function() {
  701. cMarkerClusterer.redraw_();
  702. })
  703. ];
  704. };
  705. /**
  706. * Implementation of the onRemove interface method.
  707. * Removes map event listeners and all cluster icons from the DOM.
  708. * All managed markers are also put back on the map.
  709. * @ignore
  710. */
  711. MarkerClusterer.prototype.onRemove = function() {
  712. var i;
  713. // Put all the managed markers back on the map:
  714. for (i = 0; i < this.markers_.length; i++) {
  715. if (this.markers_[i].getMap() !== this.activeMap_) {
  716. this.markers_[i].setMap(this.activeMap_);
  717. }
  718. }
  719. // Remove all clusters:
  720. for (i = 0; i < this.clusters_.length; i++) {
  721. this.clusters_[i].remove();
  722. }
  723. this.clusters_ = [];
  724. // Remove map event listeners:
  725. for (i = 0; i < this.listeners_.length; i++) {
  726. google.maps.event.removeListener(this.listeners_[i]);
  727. }
  728. this.listeners_ = [];
  729. this.activeMap_ = null;
  730. this.ready_ = false;
  731. };
  732. /**
  733. * Implementation of the draw interface method.
  734. * @ignore
  735. */
  736. MarkerClusterer.prototype.draw = function() {};
  737. /**
  738. * Sets up the styles object.
  739. */
  740. MarkerClusterer.prototype.setupStyles_ = function() {
  741. var i, size;
  742. if (this.styles_.length > 0) {
  743. return;
  744. }
  745. for (i = 0; i < this.imageSizes_.length; i++) {
  746. size = this.imageSizes_[i];
  747. this.styles_.push({
  748. url: this.imagePath_ + (i + 1) + "." + this.imageExtension_,
  749. height: size,
  750. width: size
  751. });
  752. }
  753. };
  754. /**
  755. * Fits the map to the bounds of the markers managed by the clusterer.
  756. */
  757. MarkerClusterer.prototype.fitMapToMarkers = function() {
  758. var i;
  759. var markers = this.getMarkers();
  760. var bounds = new google.maps.LatLngBounds();
  761. for (i = 0; i < markers.length; i++) {
  762. bounds.extend(markers[i].getPosition());
  763. }
  764. this.getMap().fitBounds(bounds);
  765. };
  766. /**
  767. * Returns the value of the <code>gridSize</code> property.
  768. *
  769. * @return {number} The grid size.
  770. */
  771. MarkerClusterer.prototype.getGridSize = function() {
  772. return this.gridSize_;
  773. };
  774. /**
  775. * Sets the value of the <code>gridSize</code> property.
  776. *
  777. * @param {number} gridSize The grid size.
  778. */
  779. MarkerClusterer.prototype.setGridSize = function(gridSize) {
  780. this.gridSize_ = gridSize;
  781. };
  782. /**
  783. * Returns the value of the <code>minimumClusterSize</code> property.
  784. *
  785. * @return {number} The minimum cluster size.
  786. */
  787. MarkerClusterer.prototype.getMinimumClusterSize = function() {
  788. return this.minClusterSize_;
  789. };
  790. /**
  791. * Sets the value of the <code>minimumClusterSize</code> property.
  792. *
  793. * @param {number} minimumClusterSize The minimum cluster size.
  794. */
  795. MarkerClusterer.prototype.setMinimumClusterSize = function(minimumClusterSize) {
  796. this.minClusterSize_ = minimumClusterSize;
  797. };
  798. /**
  799. * Returns the value of the <code>maxZoom</code> property.
  800. *
  801. * @return {number} The maximum zoom level.
  802. */
  803. MarkerClusterer.prototype.getMaxZoom = function() {
  804. return this.maxZoom_;
  805. };
  806. /**
  807. * Sets the value of the <code>maxZoom</code> property.
  808. *
  809. * @param {number} maxZoom The maximum zoom level.
  810. */
  811. MarkerClusterer.prototype.setMaxZoom = function(maxZoom) {
  812. this.maxZoom_ = maxZoom;
  813. };
  814. /**
  815. * Returns the value of the <code>styles</code> property.
  816. *
  817. * @return {Array} The array of styles defining the cluster markers to be used.
  818. */
  819. MarkerClusterer.prototype.getStyles = function() {
  820. return this.styles_;
  821. };
  822. /**
  823. * Sets the value of the <code>styles</code> property.
  824. *
  825. * @param {Array.<ClusterIconStyle>} styles The array of styles to use.
  826. */
  827. MarkerClusterer.prototype.setStyles = function(styles) {
  828. this.styles_ = styles;
  829. };
  830. /**
  831. * Returns the value of the <code>title</code> property.
  832. *
  833. * @return {string} The content of the title text.
  834. */
  835. MarkerClusterer.prototype.getTitle = function() {
  836. return this.title_;
  837. };
  838. /**
  839. * Sets the value of the <code>title</code> property.
  840. *
  841. * @param {string} title The value of the title property.
  842. */
  843. MarkerClusterer.prototype.setTitle = function(title) {
  844. this.title_ = title;
  845. };
  846. /**
  847. * Returns the value of the <code>zoomOnClick</code> property.
  848. *
  849. * @return {boolean} True if zoomOnClick property is set.
  850. */
  851. MarkerClusterer.prototype.getZoomOnClick = function() {
  852. return this.zoomOnClick_;
  853. };
  854. /**
  855. * Sets the value of the <code>zoomOnClick</code> property.
  856. *
  857. * @param {boolean} zoomOnClick The value of the zoomOnClick property.
  858. */
  859. MarkerClusterer.prototype.setZoomOnClick = function(zoomOnClick) {
  860. this.zoomOnClick_ = zoomOnClick;
  861. };
  862. /**
  863. * Returns the value of the <code>averageCenter</code> property.
  864. *
  865. * @return {boolean} True if averageCenter property is set.
  866. */
  867. MarkerClusterer.prototype.getAverageCenter = function() {
  868. return this.averageCenter_;
  869. };
  870. /**
  871. * Sets the value of the <code>averageCenter</code> property.
  872. *
  873. * @param {boolean} averageCenter The value of the averageCenter property.
  874. */
  875. MarkerClusterer.prototype.setAverageCenter = function(averageCenter) {
  876. this.averageCenter_ = averageCenter;
  877. };
  878. /**
  879. * Returns the value of the <code>ignoreHidden</code> property.
  880. *
  881. * @return {boolean} True if ignoreHidden property is set.
  882. */
  883. MarkerClusterer.prototype.getIgnoreHidden = function() {
  884. return this.ignoreHidden_;
  885. };
  886. /**
  887. * Sets the value of the <code>ignoreHidden</code> property.
  888. *
  889. * @param {boolean} ignoreHidden The value of the ignoreHidden property.
  890. */
  891. MarkerClusterer.prototype.setIgnoreHidden = function(ignoreHidden) {
  892. this.ignoreHidden_ = ignoreHidden;
  893. };
  894. /**
  895. * Returns the value of the <code>enableRetinaIcons</code> property.
  896. *
  897. * @return {boolean} True if enableRetinaIcons property is set.
  898. */
  899. MarkerClusterer.prototype.getEnableRetinaIcons = function() {
  900. return this.enableRetinaIcons_;
  901. };
  902. /**
  903. * Sets the value of the <code>enableRetinaIcons</code> property.
  904. *
  905. * @param {boolean} enableRetinaIcons The value of the enableRetinaIcons property.
  906. */
  907. MarkerClusterer.prototype.setEnableRetinaIcons = function(enableRetinaIcons) {
  908. this.enableRetinaIcons_ = enableRetinaIcons;
  909. };
  910. /**
  911. * Returns the value of the <code>imageExtension</code> property.
  912. *
  913. * @return {string} The value of the imageExtension property.
  914. */
  915. MarkerClusterer.prototype.getImageExtension = function() {
  916. return this.imageExtension_;
  917. };
  918. /**
  919. * Sets the value of the <code>imageExtension</code> property.
  920. *
  921. * @param {string} imageExtension The value of the imageExtension property.
  922. */
  923. MarkerClusterer.prototype.setImageExtension = function(imageExtension) {
  924. this.imageExtension_ = imageExtension;
  925. };
  926. /**
  927. * Returns the value of the <code>imagePath</code> property.
  928. *
  929. * @return {string} The value of the imagePath property.
  930. */
  931. MarkerClusterer.prototype.getImagePath = function() {
  932. return this.imagePath_;
  933. };
  934. /**
  935. * Sets the value of the <code>imagePath</code> property.
  936. *
  937. * @param {string} imagePath The value of the imagePath property.
  938. */
  939. MarkerClusterer.prototype.setImagePath = function(imagePath) {
  940. this.imagePath_ = imagePath;
  941. };
  942. /**
  943. * Returns the value of the <code>imageSizes</code> property.
  944. *
  945. * @return {Array} The value of the imageSizes property.
  946. */
  947. MarkerClusterer.prototype.getImageSizes = function() {
  948. return this.imageSizes_;
  949. };
  950. /**
  951. * Sets the value of the <code>imageSizes</code> property.
  952. *
  953. * @param {Array} imageSizes The value of the imageSizes property.
  954. */
  955. MarkerClusterer.prototype.setImageSizes = function(imageSizes) {
  956. this.imageSizes_ = imageSizes;
  957. };
  958. /**
  959. * Returns the value of the <code>calculator</code> property.
  960. *
  961. * @return {function} the value of the calculator property.
  962. */
  963. MarkerClusterer.prototype.getCalculator = function() {
  964. return this.calculator_;
  965. };
  966. /**
  967. * Sets the value of the <code>calculator</code> property.
  968. *
  969. * @param {function(Array.<google.maps.Marker>, number)} calculator The value
  970. * of the calculator property.
  971. */
  972. MarkerClusterer.prototype.setCalculator = function(calculator) {
  973. this.calculator_ = calculator;
  974. };
  975. /**
  976. * Sets the value of the <code>hideLabel</code> property.
  977. *
  978. * @param {boolean} printable The value of the hideLabel property.
  979. */
  980. MarkerClusterer.prototype.setHideLabel = function(hideLabel) {
  981. this.hideLabel_ = hideLabel;
  982. };
  983. /**
  984. * Returns the value of the <code>hideLabel</code> property.
  985. *
  986. * @return {boolean} the value of the hideLabel property.
  987. */
  988. MarkerClusterer.prototype.getHideLabel = function() {
  989. return this.hideLabel_;
  990. };
  991. /**
  992. * Returns the value of the <code>batchSizeIE</code> property.
  993. *
  994. * @return {number} the value of the batchSizeIE property.
  995. */
  996. MarkerClusterer.prototype.getBatchSizeIE = function() {
  997. return this.batchSizeIE_;
  998. };
  999. /**
  1000. * Sets the value of the <code>batchSizeIE</code> property.
  1001. *
  1002. * @param {number} batchSizeIE The value of the batchSizeIE property.
  1003. */
  1004. MarkerClusterer.prototype.setBatchSizeIE = function(batchSizeIE) {
  1005. this.batchSizeIE_ = batchSizeIE;
  1006. };
  1007. /**
  1008. * Returns the value of the <code>clusterClass</code> property.
  1009. *
  1010. * @return {string} the value of the clusterClass property.
  1011. */
  1012. MarkerClusterer.prototype.getClusterClass = function() {
  1013. return this.clusterClass_;
  1014. };
  1015. /**
  1016. * Sets the value of the <code>clusterClass</code> property.
  1017. *
  1018. * @param {string} clusterClass The value of the clusterClass property.
  1019. */
  1020. MarkerClusterer.prototype.setClusterClass = function(clusterClass) {
  1021. this.clusterClass_ = clusterClass;
  1022. };
  1023. /**
  1024. * Returns the array of markers managed by the clusterer.
  1025. *
  1026. * @return {Array} The array of markers managed by the clusterer.
  1027. */
  1028. MarkerClusterer.prototype.getMarkers = function() {
  1029. return this.markers_;
  1030. };
  1031. /**
  1032. * Returns the number of markers managed by the clusterer.
  1033. *
  1034. * @return {number} The number of markers.
  1035. */
  1036. MarkerClusterer.prototype.getTotalMarkers = function() {
  1037. return this.markers_.length;
  1038. };
  1039. /**
  1040. * Returns the current array of clusters formed by the clusterer.
  1041. *
  1042. * @return {Array} The array of clusters formed by the clusterer.
  1043. */
  1044. MarkerClusterer.prototype.getClusters = function() {
  1045. return this.clusters_;
  1046. };
  1047. /**
  1048. * Returns the number of clusters formed by the clusterer.
  1049. *
  1050. * @return {number} The number of clusters formed by the clusterer.
  1051. */
  1052. MarkerClusterer.prototype.getTotalClusters = function() {
  1053. return this.clusters_.length;
  1054. };
  1055. /**
  1056. * Adds a marker to the clusterer. The clusters are redrawn unless
  1057. * <code>opt_nodraw</code> is set to <code>true</code>.
  1058. *
  1059. * @param {google.maps.Marker} marker The marker to add.
  1060. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
  1061. */
  1062. MarkerClusterer.prototype.addMarker = function(marker, opt_nodraw) {
  1063. this.pushMarkerTo_(marker);
  1064. if (!opt_nodraw) {
  1065. this.redraw_();
  1066. }
  1067. };
  1068. /**
  1069. * Adds an array of markers to the clusterer. The clusters are redrawn unless
  1070. * <code>opt_nodraw</code> is set to <code>true</code>.
  1071. *
  1072. * @param {Array.<google.maps.Marker>} markers The markers to add.
  1073. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
  1074. */
  1075. MarkerClusterer.prototype.addMarkers = function(markers, opt_nodraw) {
  1076. var key;
  1077. for (key in markers) {
  1078. if (markers.hasOwnProperty(key)) {
  1079. this.pushMarkerTo_(markers[key]);
  1080. }
  1081. }
  1082. if (!opt_nodraw) {
  1083. this.redraw_();
  1084. }
  1085. };
  1086. /**
  1087. * Pushes a marker to the clusterer.
  1088. *
  1089. * @param {google.maps.Marker} marker The marker to add.
  1090. */
  1091. MarkerClusterer.prototype.pushMarkerTo_ = function(marker) {
  1092. // If the marker is draggable add a listener so we can update the clusters on the dragend:
  1093. // if (marker.getDraggable()) {
  1094. // var cMarkerClusterer = this;
  1095. // google.maps.event.addListener(marker, "dragend", function() {
  1096. // if (cMarkerClusterer.ready_) {
  1097. // this.isAdded = false;
  1098. // cMarkerClusterer.repaint();
  1099. // }
  1100. // });
  1101. // }
  1102. marker.isAdded = false;
  1103. this.markers_.push(marker);
  1104. };
  1105. /**
  1106. * Removes a marker from the cluster and map. The clusters are redrawn unless
  1107. * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if the
  1108. * marker was removed from the clusterer.
  1109. *
  1110. * @param {google.maps.Marker} marker The marker to remove.
  1111. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
  1112. * @param {boolean} [opt_noMapRemove] Set to <code>true</code> to prevent removal from map but still removing from cluster management
  1113. * @return {boolean} True if the marker was removed from the clusterer.
  1114. */
  1115. MarkerClusterer.prototype.removeMarker = function(marker, opt_nodraw, opt_noMapRemove) {
  1116. var removeFromMap = true && !opt_noMapRemove;
  1117. var removed = this.removeMarker_(marker, removeFromMap);
  1118. if (!opt_nodraw && removed) {
  1119. this.repaint();
  1120. }
  1121. return removed;
  1122. };
  1123. /**
  1124. * Removes an array of markers from the cluster and map. The clusters are redrawn unless
  1125. * <code>opt_nodraw</code> is set to <code>true</code>. Returns <code>true</code> if markers
  1126. * were removed from the clusterer.
  1127. *
  1128. * @param {Array.<google.maps.Marker>} markers The markers to remove.
  1129. * @param {boolean} [opt_nodraw] Set to <code>true</code> to prevent redrawing.
  1130. * @param {boolean} [opt_noMapRemove] Set to <code>true</code> to prevent removal from map but still removing from cluster management
  1131. * @return {boolean} True if markers were removed from the clusterer.
  1132. */
  1133. MarkerClusterer.prototype.removeMarkers = function(markers, opt_nodraw, opt_noMapRemove) {
  1134. var i, r;
  1135. var removed = false;
  1136. var removeFromMap = true && !opt_noMapRemove;
  1137. for (i = 0; i < markers.length; i++) {
  1138. r = this.removeMarker_(markers[i], removeFromMap);
  1139. removed = removed || r;
  1140. }
  1141. if (!opt_nodraw && removed) {
  1142. this.repaint();
  1143. }
  1144. return removed;
  1145. };
  1146. /**
  1147. * Removes a marker and returns true if removed, false if not.
  1148. *
  1149. * @param {google.maps.Marker} marker The marker to remove
  1150. * @param {boolean} removeFromMap set to <code>true</code> to explicitly remove from map as well as cluster manangement
  1151. * @return {boolean} Whether the marker was removed or not
  1152. */
  1153. MarkerClusterer.prototype.removeMarker_ = function(marker, removeFromMap) {
  1154. var i;
  1155. var index = -1;
  1156. if (this.markers_.indexOf) {
  1157. index = this.markers_.indexOf(marker);
  1158. } else {
  1159. for (i = 0; i < this.markers_.length; i++) {
  1160. if (marker === this.markers_[i]) {
  1161. index = i;
  1162. break;
  1163. }
  1164. }
  1165. }
  1166. if (index === -1) {
  1167. // Marker is not in our list of markers, so do nothing:
  1168. return false;
  1169. }
  1170. if (removeFromMap) {
  1171. marker.setMap(null);
  1172. }
  1173. this.markers_.splice(index, 1); // Remove the marker from the list of managed markers
  1174. return true;
  1175. };
  1176. /**
  1177. * Removes all clusters and markers from the map and also removes all markers
  1178. * managed by the clusterer.
  1179. */
  1180. MarkerClusterer.prototype.clearMarkers = function() {
  1181. this.resetViewport_(true);
  1182. this.markers_ = [];
  1183. };
  1184. /**
  1185. * Recalculates and redraws all the marker clusters from scratch.
  1186. * Call this after changing any properties.
  1187. */
  1188. MarkerClusterer.prototype.repaint = function() {
  1189. var oldClusters = this.clusters_.slice();
  1190. this.clusters_ = [];
  1191. this.resetViewport_(false);
  1192. this.redraw_();
  1193. // Remove the old clusters.
  1194. // Do it in a timeout to prevent blinking effect.
  1195. setTimeout(function() {
  1196. var i;
  1197. for (i = 0; i < oldClusters.length; i++) {
  1198. oldClusters[i].remove();
  1199. }
  1200. }, 0);
  1201. };
  1202. /**
  1203. * Returns the current bounds extended by the grid size.
  1204. *
  1205. * @param {google.maps.LatLngBounds} bounds The bounds to extend.
  1206. * @return {google.maps.LatLngBounds} The extended bounds.
  1207. * @ignore
  1208. */
  1209. MarkerClusterer.prototype.getExtendedBounds = function(bounds) {
  1210. var projection = this.getProjection();
  1211. // Turn the bounds into latlng.
  1212. var tr = new google.maps.LatLng(bounds.getNorthEast().lat(),
  1213. bounds.getNorthEast().lng());
  1214. var bl = new google.maps.LatLng(bounds.getSouthWest().lat(),
  1215. bounds.getSouthWest().lng());
  1216. // Convert the points to pixels and the extend out by the grid size.
  1217. var trPix = projection.fromLatLngToDivPixel(tr);
  1218. trPix.x += this.gridSize_;
  1219. trPix.y -= this.gridSize_;
  1220. var blPix = projection.fromLatLngToDivPixel(bl);
  1221. blPix.x -= this.gridSize_;
  1222. blPix.y += this.gridSize_;
  1223. // Convert the pixel points back to LatLng
  1224. var ne = projection.fromDivPixelToLatLng(trPix);
  1225. var sw = projection.fromDivPixelToLatLng(blPix);
  1226. // Extend the bounds to contain the new bounds.
  1227. bounds.extend(ne);
  1228. bounds.extend(sw);
  1229. return bounds;
  1230. };
  1231. /**
  1232. * Redraws all the clusters.
  1233. */
  1234. MarkerClusterer.prototype.redraw_ = function() {
  1235. this.createClusters_(0);
  1236. };
  1237. /**
  1238. * Removes all clusters from the map. The markers are also removed from the map
  1239. * if <code>opt_hide</code> is set to <code>true</code>.
  1240. *
  1241. * @param {boolean} [opt_hide] Set to <code>true</code> to also remove the markers
  1242. * from the map.
  1243. */
  1244. MarkerClusterer.prototype.resetViewport_ = function(opt_hide) {
  1245. var i, marker;
  1246. // Remove all the clusters
  1247. for (i = 0; i < this.clusters_.length; i++) {
  1248. this.clusters_[i].remove();
  1249. }
  1250. this.clusters_ = [];
  1251. // Reset the markers to not be added and to be removed from the map.
  1252. for (i = 0; i < this.markers_.length; i++) {
  1253. marker = this.markers_[i];
  1254. marker.isAdded = false;
  1255. if (opt_hide) {
  1256. marker.setMap(null);
  1257. }
  1258. }
  1259. };
  1260. /**
  1261. * Calculates the distance between two latlng locations in km.
  1262. *
  1263. * @param {google.maps.LatLng} p1 The first lat lng point.
  1264. * @param {google.maps.LatLng} p2 The second lat lng point.
  1265. * @return {number} The distance between the two points in km.
  1266. * @see http://www.movable-type.co.uk/scripts/latlong.html
  1267. */
  1268. MarkerClusterer.prototype.distanceBetweenPoints_ = function(p1, p2) {
  1269. var R = 6371; // Radius of the Earth in km
  1270. var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
  1271. var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
  1272. var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
  1273. Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
  1274. Math.sin(dLon / 2) * Math.sin(dLon / 2);
  1275. var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  1276. var d = R * c;
  1277. return d;
  1278. };
  1279. /**
  1280. * Determines if a marker is contained in a bounds.
  1281. *
  1282. * @param {google.maps.Marker} marker The marker to check.
  1283. * @param {google.maps.LatLngBounds} bounds The bounds to check against.
  1284. * @return {boolean} True if the marker is in the bounds.
  1285. */
  1286. MarkerClusterer.prototype.isMarkerInBounds_ = function(marker, bounds) {
  1287. var northEast = bounds.getNorthEast();
  1288. var southWest = bounds.getSouthWest();
  1289. var position = marker.getPosition();
  1290. var minX, maxX, minY, maxY;
  1291. minX = southWest.lat();
  1292. maxX = northEast.lat();
  1293. minY = southWest.lng();
  1294. maxY = northEast.lng();
  1295. while (0 > maxY)
  1296. maxY += 180;
  1297. maxY += 180;
  1298. // bounds[this.a].g = maxY;? what for
  1299. if (minX < position.lat() && position.lat() < maxX &&
  1300. minY < position.lng() && position.lng() < maxY) {
  1301. return true;
  1302. }
  1303. return false;
  1304. };
  1305. /**
  1306. * Adds a marker to a cluster, or creates a new cluster.
  1307. *
  1308. * @param {google.maps.Marker} marker The marker to add.
  1309. */
  1310. MarkerClusterer.prototype.addToClosestCluster_ = function(marker) {
  1311. var i, d, cluster, center;
  1312. var distance = 40000; // Some large number
  1313. var clusterToAddTo = null;
  1314. for (i = 0; i < this.clusters_.length; i++) {
  1315. cluster = this.clusters_[i];
  1316. center = cluster.getCenter();
  1317. if (center) {
  1318. d = this.distanceBetweenPoints_(center, marker.getPosition());
  1319. if (d < distance) {
  1320. distance = d;
  1321. clusterToAddTo = cluster;
  1322. }
  1323. }
  1324. }
  1325. if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
  1326. clusterToAddTo.addMarker(marker);
  1327. } else {
  1328. cluster = new Cluster(this);
  1329. cluster.addMarker(marker);
  1330. this.clusters_.push(cluster);
  1331. }
  1332. };
  1333. /**
  1334. * Creates the clusters. This is done in batches to avoid timeout errors
  1335. * in some browsers when there is a huge number of markers.
  1336. *
  1337. * @param {number} iFirst The index of the first marker in the batch of
  1338. * markers to be added to clusters.
  1339. */
  1340. MarkerClusterer.prototype.createClusters_ = function(iFirst) {
  1341. var i, marker;
  1342. var mapBounds;
  1343. var cMarkerClusterer = this;
  1344. if (!this.ready_) {
  1345. return;
  1346. }
  1347. // Cancel previous batch processing if we're working on the first batch:
  1348. if (iFirst === 0) {
  1349. /**
  1350. * This event is fired when the <code>MarkerClusterer</code> begins
  1351. * clustering markers.
  1352. * @name MarkerClusterer#clusteringbegin
  1353. * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
  1354. * @event
  1355. */
  1356. google.maps.event.trigger(this, "clusteringbegin", this);
  1357. if (typeof this.timerRefStatic !== "undefined") {
  1358. clearTimeout(this.timerRefStatic);
  1359. delete this.timerRefStatic;
  1360. }
  1361. }
  1362. // Get our current map view bounds.
  1363. // Create a new bounds object so we don't affect the map.
  1364. //
  1365. // See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
  1366. if (this.getMap().getZoom() > 3) {
  1367. mapBounds = new google.maps.LatLngBounds(this.getMap().getBounds().getSouthWest(),
  1368. this.getMap().getBounds().getNorthEast());
  1369. } else {
  1370. mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
  1371. }
  1372. var bounds = this.getExtendedBounds(mapBounds);
  1373. // console.log(bounds);
  1374. var iLast = Math.min(iFirst + this.batchSize_, this.markers_.length);
  1375. for (i = iFirst; i < iLast; i++) {
  1376. this.markers_[i];
  1377. if (this.markers_.isFilter === true) {
  1378. if (this.markers_[i].isFilter === undefined) {
  1379. if (this.markers_[i].setMap !== undefined)
  1380. this.markers_[i].setMap(null);
  1381. continue;
  1382. }
  1383. }
  1384. if (!this.markers_[i].isAdded && this.isMarkerInBounds_(this.markers_[i], bounds)) {
  1385. if (!this.ignoreHidden_ || (this.ignoreHidden_ && this.markers_[i].getVisible())) {
  1386. if (this.markers_[i].getMap === undefined)
  1387. this.markers_[i] = this.addOrtherMarker(this.markers_[i]);
  1388. this.addToClosestCluster_(this.markers_[i]);
  1389. }
  1390. }
  1391. }
  1392. if (iLast < this.markers_.length) {
  1393. this.timerRefStatic = setTimeout(function() {
  1394. cMarkerClusterer.createClusters_(iLast);
  1395. }, 0);
  1396. } else {
  1397. delete this.timerRefStatic;
  1398. /**
  1399. * This event is fired when the <code>MarkerClusterer</code> stops
  1400. * clustering markers.
  1401. * @name MarkerClusterer#clusteringend
  1402. * @param {MarkerClusterer} mc The MarkerClusterer whose markers are being clustered.
  1403. * @event
  1404. */
  1405. google.maps.event.trigger(this, "clusteringend", this);
  1406. for (i = 0; i < this.clusters_.length; i++) {
  1407. this.clusters_[i].updateIcon_();
  1408. }
  1409. }
  1410. };
  1411. MarkerClusterer.prototype.addOrtherMarker = function(data) {
  1412. var self = this;
  1413. var position = [data.lat, data.lng];
  1414. var color, tooltip;
  1415. if (typeof testVariable !== "undefined")
  1416. color = systemconfig.markerColor;
  1417. if (data.color)
  1418. color = data.color;
  1419. if (data.tooltip)
  1420. tooltip = data.tooltip;
  1421. var image = {
  1422. path: "M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z",
  1423. // This marker is 20 pixels wide by 32 pixels high.
  1424. scaledSize: new google.maps.Size(24, 24),
  1425. // The origin for this image is (0, 0).
  1426. origin: new google.maps.Point(0, 0),
  1427. // The anchor for this image is the base of the flagpole at (0, 32).
  1428. anchor: new google.maps.Point(12, 12),
  1429. fillColor: color,
  1430. fillOpacity: 1,
  1431. strokeColor: "white",
  1432. strokeWeight: 4
  1433. };
  1434. var marker = new google.maps.Marker({
  1435. position: new google.maps.LatLng(position[0], position[1]),
  1436. draggable: false,
  1437. icon: image,
  1438. zIndex: 2
  1439. });
  1440. if (tooltip) {
  1441. var style = {
  1442. maxWidth: 350
  1443. }
  1444. var content = "";
  1445. if (typeof tooltip == "object") {
  1446. if (tooltip.style)
  1447. style = tooltip.style;
  1448. if (tooltip.element)
  1449. content = tooltip.element;
  1450. } else
  1451. content = tooltip;
  1452. var infowindow = new google.maps.InfoWindow(style);
  1453. google.maps.event.addListener(marker, 'mouseover', function() {
  1454. infowindow.setContent(content);
  1455. infowindow.open(self.map_, marker);
  1456. });
  1457. google.maps.event.addListener(marker, 'mouseout', function(event) {
  1458. infowindow.close();
  1459. });
  1460. }
  1461. marker.dataMarker = data;
  1462. marker.isFilter = data.isFilter;
  1463. return marker;
  1464. }
  1465. /**
  1466. * Extends an object's prototype by another's.
  1467. *
  1468. * @param {Object} obj1 The object to be extended.
  1469. * @param {Object} obj2 The object to extend with.
  1470. * @return {Object} The new extended object.
  1471. * @ignore
  1472. */
  1473. MarkerClusterer.prototype.extend = function(obj1, obj2) {
  1474. return (function(object) {
  1475. var property;
  1476. for (property in object.prototype) {
  1477. this.prototype[property] = object.prototype[property];
  1478. }
  1479. return this;
  1480. }).apply(obj1, [obj2]);
  1481. };
  1482. /**
  1483. * The default function for determining the label text and style
  1484. * for a cluster icon.
  1485. *
  1486. * @param {Array.<google.maps.Marker>} markers The array of markers represented by the cluster.
  1487. * @param {number} numStyles The number of marker styles available.
  1488. * @return {ClusterIconInfo} The information resource for the cluster.
  1489. * @constant
  1490. * @ignore
  1491. */
  1492. MarkerClusterer.CALCULATOR = function(markers, numStyles) {
  1493. var index = 0;
  1494. var title = "";
  1495. var count = markers.length.toString();
  1496. var dv = count;
  1497. while (dv !== 0) {
  1498. dv = parseInt(dv / 10, 10);
  1499. index++;
  1500. }
  1501. index = Math.min(index, numStyles);
  1502. return {
  1503. text: count,
  1504. index: index,
  1505. title: title
  1506. };
  1507. };
  1508. /**
  1509. * The number of markers to process in one batch.
  1510. *
  1511. * @type {number}
  1512. * @constant
  1513. */
  1514. MarkerClusterer.BATCH_SIZE = 2000;
  1515. /**
  1516. * The number of markers to process in one batch (IE only).
  1517. *
  1518. * @type {number}
  1519. * @constant
  1520. */
  1521. MarkerClusterer.BATCH_SIZE_IE = 500;
  1522. /**
  1523. * The default root name for the marker cluster images.
  1524. *
  1525. * @type {string}
  1526. * @constant
  1527. */
  1528. MarkerClusterer.IMAGE_PATH = "//cdn.rawgit.com/mahnunchik/markerclustererplus/master/images/m";
  1529. /**
  1530. * The default extension name for the marker cluster images.
  1531. *
  1532. * @type {string}
  1533. * @constant
  1534. */
  1535. MarkerClusterer.IMAGE_EXTENSION = "png";
  1536. /**
  1537. * The default array of sizes for the marker cluster images.
  1538. *
  1539. * @type {Array.<number>}
  1540. * @constant
  1541. */
  1542. MarkerClusterer.IMAGE_SIZES = [53, 56, 66, 78, 90];
  1543. if (typeof String.prototype.trim !== 'function') {
  1544. /**
  1545. * IE hack since trim() doesn't exist in all browsers
  1546. * @return {string} The string with removed whitespace
  1547. */
  1548. String.prototype.trim = function() {
  1549. return this.replace(/^\s+|\s+$/g, '');
  1550. };
  1551. }
  1552. window.MarkerClusterer = MarkerClusterer;
  1553. export default MarkerClusterer;