forked from timeu/google-map-markerclusterer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
google-map-markerclusterer.html
479 lines (432 loc) · 16.7 KB
/
google-map-markerclusterer.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
<link rel="import" href="../polymer/polymer-element.html">
<link rel="import" href="google-map-overlayview-behavior.html">
<link rel="import" href="google-map-markercluster.html">
<link rel="import" href="google-map-defaulticon.html">
<link rel="import" href="../polymer/lib/utils/debounce.html">
<link rel="import" href="../polymer/lib/utils/flattened-nodes-observer.html">
<dom-module id="google-map-markerclusterer">
<template><slot id="clustericontemplate" name="cluster-icon"></slot></template>
<script>
/* global google */
/* global Markerclusterer */
(function() {
/*
* The `google-map-markerclusterer` element is a port of markercluster-plus to polymer.
* It helps to cluster markers on a google-map together
* ##### Example
* <google-map-markerclusterer></google-map-markerclusterer>
*
* ##### Example - custom cluster marker
*
* <google-map-markerclusterer>
* <my-custom-clustericon class="cluster-icon"></my-custom-clustericon>
* </google-map-markerclusterer>
*
*
* @customElement
* @polymer
* @demo demo/index.html
* @demo demo/simple.html
*/
class GoogleMapMarkerclusterer extends GoogleMapOverlayViewBehavior(Polymer.Element) {
static get is() { return 'google-map-markerclusterer'; }
/**
* Fired when the clustering of the markers starts.
* @event google-map-markercluster-clustering-start
*/
/**
* Fired when the clustering of the markers ends.
* @event google-map-markercluster-clustering-end
*/
/**
* Fired when the mouse enters the area of the cluster.
* @param {google.maps.MouseEvent} event The mouse event.
* @event google-map-markercluster-mouseover
*/
/**
* Fired when the mouse leaves the area of the cluster.
* @param {google.maps.MouseEvent} event The mouse event.
* @event google-map-markercluster-mouseout
*/
/**
* Fired when the cluster was clicked.
* @param {google.maps.MouseEvent} event The mouse event.
* @event google-map-markercluster-click
*/
static get properties() {
return {
/**
* Markers that should be clustered.
*/
markers: {
type:Array,
value: function() {return [];},
observer:'_markersChanged'
},
/**
* If set, the zoom level is set such that all markers (google-map-marker children) are brought into view.
*/
fitToMarkers: {
type: Boolean,
value: false,
observer: '_fitToMarkersChanged'
},
/**
* BatchSize specifies the amount of markers that should be processed per run.
*/
batchSize : {
type: Number,
value: 2000
},
/**
* If set ignores hidden markers when creating the clusters.
*/
ignoreHidden: {
type: Boolean,
value: false
},
/**
* Specifies the size of the grid for each cluster in pixel.
*/
gridSize:{
type: Number,
value: 60
},
/**
* Sepcifies the minimum number of markers to be clustered.
*/
minimumClusterSize : {
type: Number,
value: 2
},
/**
* If set, the center of the cluster is set to the average of all locations of its containing markers.
* Otherwise the cluster center will be the one of the first marker added to it.
*/
averageCenter : {
type: Boolean,
value: false
},
/**
* Specifies the maximum zoom at which individual markers are shown.
* By default no maxZoom is set.
*/
maxZoom : {
type: Number,
value: null
},
/**
* If set, the map is zoomed far enough that all markers of the cluster fit inside the viewport (Default: true).
*/
zoomOnClick: {
type:Boolean,
value:true
},
/**
* Styles for the google-map-defaulticon element.
*/
styles : {
type: Array,
value: null,
observer:'_changeStyles'
}
}
}
static get observers() {
return [
'_optionChanged(gridSize,averageCenter,minimumClusterSize,maxZoom)'
]
}
constructor() {
super();
this.clusters = [];
this.listeners = [];
// TODO move to overlayview behavior
this.isReady = false;
this._clusterIconTemplate = null;
}
ready() {
super.ready();
this._boundHandler = this._initClusterIconTemplate.bind(this);
setTimeout(this._boundHandler);
//this.$.clustericontemplate.addEventListener('slotchange', this._boundHandler); # not possible because we take it out of the slot and add it below to the google-map-markercluster
}
_initClusterIconTemplate() {
var clusterIconTemplateContent = this.$.clustericontemplate.assignedNodes({flatten:true})
.filter(n => n.nodeType === Node.ELEMENT_NODE);
if (clusterIconTemplateContent.length > 0) {
clusterIconTemplateContent = clusterIconTemplateContent[0];
clusterIconTemplateContent.removeAttribute("slot");
}
else {
clusterIconTemplateContent = document.createElement('google-map-defaulticon');
}
this._clusterIconTemplate = document.createElement('google-map-markercluster');
this._clusterIconTemplate.appendChild(clusterIconTemplateContent);
}
/**
* Calculates the distance between two latlng locations in km.
*
* @param {google.maps.LatLng} p1 The first lat lng point.
* @param {google.maps.LatLng} p2 The second lat lng point.
* @return {number} The distance between the two points in km.
* @see http://www.movable-type.co.uk/scripts/latlong.html
*/
_distanceBetweenPoints(p1, p2) {
var R = 6371; // Radius of the Earth in km
var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
/**
* Returns if the marker is inside the specified bounds
*/
_isMarkerInBounds(marker, bounds) {
return bounds.contains(marker.getPosition());
}
/**
* Called when the markerclusterer is added to the map.
* Events are initialized.
*/
onAdd() {
var mc = this;
this.isReady = true;
this._repaintDebouncer = Polymer.Debouncer.debounce(this._repaintDebouncer, Polymer.Async.timeOut.after(250), this.repaint.bind(this));
// Add the map event listeners
this.listeners = [
google.maps.event.addListener(this.map, 'zoom_changed', function () {
mc._resetClusters();
// Workaround for this Google bug: when map is at level 0 and "-" of
// zoom slider is clicked, a "zoom_changed" event is fired even though
// the map doesn't zoom out any further. In this situation, no "idle"
// event is triggered so the cluster markers that have been removed
// do not get redrawn. Same goes for a zoom in at maxZoom.
if (this.getZoom() === (this.get('minZoom') || 0) || this.getZoom() === this.get('maxZoom')) {
//google.maps.event.trigger(this, "idle");
}
}),
google.maps.event.addListener(this.map, 'idle', function () {
this._computeClusters(0);
}.bind(this))
];
}
/**
* Adds a marker to a cluster, or creates a new cluster.
*/
_addToClosestCluster(marker) {
var i, d, cluster, center;
var distance = 40000; // Some large number
var clusterToAddTo = null;
for (i = 0; i < this.clusters.length; i++) {
cluster = this.clusters[i];
center = cluster.center;
if (center) {
d = this._distanceBetweenPoints(center, marker.getPosition());
if (d < distance) {
distance = d;
clusterToAddTo = cluster;
}
}
}
if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
clusterToAddTo.addMarker(marker);
} else {
cluster = this._clusterIconTemplate.cloneNode(true);
cluster._enableProperties();
//this.shadowRoot.appendChild(cluster);
// WORKAROUND for
/*var defaultIcon = cluster.querySelector('google-map-defaulticon');
if (defaultIcon) {
defaultIcon.styles = this.styles;
}*/
cluster.styles = this.styles;
cluster.map = this.map;
cluster.minimumClusterSize = this.minimumClusterSize;
cluster.maxZoom = this.maxZoom;
cluster.gridSize = this.gridSize;
cluster.zoomOnClick = this.zoomOnClick;
cluster.averageCenter = this.averageCenter;
cluster.addMarker(marker);
this.clusters.push(cluster);
}
}
/**
* Creates the clusters. This is done in batches to avoid timeout errors
* in some browsers when there is a huge number of markers.
*
* @param {number} iFirst The index of the first marker in the batch of
* markers to be added to clusters.
*/
_computeClusters(iFirst) {
var i, marker;
var mapBounds;
var mc = this;
if (!this.isReady || !this.markers) {
return;
}
// Cancel previous batch processing if we're working on the first batch:
if (iFirst === 0) {
this.dispatchEvent(new CustomEvent('google-map-markercluster-clustering-start', { bubbles: true, composed: true }));
if (typeof this.timerRefStatic !== 'undefined') {
clearTimeout(this.timerRefStatic);
delete this.timerRefStatic;
}
}
// Get our current map view bounds.
// Create a new bounds object so we don't affect the map.
//
// See Comments 9 & 11 on Issue 3651 relating to this workaround for a Google Maps bug:
if (this.map.getZoom() > 3) {
mapBounds = new google.maps.LatLngBounds(this.map.getBounds().getSouthWest(),
this.map.getBounds().getNorthEast());
} else {
mapBounds = new google.maps.LatLngBounds(new google.maps.LatLng(85.02070771743472, -178.48388434375), new google.maps.LatLng(-85.08136444384544, 178.00048865625));
}
var bounds = this.getExtendedBounds(mapBounds,this.gridSize);
var iLast = Math.min(iFirst + this.batchSize, this.markers.length);
for (i = iFirst; i < iLast; i++) {
marker = this.markers[i];
if (!marker.isAdded && this._isMarkerInBounds(marker, bounds)) {
if (!this.ignoreHidden || (this.ignoreHidden && marker.getVisible())) {
this._addToClosestCluster(marker);
}
}
}
if (iLast < this.markers.length) {
this.timerRefStatic = setTimeout(function () {
mc._computeClusters(iLast);
}, 0);
} else {
delete this.timerRefStatic;
this.dispatchEvent(new CustomEvent('google-map-markercluster-clustering-end', { bubbles: true, composed: true }));
}
}
/**
* Callback that is called when the markerclusterer is removed from the map.
* This will put all clustered markers back on the map
*/
onRemove() {
// Put all the managed markers back on the map:
for (var i = 0, m; m = this.markers[i]; ++i) {
if (m.getMap() !== this.map) {
m.setMap(this.map);
}
}
}
/**
* Observer function that is called when `fitToMarkers` is changed.
*/
_fitToMarkersChanged() {
// TODO(ericbidelman): respect user's zoom level.
if (this.map && this.fitToMarkers) {
var latLngBounds = new google.maps.LatLngBounds();
for (var i = 0, m; m = this.markers[i]; ++i) {
latLngBounds.extend(
new google.maps.LatLng(m.latitude, m.longitude));
}
// For one marker, don't alter zoom, just center it.
if (this.markers.length > 1) {
this.map.fitBounds(latLngBounds);
}
this.map.setCenter(latLngBounds.getCenter());
}
}
/**
* Observer function that is called if one of the options is changed.
* Debounce calls to `repaint`
*/
_optionChanged(markers,gridSize,averageCenter,minimumClusterSize,maxZoom) {
this._repaintDebouncer = Polymer.Debouncer.debounce(this._repaintDebouncer, Polymer.Async.timeOut.after(250), this.repaint.bind(this));
}
/**
* Repaint will re-create and re-draw the clusters.
*/
repaint() {
this._resetClusters();
this._computeClusters(0);
}
/**
* Removes the clusters and resets the markers.
*/
_resetClusters() {
// Remove all the clusters
for (var i = 0; i < this.clusters.length; i++) {
this.clusters[i].map = null;
}
this.clusters = [];
this._resetMarkers(false,this.markers);
}
/**
* Initializes the markers and setups dragend event if markers is draggable.
*/
_initMarkers(markers) {
var mc = this;
var dragendFunc = function() {
if (mc.isReady) {
this.isAdded = false;
mc.repaint();
}
};
for (var i =0;i<markers.length;i++) {
var marker = markers[i];
if (marker.getDraggable()) {
google.maps.event.addListener(marker, 'dragend', dragendFunc);
}
marker.isAdded = false;
}
}
/**
* this will reset the marker.
* @param {Boolean} opt_hide specifies if the markers should be removed entirely from the map.
* @param {Array} markers the markers that should be reset
*/
_resetMarkers(optHide,markers) {
if (!markers) {
return;
}
for (var i = 0; i < markers.length; i++) {
var marker = markers[i];
marker.isAdded = false;
if (optHide) {
marker.setMap(null);
}
}
}
/**
* Observer function that is called when the `markers` Array is changed.
* Will reset the current markers and debounce call to `repaint`
*/
_markersChanged(newMarkers,oldMarkers) {
// remove the old markers
if (oldMarkers) {
this._resetMarkers(true,oldMarkers);
}
this._initMarkers(newMarkers);
this._repaintDebouncer = Polymer.Debouncer.debounce(this._repaintDebouncer, Polymer.Async.timeOut.after(250),this.repaint.bind(this));
}
/**
* Observer function that is called when the styles are changed.
* Only used when the `google-map-defaulticon` is used.
*/
_changeStyles(styles) {
if (!this._clusterIconTemplate) {
return;
}
var defaultIcon = this._clusterIconTemplate.querySelector('google-map-defaulticon');
if (defaultIcon) {
defaultIcon.styles = styles;
for (var i = 0; i < this.clusters.length; i++) {
this.clusters[i].firstElementChild.styles = styles;
}
}
}
}
customElements.define('google-map-markerclusterer', GoogleMapMarkerclusterer);
})();
</script>
</dom-module>