forked from jbdemonte/gmap3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgmap3.js
2513 lines (2318 loc) · 74.2 KB
/
gmap3.js
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* GMAP3 Plugin for JQuery
* Version : 5.1.1
* Date : 2013-05-25
* Licence : GPL v3 : http://www.gnu.org/licenses/gpl.html
* Author : DEMONTE Jean-Baptiste
* Contact : jbdemonte@gmail.com
* Web site : http://gmap3.net
*
* Copyright (c) 2010-2012 Jean-Baptiste DEMONTE
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* - Neither the name of the author nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
;(function ($, undef) {
/***************************************************************************/
/* GMAP3 DEFAULTS */
/***************************************************************************/
// defaults are defined later in the code to pass the rails asset pipeline and
//jasmine while google library is not loaded
var defaults, gId = 0;
function initDefaults() {
if (!defaults) {
defaults = {
verbose: false,
queryLimit: {
attempt: 5,
delay: 250, // setTimeout(..., delay + random);
random: 250
},
classes: {
Map : google.maps.Map,
Marker : google.maps.Marker,
InfoWindow : google.maps.InfoWindow,
Circle : google.maps.Circle,
Rectangle : google.maps.Rectangle,
OverlayView : google.maps.OverlayView,
StreetViewPanorama: google.maps.StreetViewPanorama,
KmlLayer : google.maps.KmlLayer,
TrafficLayer : google.maps.TrafficLayer,
BicyclingLayer : google.maps.BicyclingLayer,
GroundOverlay : google.maps.GroundOverlay,
StyledMapType : google.maps.StyledMapType,
ImageMapType : google.maps.ImageMapType
},
map: {
mapTypeId : google.maps.MapTypeId.ROADMAP,
center: [46.578498, 2.457275],
zoom: 2
},
overlay: {
pane: "floatPane",
content: "",
offset: {
x: 0,
y: 0
}
},
geoloc: {
getCurrentPosition: {
maximumAge: 60000,
timeout: 5000
}
}
}
}
}
function globalId(id, simulate){
return id !== undef ? id : "gmap3_" + (simulate ? gId + 1 : ++gId);
}
/**
* Return true if current version of Google Maps is equal or above to these in parameter
* @param version {string} Minimal version required
* @return {Boolean}
*/
function googleVersionMin(version) {
var i,
gmVersion = google.maps.version.split(".");
version = version.split(".");
for(i = 0; i < gmVersion.length; i++) {
gmVersion[i] = parseInt(gmVersion[i], 10);
}
for(i = 0; i < version.length; i++) {
version[i] = parseInt(version[i], 10);
if (gmVersion.hasOwnProperty(i)) {
if (gmVersion[i] < version[i]) {
return false;
}
} else {
return false;
}
}
return true;
}
/**
* attach events from a container to a sender
* todo[
* events => { eventName => function, }
* onces => { eventName => function, }
* data => mixed data
* ]
**/
function attachEvents($container, args, sender, id, senders){
if (args.todo.events || args.todo.onces) {
var context = {
id: id,
data: args.todo.data,
tag: args.todo.tag
};
if (args.todo.events){
$.each(args.todo.events, function(name, f){
var that = $container, fn = f;
if ($.isArray(f)) {
that = f[0];
fn = f[1]
}
google.maps.event.addListener(sender, name, function(event) {
fn.apply(that, [senders ? senders : sender, event, context]);
});
});
}
if (args.todo.onces){
$.each(args.todo.onces, function(name, f){
var that = $container, fn = f;
if ($.isArray(f)) {
that = f[0];
fn = f[1]
}
google.maps.event.addListenerOnce(sender, name, function(event) {
fn.apply(that, [senders ? senders : sender, event, context]);
});
});
}
}
}
/***************************************************************************/
/* STACK */
/***************************************************************************/
function Stack (){
var st = [];
this.empty = function (){
return !st.length;
};
this.add = function(v){
st.push(v);
};
this.get = function (){
return st.length ? st[0] : false;
};
this.ack = function (){
st.shift();
};
}
/***************************************************************************/
/* TASK */
/***************************************************************************/
function Task(ctx, onEnd, todo){
var session = {},
that = this,
current,
resolve = {
latLng:{ // function => bool (=> address = latLng)
map:false,
marker:false,
infowindow:false,
circle:false,
overlay: false,
getlatlng: false,
getmaxzoom: false,
getelevation: false,
streetviewpanorama: false,
getaddress: true
},
geoloc:{
getgeoloc: true
}
};
if (typeof todo === "string"){
todo = unify(todo);
}
function unify(todo){
var result = {};
result[todo] = {};
return result;
}
function next(){
var k;
for(k in todo){
if (k in session){ // already run
continue;
}
return k;
}
}
this.run = function (){
var k, opts;
while(k = next()){
if (typeof ctx[k] === "function"){
current = k;
opts = $.extend(true, {}, defaults[k] || {}, todo[k].options || {});
if (k in resolve.latLng){
if (todo[k].values){
resolveAllLatLng(todo[k].values, ctx, ctx[k], {todo:todo[k], opts:opts, session:session});
} else {
resolveLatLng(ctx, ctx[k], resolve.latLng[k], {todo:todo[k], opts:opts, session:session});
}
} else if (k in resolve.geoloc){
geoloc(ctx, ctx[k], {todo:todo[k], opts:opts, session:session});
} else {
ctx[k].apply(ctx, [{todo:todo[k], opts:opts, session:session}]);
}
return; // wait until ack
} else {
session[k] = null;
}
}
onEnd.apply(ctx, [todo, session]);
};
this.ack = function(result){
session[current] = result;
that.run.apply(that, []);
};
}
function getKeys(obj){
var k, keys = [];
for(k in obj){
keys.push(k);
}
return keys;
}
function tuple(args, value){
var todo = {};
// "copy" the common data
if (args.todo){
for(var k in args.todo){
if ((k !== "options") && (k !== "values")){
todo[k] = args.todo[k];
}
}
}
// "copy" some specific keys from value first else args.todo
var i, keys = ["data", "tag", "id", "events", "onces"];
for(i=0; i<keys.length; i++){
copyKey(todo, keys[i], value, args.todo);
}
// create an extended options
todo.options = $.extend({}, args.opts || {}, value.options || {});
return todo;
}
/**
* copy a key content
**/
function copyKey(target, key){
for(var i=2; i<arguments.length; i++){
if (key in arguments[i]){
target[key] = arguments[i][key];
return;
}
}
}
/***************************************************************************/
/* GEOCODERCACHE */
/***************************************************************************/
function GeocoderCache(){
var cache = [];
this.get = function(request){
if (cache.length){
var i, j, k, item, eq,
keys = getKeys(request);
for(i=0; i<cache.length; i++){
item = cache[i];
eq = keys.length == item.keys.length;
for(j=0; (j<keys.length) && eq; j++){
k = keys[j];
eq = k in item.request;
if (eq){
if ((typeof request[k] === "object") && ("equals" in request[k]) && (typeof request[k] === "function")){
eq = request[k].equals(item.request[k]);
} else{
eq = request[k] === item.request[k];
}
}
}
if (eq){
return item.results;
}
}
}
};
this.store = function(request, results){
cache.push({request:request, keys:getKeys(request), results:results});
};
}
/***************************************************************************/
/* OVERLAYVIEW */
/***************************************************************************/
function OverlayView(map, opts, latLng, $div) {
var that = this, listeners = [];
defaults.classes.OverlayView.call(this);
this.setMap(map);
this.onAdd = function() {
var panes = this.getPanes();
if (opts.pane in panes) {
$(panes[opts.pane]).append($div);
}
$.each("dblclick click mouseover mousemove mouseout mouseup mousedown".split(" "), function(i, name){
listeners.push(
google.maps.event.addDomListener($div[0], name, function(e) {
$.Event(e).stopPropagation();
google.maps.event.trigger(that, name, [e]);
that.draw();
})
);
});
listeners.push(
google.maps.event.addDomListener($div[0], "contextmenu", function(e) {
$.Event(e).stopPropagation();
google.maps.event.trigger(that, "rightclick", [e]);
that.draw();
})
);
};
this.getPosition = function(){
return latLng;
};
this.draw = function() {
var ps = this.getProjection().fromLatLngToDivPixel(latLng);
$div
.css("left", (ps.x+opts.offset.x) + "px")
.css("top" , (ps.y+opts.offset.y) + "px");
};
this.onRemove = function() {
for (var i = 0; i < listeners.length; i++) {
google.maps.event.removeListener(listeners[i]);
}
$div.remove();
};
this.hide = function() {
$div.hide();
};
this.show = function() {
$div.show();
};
this.toggle = function() {
if ($div) {
if ($div.is(":visible")){
this.show();
} else {
this.hide();
}
}
};
this.toggleDOM = function() {
if (this.getMap()) {
this.setMap(null);
} else {
this.setMap(map);
}
};
this.getDOMElement = function() {
return $div[0];
};
}
/***************************************************************************/
/* CLUSTERING */
/***************************************************************************/
/**
* Usefull to get a projection
* => done in a function, to let dead-code analyser works without google library loaded
**/
function newEmptyOverlay(map, radius){
function Overlay(){
this.onAdd = function(){};
this.onRemove = function(){};
this.draw = function(){};
return defaults.classes.OverlayView.apply(this, []);
}
Overlay.prototype = defaults.classes.OverlayView.prototype;
var obj = new Overlay();
obj.setMap(map);
return obj;
}
/**
* Class InternalClusterer
* This class manage clusters thanks to "todo" objects
*
* Note:
* Individuals marker are created on the fly thanks to the todo objects, they are
* first set to null to keep the indexes synchronised with the todo list
* This is the "display" function, set by the gmap3 object, which uses theses data
* to create markers when clusters are not required
* To remove a marker, the objects are deleted and set not null in arrays
* markers[key]
* = null : marker exist but has not been displayed yet
* = false : marker has been removed
**/
function InternalClusterer($container, map, raw){
var updating = false,
updated = false,
redrawing = false,
ready = false,
enabled = true,
that = this,
events = [],
store = {}, // combin of index (id1-id2-...) => object
ids = {}, // unique id => index
idxs = {}, // index => unique id
markers = [], // index => marker
todos = [], // index => todo or null if removed
values = [], // index => value
overlay = newEmptyOverlay(map, raw.radius),
timer, projection,
ffilter, fdisplay, ferror; // callback function
main();
function prepareMarker(index) {
if (!markers[index]) {
delete todos[index].options.map;
markers[index] = new defaults.classes.Marker(todos[index].options);
attachEvents($container, {todo: todos[index]}, markers[index], todos[index].id);
}
}
/**
* return a marker by its id, null if not yet displayed and false if no exist or removed
**/
this.getById = function(id){
if (id in ids) {
prepareMarker(ids[id]);
return markers[ids[id]];
}
return false;
};
/**
* remove one object from the store
**/
this.rm = function (id) {
var index = ids[id];
if (markers[index]){ // can be null
markers[index].setMap(null);
}
delete markers[index];
markers[index] = false;
delete todos[index];
todos[index] = false;
delete values[index];
values[index] = false;
delete ids[id];
delete idxs[index];
updated = true;
};
/**
* remove a marker by its id
**/
this.clearById = function(id){
if (id in ids){
this.rm(id);
return true;
}
};
/**
* remove objects from the store
**/
this.clear = function(last, first, tag){
var start, stop, step, index, i,
list = [],
check = ftag(tag);
if (last) {
start = todos.length - 1;
stop = -1;
step = -1;
} else {
start = 0;
stop = todos.length;
step = 1;
}
for (index = start; index != stop; index += step) {
if (todos[index]) {
if (!check || check(todos[index].tag)){
list.push(idxs[index]);
if (first || last) {
break;
}
}
}
}
for (i = 0; i < list.length; i++) {
this.rm(list[i]);
}
};
// add a "marker todo" to the cluster
this.add = function(todo, value){
todo.id = globalId(todo.id);
this.clearById(todo.id);
ids[todo.id] = markers.length;
idxs[markers.length] = todo.id;
markers.push(null); // null = marker not yet created / displayed
todos.push(todo);
values.push(value);
updated = true;
};
// add a real marker to the cluster
this.addMarker = function(marker, todo){
todo = todo || {};
todo.id = globalId(todo.id);
this.clearById(todo.id);
if (!todo.options){
todo.options = {};
}
todo.options.position = marker.getPosition();
attachEvents($container, {todo:todo}, marker, todo.id);
ids[todo.id] = markers.length;
idxs[markers.length] = todo.id;
markers.push(marker);
todos.push(todo);
values.push(todo.data || {});
updated = true;
};
// return a "marker todo" by its index
this.todo = function(index){
return todos[index];
};
// return a "marker value" by its index
this.value = function(index){
return values[index];
};
// return a marker by its index
this.marker = function(index){
if (index in markers) {
prepareMarker(index);
return markers[index];
}
return false;
};
// return a marker by its index
this.markerIsSet = function(index){
return Boolean(markers[index]);
};
// store a new marker instead if the default "false"
this.setMarker = function(index, marker){
markers[index] = marker;
};
// link the visible overlay to the logical data (to hide overlays later)
this.store = function(cluster, obj, shadow){
store[cluster.ref] = {obj:obj, shadow:shadow};
};
// free all objects
this.free = function(){
for(var i = 0; i < events.length; i++){
google.maps.event.removeListener(events[i]);
}
events = [];
$.each(store, function(key){
flush(key);
});
store = {};
$.each(todos, function(i){
todos[i] = null;
});
todos = [];
$.each(markers, function(i){
if (markers[i]){ // false = removed
markers[i].setMap(null);
delete markers[i];
}
});
markers = [];
$.each(values, function(i){
delete values[i];
});
values = [];
ids = {};
idxs = {};
};
// link the display function
this.filter = function(f){
ffilter = f;
redraw();
};
// enable/disable the clustering feature
this.enable = function(value){
if (enabled != value){
enabled = value;
redraw();
}
};
// link the display function
this.display = function(f){
fdisplay = f;
};
// link the errorfunction
this.error = function(f){
ferror = f;
};
// lock the redraw
this.beginUpdate = function(){
updating = true;
};
// unlock the redraw
this.endUpdate = function(){
updating = false;
if (updated){
redraw();
}
};
// extends current bounds with internal markers
this.autofit = function(bounds){
for(var i=0; i<todos.length; i++){
if (todos[i]){
bounds.extend(todos[i].options.position);
}
}
};
// bind events
function main(){
projection = overlay.getProjection();
if (!projection){
setTimeout(function(){
main.apply(that, []);
},
25);
return;
}
ready = true;
events.push(google.maps.event.addListener(map, "zoom_changed", function(){delayRedraw();}));
events.push(google.maps.event.addListener(map, "bounds_changed", function(){delayRedraw();}));
redraw();
}
// flush overlays
function flush(key){
if (typeof store[key] === "object"){ // is overlay
if (typeof(store[key].obj.setMap) === "function") {
store[key].obj.setMap(null);
}
if (typeof(store[key].obj.remove) === "function") {
store[key].obj.remove();
}
if (typeof(store[key].shadow.remove) === "function") {
store[key].obj.remove();
}
if (typeof(store[key].shadow.setMap) === "function") {
store[key].shadow.setMap(null);
}
delete store[key].obj;
delete store[key].shadow;
} else if (markers[key]){ // marker not removed
markers[key].setMap(null);
// don't remove the marker object, it may be displayed later
}
delete store[key];
}
/**
* return the distance between 2 latLng couple into meters
* Params :
* Lat1, Lng1, Lat2, Lng2
* LatLng1, Lat2, Lng2
* Lat1, Lng1, LatLng2
* LatLng1, LatLng2
**/
function distanceInMeter(){
var lat1, lat2, lng1, lng2, e, f, g, h;
if (arguments[0] instanceof google.maps.LatLng){
lat1 = arguments[0].lat();
lng1 = arguments[0].lng();
if (arguments[1] instanceof google.maps.LatLng){
lat2 = arguments[1].lat();
lng2 = arguments[1].lng();
} else {
lat2 = arguments[1];
lng2 = arguments[2];
}
} else {
lat1 = arguments[0];
lng1 = arguments[1];
if (arguments[2] instanceof google.maps.LatLng){
lat2 = arguments[2].lat();
lng2 = arguments[2].lng();
} else {
lat2 = arguments[2];
lng2 = arguments[3];
}
}
e = Math.PI*lat1/180;
f = Math.PI*lng1/180;
g = Math.PI*lat2/180;
h = Math.PI*lng2/180;
return 1000*6371 * Math.acos(Math.min(Math.cos(e)*Math.cos(g)*Math.cos(f)*Math.cos(h)+Math.cos(e)*Math.sin(f)*Math.cos(g)*Math.sin(h)+Math.sin(e)*Math.sin(g),1));
}
// extend the visible bounds
function extendsMapBounds(){
var radius = distanceInMeter(map.getCenter(), map.getBounds().getNorthEast()),
circle = new google.maps.Circle({
center: map.getCenter(),
radius: 1.25 * radius // + 25%
});
return circle.getBounds();
}
// return an object where keys are store keys
function getStoreKeys(){
var keys = {}, k;
for(k in store){
keys[k] = true;
}
return keys;
}
// async the delay function
function delayRedraw(){
clearTimeout(timer);
timer = setTimeout(function(){
redraw();
},
25);
}
// generate bounds extended by radius
function extendsBounds(latLng) {
var p = projection.fromLatLngToDivPixel(latLng),
ne = projection.fromDivPixelToLatLng(new google.maps.Point(p.x+raw.radius, p.y-raw.radius)),
sw = projection.fromDivPixelToLatLng(new google.maps.Point(p.x-raw.radius, p.y+raw.radius));
return new google.maps.LatLngBounds(sw, ne);
}
// run the clustering process and call the display function
function redraw(){
if (updating || redrawing || !ready){
return;
}
var keys = [], used = {},
zoom = map.getZoom(),
forceDisabled = ("maxZoom" in raw) && (zoom > raw.maxZoom),
previousKeys = getStoreKeys(),
i, j, k, indexes, check = false, bounds, cluster, position, previous, lat, lng, loop;
// reset flag
updated = false;
if (zoom > 3){
// extend the bounds of the visible map to manage clusters near the boundaries
bounds = extendsMapBounds();
// check contain only if boundaries are valid
check = bounds.getSouthWest().lng() < bounds.getNorthEast().lng();
}
// calculate positions of "visibles" markers (in extended bounds)
for(i=0; i<todos.length; i++){
if (todos[i] && (!check || bounds.contains(todos[i].options.position)) && (!ffilter || ffilter(values[i]))){
keys.push(i);
}
}
// for each "visible" marker, search its neighbors to create a cluster
// we can't do a classical "for" loop, because, analysis can bypass a marker while focusing on cluster
while(1){
i=0;
while(used[i] && (i<keys.length)){ // look for the next marker not used
i++;
}
if (i == keys.length){
break;
}
indexes = [];
if (enabled && !forceDisabled){
loop = 10;
do{
previous = indexes;
indexes = [];
loop--;
if (previous.length){
position = bounds.getCenter()
} else {
position = todos[ keys[i] ].options.position;
}
bounds = extendsBounds(position);
for(j=i; j<keys.length; j++){
if (used[j]){
continue;
}
if (bounds.contains(todos[ keys[j] ].options.position)){
indexes.push(j);
}
}
} while( (previous.length < indexes.length) && (indexes.length > 1) && loop);
} else {
for(j=i; j<keys.length; j++){
if (used[j]){
continue;
}
indexes.push(j);
break;
}
}
cluster = {indexes:[], ref:[]};
lat = lng = 0;
for(k=0; k<indexes.length; k++){
used[ indexes[k] ] = true;
cluster.indexes.push(keys[indexes[k]]);
cluster.ref.push(keys[indexes[k]]);
lat += todos[ keys[indexes[k]] ].options.position.lat();
lng += todos[ keys[indexes[k]] ].options.position.lng();
}
lat /= indexes.length;
lng /= indexes.length;
cluster.latLng = new google.maps.LatLng(lat, lng);
cluster.ref = cluster.ref.join("-");
if (cluster.ref in previousKeys){ // cluster doesn't change
delete previousKeys[cluster.ref]; // remove this entry, these still in this array will be removed
} else { // cluster is new
if (indexes.length === 1){ // alone markers are not stored, so need to keep the key (else, will be displayed every time and marker will blink)
store[cluster.ref] = true;
}
fdisplay(cluster);
}
}
// flush the previous overlays which are not still used
$.each(previousKeys, function(key){
flush(key);
});
redrawing = false;
}
}
/**
* Class Clusterer
* a facade with limited method for external use
**/
function Clusterer(id, internalClusterer){
this.id = function(){
return id;
};
this.filter = function(f){
internalClusterer.filter(f);
};
this.enable = function(){
internalClusterer.enable(true);
};
this.disable = function(){
internalClusterer.enable(false);
};
this.add = function(marker, todo, lock){
if (!lock) {
internalClusterer.beginUpdate();
}
internalClusterer.addMarker(marker, todo);
if (!lock) {
internalClusterer.endUpdate();
}
};
this.getById = function(id){
return internalClusterer.getById(id);
};
this.clearById = function(id, lock){
var result;
if (!lock) {
internalClusterer.beginUpdate();
}
result = internalClusterer.clearById(id);
if (!lock) {
internalClusterer.endUpdate();
}
return result;
};
this.clear = function(last, first, tag, lock){
if (!lock) {
internalClusterer.beginUpdate();
}
internalClusterer.clear(last, first, tag);
if (!lock) {
internalClusterer.endUpdate();
}
};
}
/***************************************************************************/
/* STORE */
/***************************************************************************/
function Store(){
var store = {}, // name => [id, ...]
objects = {}; // id => object
function normalize(res) {
return {
id: res.id,
name: res.name,
object:res.obj,
tag:res.tag,
data:res.data
};
}
/**
* add a mixed to the store
**/
this.add = function(args, name, obj, sub){
var todo = args.todo || {},
id = globalId(todo.id);
if (!store[name]){
store[name] = [];
}
if (id in objects){ // object already exists: remove it
this.clearById(id);
}
objects[id] = {obj:obj, sub:sub, name:name, id:id, tag:todo.tag, data:todo.data};
store[name].push(id);