-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmap.js
2076 lines (1815 loc) · 88.8 KB
/
map.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
if(!window.console) // for very old browser
var console = { log : function(i){}}
var language = window.navigator.languages ? window.navigator.languages[0] : (window.navigator.language || window.navigator.userLanguage);
if(typeof language === 'string')
language = [ language ];
// we need to have the following languages:
// browserlang
// a short one (de instead of de-AT) if not present
// en as fallback if not present
if(language.indexOf("en") == -1)
language.push("en");
for(var i = 0; i < language.length; i++) {
if(language[i].match(/-/)) {
var short_lang = language[i].match(/^([a-zA-Z]*)-/)[1];
if(language.indexOf(short_lang) == -1) {
language.push(short_lang);
continue;
}
}
}
console.log(language);
// global texts
var attr = {
osm : 'Map data © <a href="https://openstreetmap.org/">OpenStreetMap</a> contributors - <a href="http://opendatacommons.org/licenses/odbl/">ODbL</a>',
osm_tiles : 'Tiles © OSM - <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC BY-SA</a>',
search : 'Search by OSM - <a href="http://wiki.openstreetmap.org/wiki/Nominatim">Nominatim</a>',
mapbox : 'Tiles © <a href="http://mapbox.com/about/maps/">MapBox</a>',
mapquest : 'Tiles courtesy of <a href="http://www.mapquest.com/">MapQuest</a>',
greenmap : 'Green Map Icons used by permission © <a href="http://www.greenmap.org">Green Map System 2015</a>',
overpass : 'POI via <a href="http://www.overpass-api.de/">Overpass API</a>'
}
if(!window.assethost)
var assethost = "http://demo.transformap.co/";
/*
* takes a two args: osm datatype and osm id
* if marker in field of view, toggle popup.
* zooms in if marker is hidden in cluster to get leafletMarker
*/
function MytogglePopup(osm_type,osm_id) {
disableLoadPOI = true;
var leaflet_marker = getVisibleMarker(osm_type,osm_id)
if(leaflet_marker) {
leaflet_marker.togglePopup();
setTimeout(function () {
disableLoadPOI = false;
}, 200);
return;
} //else
var target_marker;
var marker_array = markers.GetMarkers();
for(var i = 0; i < marker_array.length; i++) {
var prunecluster_marker = marker_array[i];
if(prunecluster_marker.data.type == osm_type && prunecluster_marker.data.id == osm_id) {
target_marker = prunecluster_marker;
break;
}
}
if(target_marker) {
if(map.getZoom() == map.getMaxZoom()) {
var possible_clusters = [];
map.eachLayer(function (layer) {
if(layer._population > 0)
possible_clusters.push(layer);
});
var distance = 123456789;
var nearest_cluster = null;
for(i = 0; i < possible_clusters.length; i++) {
var new_distance = calculateDistance(target_marker.position.lat, possible_clusters[i]._latlng.lat, target_marker.position.lng, possible_clusters[i]._latlng.lng);
if( new_distance < distance ) {
distance = new_distance;
nearest_cluster = possible_clusters[i];
}
}
if(!nearest_cluster) {
console.log("Error in MytogglePopup: no nearest cluster found");
disableLoadPOI = false;
return;
}
nearest_cluster.fireEvent('click');
}
else
map.setZoomAround( new L.LatLng(target_marker.position.lat, target_marker.position.lng), map.getZoom() + 1);
setTimeout(function () {
MytogglePopup(osm_type,osm_id);
}, 200);
} else {
disableLoadPOI = false;
console.log("Error in MytogglePopup: marker " + osm_type + " " + osm_id + " not found in markers.GetMarkers()");
}
}
//source: http://jsfiddle.net/vg01q7xw/
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
function calculateDistance(lat1, lat2, lon1, lon2) {
var R = 6371000; // meter
var Phi1 = lat1.toRad();
var Phi2 = lat2.toRad();
var DeltaPhi = (lat2 - lat1).toRad();
var DeltaLambda = (lon2 - lon1).toRad();
var a = Math.sin(DeltaPhi / 2) * Math.sin(DeltaPhi / 2)
+ Math.cos(Phi1) * Math.cos(Phi2) * Math.sin(DeltaLambda / 2)
* Math.sin(DeltaLambda / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d;
}
function getVisibleMarker(osm_type,osm_id) {
var my_layer = null;
map.eachLayer(function (layer) {
if(! layer._popup || ! layer.options.alt)
return;
if(layer.options.alt != (osm_type + " " + osm_id))
return;
my_layer = layer;
});
return my_layer;
}
/* this part must be in global namespace */
// fetch taxonomy, containing all translations, and implicit affiliations
// taken from Wikipedia:JSON
var taxonomy, turbolink;
var url = assethost+"taxonomy.json";
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState === done && http_request.status === ok) {
if(!window.JSON) {
// document.getElementById('map').inn("Error:cannot handle JSON");
return;
}
taxonomy = JSON.parse(http_request.responseText);
if(taxonomy) {
// add map key derived from it
for(var osmkey_counter = 0; osmkey_counter < overpass_config.icon_tags.length; osmkey_counter++) {
var osmkey = overpass_config.icon_tags[osmkey_counter];
var taxonomy_block = taxonomy[osmkey];
if (!taxonomy_block) {
console.log("no entry in taxonomy for " + osmkey);
break;
}
var entry_array = taxonomy_block['items'];
for (var i = 0; i < entry_array.length; i++ ) {
var item = entry_array[i];
for ( var osmvalue_counter = 0; osmvalue_counter < item['osm:values'].length; osmvalue_counter++ ) {
var li = $("<li>");
var new_id = item['osm:key'] + item['osm:values'][osmvalue_counter];
li.attr("onClick", "toggleInfoBox('" + new_id + "');");
li.append('<img src="'+assethost+'assets/transformap/pngs/identities/24/' + item['osm:key'] + '=' + item['osm:values'][osmvalue_counter] + '.png" /> '
+ item['label']['en']
+ '<div class=InfoBox '
+ 'id="' + new_id + '">'
+ item['description']['en'] + '</div>');
$('#mapkey').append(li);
}
}
}
if(window.filters)
createFiltersOfTaxonomy();
}
else
console.log("taxonomy not here");
}
};
http_request.send(null);
var overpass_ql_text,
overpass_query,
overpass_query_nodes,
overpass_query_ways,
overpass_query_rels,
object_type_keys = [ "amenity", "shop", "tourism", "craft", "garden:type", "leisure", "office", "man_made", "landuse", "club", "farm_boxes" ] ;
/*
* sets global the vars above
* MUST be called before first loadPOI
*/
function buildOverpassQuery() {
if(! window.overpass_config )
window.overpass_config = {};
var op_server1 = "//overpass-api.de/api/",
op_server2 = (window.parent.document.location.protocol == "https:") ? op_server1 : "http://api.openstreetmap.fr/oapi/", //fr does'n have https, ru too
op_server3 = (window.parent.document.location.protocol == "https:") ? op_server1 : "http://overpass.osm.rambler.ru/cgi/";
if(! overpass_config.timeout) overpass_config.timeout = 180;
if(! overpass_config.minzoom) overpass_config.minzoom = 12;
if(! overpass_config.servers) overpass_config.servers = [ op_server1, op_server2, op_server3 ];
if(! overpass_config.q_array) overpass_config.q_array = [ [ '"identity"' ] ];
if(! overpass_config.icon_folder) overpass_config.icon_folder = "identities";
if(! overpass_config.icon_tags) overpass_config.icon_tags = [ "identity" ];
if(! overpass_config.icon_size) overpass_config.icon_size = 24;
if(! overpass_config.class_selector_key) overpass_config.class_selector_key = { key: "" };
var overpass_urlstart = 'interpreter?data=';
var overpass_start = '[out:json][timeout:' + overpass_config.timeout + '][bbox:BBOX];';
var overpass_query_string = "";
var overpass_query_string_nodes = "";
var overpass_query_string_ways = "";
var overpass_query_string_rels = "";
for (var i = 0; i < overpass_config.q_array.length; i++) {
var anded_tags = overpass_config.q_array[i];
var anded_querystring = "";
var nr_of_and_clauses = anded_tags.length;
for (var j=0; j < nr_of_and_clauses; j++) {
anded_querystring += "[" + anded_tags[j] + "]";
}
overpass_query_string += "node" + anded_querystring + ";out;";
overpass_query_string += "(way" + anded_querystring + ";node(w));out;";
overpass_query_string += "rel" + anded_querystring + ";out;>;out;";
overpass_query_string_nodes += "node" + anded_querystring + ";out;";
overpass_query_string_ways += "(way" + anded_querystring + ";node(w));out;";
overpass_query_string_rels += "rel" + anded_querystring + ";out;>;out;";
}
overpass_ql_text = overpass_start + overpass_query_string;
overpass_query = overpass_config.servers[0] + overpass_urlstart + overpass_ql_text;
overpass_query_nodes = overpass_config.servers[0] + overpass_urlstart + overpass_start + overpass_query_string_nodes;
overpass_query_ways = overpass_config.servers[1] + overpass_urlstart + overpass_start + overpass_query_string_ways;
overpass_query_rels = overpass_config.servers[2] + overpass_urlstart + overpass_start + overpass_query_string_rels;
console.log(overpass_query_nodes);
console.log(overpass_query_ways);
console.log(overpass_query_rels);
}
var debugLayer,
map,
markers = new PruneClusterForLeaflet(60,20),
lc = {},
default_overlay = {
"POIs" : markers
};
function initMap(defaultlayer,base_maps,overlay_maps,lat,lon,zoom) {
var center = new L.LatLng(lat ? lat : 0, lon ? lon : 0);
var overriddenId = new L.Control.EditInOSM.Editors.Id({ url: "http://editor.transformap.co/#background=Bing&map=" });
var MapQuestOpen_OSM = new L.tileLayer('http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpeg', {
subdomains: '1234',
attribution: [attr.osm, attr.mapquest, attr.overpass, attr.greenmap].join(', '),
maxZoom : 19,
maxNativeZoom: 18 ,
noWrap: true
});
var osm = new L.TileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: [attr.osm, attr.osm_tiles, attr.overpass, attr.greenmap].join(', '),
maxZoom : 19,
noWrap: true
});
if(!defaultlayer)
defaultlayer = (window.parent.document.location.protocol == "https:") ? osm : MapQuestOpen_OSM;
if(!overlay_maps)
overlay_maps = default_overlay;
map = new L.Map('map', {
center: center,
zoom: zoom ? zoom : 3,
layers: defaultlayer,
editInOSMControlOptions: {
position: 'topright',
zoomThreshold: 18,
widget: 'multiButton',
editors: [overriddenId]
}
});
if(!base_maps) {
base_maps = {
'MapQuestOpen': MapQuestOpen_OSM,
'OpenSteetMap - Mapnik': osm
};
}
map.addLayer(markers);
var ctrl = new L.Control.Layers(base_maps,overlay_maps)
map.addControl(ctrl);
L.LatLngBounds.prototype.toOverpassBBoxString = function (){
var a = this._southWest,
b = this._northEast;
return [a.lat, a.lng, b.lat, b.lng].join(",");
}
var path_style = L.Path.prototype._updateStyle;
L.Path.prototype._updateStyle = function () {
path_style.apply(this);
for (k in this.options.svg) {
this._path.setAttribute(k, this.options.svg[k]);
}
}
if(window.createSideBar) {
createSideBar();
setTimeout(toggleSideBarOnLoad,200);
map.on('moveend', updatePOIlist);
if(window.filters)
map.on('moveend',updateFilterCount); // here because it is called on every map move
}
$('#map').append('<a href="https://github.com/TransforMap/transfor-map" title="Fork me on GitHub" id=forkme></a>');
$('#forkme').append('<img src="'+assethost+'assets/forkme-on-github.png" alt="Fork me on GitHub" />');
$('#map').append('<img src="'+assethost+'assets/ajax-loader.gif" id="loading_node" class="loading" />');
$('#map').append('<img src="'+assethost+'assets/ajax-loader.gif" id="loading_way" class="loading" />');
$('#map').append('<img src="'+assethost+'assets/ajax-loader.gif" id="loading_relation" class="loading" />');
$('#map').append('<div id="notificationbar">Please zoom in to update POIs!</div>');
map.on('moveend', updateLinks);
map.on('popupopen', setImageInPopup);
map.on('popupopen', setTranslationsInPopup);
var popup_param = getUrlVars()["popup"];
if(popup_param) {
open_popup_on_load.type = popup_param.match(/^(node|way|relation)/)[1];
open_popup_on_load.id = popup_param.replace(/^(node|way|relation)/,'' );
}
debugLayer = L.layerGroup();
debugLayer.addTo(map);
return map;
}
var open_popup_on_load = { type : "", id: "", already_shown: false };
/*
var href = location.href;
var hasQuery = href.indexOf("?") + 1;
var hasHash = href.indexOf("#") + 1;
var appendix = (hasQuery ? "&" : "?") + "ts=true";
location.href = hasHash ? href.replace("#", appendix + "#") : href + appendix;
*/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value.replace(/#.*$/,'');
});
return vars;
}
function setImageInPopup(obj) {
// console.log("setImageInPopup: called");
if(!document.getElementById('wp-image')) {
// console.log("setImageInPopup: no wp-image");
return;
}
if ($('#wp-image img').attr('src')) {
// console.log("setImageInPopup: src already set");
return;
}
var img = $('#wp-image img');
var source = wikipedia_images["wpimage_" + img.attr('title')];
if(!source) {
$('#wp-image').css('display','none');
// console.log("setImageInPopup: no answer for item yet");
return;
}
if ( source == "UNDEF") {
$('#wp-image').css('display','none');
// console.log("setImageInPopup: no image on wikipedia");
return;
}
// console.log("setImageInPopup: setting src " + source);
$('#wp-image').css('display','table-cell');
img.attr('src', source);
}
function setTranslationsInPopup(obj) {
var elements = $('.leaflet-popup-content [translated]');
if(!elements.length)
return;
//console.log(elements.length + " untranslated elements found.");
elements.each(function ( index ) {
var jqitem = $(this);
var tags_string = jqitem.attr("sourcetext");
if(tags_string == "unknown feature")
return;
var tags = tags_string.split(",");
var new_strings = [];
var langs_used = [];
for(var i=0; i < tags.length; i++) {
var tag = tags[i].trim();
if(!translations.tags[tag]) {
console.log("setTranslationsInPopup: no entry in translations found for '" + tag + "'");
new_strings.push(tag);
continue;
}
var found_transl = 0;
for(var j=0; j < language.length; j++) {
var targetlang = language[j];
if(translations.tags[tag][targetlang]) {
new_strings.push(translations.tags[tag][targetlang].value);
if(langs_used.indexOf(targetlang) == -1)
langs_used.push(targetlang);
found_transl = 1;
break;
}
}
if(!found_transl) {
console.log("no translation in your lang or en found for: '" + tag + "'");
new_strings.push(tag);
}
}
var new_text = new_strings.join(", ");
if(jqitem.children().first().text() != new_text) {
jqitem.children().first().text(new_text);
jqitem.attr("translated",langs_used.join(","));
}
});
}
function addSearch() {
map.addControl( new L.Control.Search({
url: '//nominatim.openstreetmap.org/search?format=json&q={s}',
jsonpParam: 'json_callback',
propertyName: 'display_name',
propertyLoc: ['lat','lon'],
circleLocation: false,
markerLocation: false,
autoType: false,
autoCollapse: false,
minLength: 2,
zoom:16
}) );
}
function addLocate() {
lc = L.control.locate({
position: 'topleft',
showPopup: false,
strings: {
title: "Jump to my location!"
}
}
).addTo(map);
}
var marker_table = {};
var old_zoom = 20;
var pids = {
node : {
counter : 0,
active : {}
},
way : {
counter : 0,
active : {}
},
relation : {
counter : 0,
active : {}
}
}
var mutex_loading = { "loading_node" : 0, "loading_way" : 0, "loading_relation" : 0 };
var on_start_loaded = 0;
/*
* type: "loading_node" / "loading_way" / "loading_relation"
* change: (+)1 or -1
*/
function changeLoadingIndicator(type, change) {
var loading_indicator = document.getElementById(type);
if(mutex_loading[type] + change >= 0) //don't go into negative
mutex_loading[type] = mutex_loading[type] + change;
if(change == -1) {
if(mutex_loading[type] == 0)
loading_indicator.style.display = "none";
} else // +1
loading_indicator.style.display = "block";
loading_indicator.title = mutex_loading[type];
}
function secHTML(input) {
return $("<div>").text( input ).html();
}
function getIconTag(tags) {
for (var i = 0; i < overpass_config.icon_tags.length; i++) {
var key = overpass_config.icon_tags[i];
if(tags[key] && ! ( key == "amenity" && tags[key] == "shop" ) ) {
return key;
}
}
return "";
}
function chooseIconSrc(tags,iconsize) {
var icon_tag = getIconTag(tags);
var icon_url = "";
if(!icon_tag) {
icon_url = assethost+"assets/transformap/pngs/" + overpass_config.icon_folder + "/" + iconsize + "/unknown.png";
} else {
if (tags[icon_tag].indexOf(";") >= 0) // more than one item, take generic icon
icon_url = assethost+"assets/transformap/pngs/" + overpass_config.icon_folder + "/" + iconsize + "/generic.png";
else
icon_url = assethost+"assets/transformap/pngs/" + overpass_config.icon_folder + "/" + iconsize + "/" + icon_tag + "=" + tags[icon_tag] + ".png";
}
return icon_url;
}
var disableLoadPOI = false;
var bboxes_requested = [
/* e.g. { outer_bbox: L.LatLngBounds, inner_polyboxes: [ L.LatLngBounds, L.LatLngBounds, ... ] }, { ... } */
]; //VERY SIMPLE list of areas already requested, don't load if new one is inside
/*contains(2) {
return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) && // south2 >= south && north2 <= north &&
(sw2.lng >= sw.lng) && (ne2.lng <= ne.lng); // west2 >= west && east2 <= east
}
intersects(2) {
latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
return latIntersects && lngIntersects;
}*/
/*
* returns true if it already was in BBOX,
* and false if it had to be added
*/
function checkIfInRequestedBboxesAndIfNotaddTo(bounds) {
var north = bounds._northEast.lat, // for performance reasons, do this one time
east = bounds._northEast.lng,
south = bounds._southWest.lat,
west = bounds._southWest.lng;
var b_height = north - south,
b_width = east - west,
width_to_height = b_width/b_height;
var zoom_delta_to_max = map.getMaxZoom() - map.getZoom(),
min_height = b_height / (Math.pow(2,zoom_delta_to_max));
// console.log("checkIfInRequestedBboxesAndIfNotaddTo: viewbox_height = " + viewbox_height + "°, min_heigh = " + min_height);
var min_width = b_width / (Math.pow(2,zoom_delta_to_max));
// console.log("checkIfInRequestedBboxesAndIfNotaddTo: called. bboxes_requested:" + JSON.stringify(bboxes_requested));
for(var i=0; i < bboxes_requested.length; i++) { //for-loop over outer bboxes
var current_bound = bboxes_requested[i];
if(! current_bound.outer_bbox.intersects(bounds)) //neither crossing nor inside
continue;
console.log("checkIfInRequestedBboxesAndIfNotaddTo begin: " + current_bound.inner_polyboxes.length + " inner polyboxes");
if(current_bound.outer_bbox.contains(bounds)) { // only if it doesn't cross outer bbox it is possible that it's already covered
for(var inner_bbox_i = 0; inner_bbox_i < current_bound.inner_polyboxes.length; inner_bbox_i++) {
current_inner_bbox = current_bound.inner_polyboxes[inner_bbox_i];
if(!current_inner_bbox.hasOwnProperty("_southWest")) {
console.log("current_inner_bbox error:");
console.log(current_inner_bbox);
console.log(current_bound);
}
//current_inner_bbox.contains(bounds):
if(south < current_inner_bbox._southWest.lat ||
north > current_inner_bbox._northEast.lat ||
west < current_inner_bbox._southWest.lng ||
east > current_inner_bbox._northEast.lng)
continue;
return true; // all ¬ contains-checks failed, must be contained
/* if(current_inner_bbox.contains(bounds)) {
// console.log("checkIfInRequestedBboxesAndIfNotaddTo: bbox already here");
return true;
} //false == continue*/
}
}
else //intersects one border
current_bound.outer_bbox.extend(bounds);
// either intersects with outer bbox or is not in any inner bbox
// add one horizontal and one vertical box that it intersects for EACH box!
var new_bboxes = [],
new_bounds_north_stretched = null,
new_bounds_south_stretched = null,
new_bounds_west_stretched = null,
new_bounds_east_stretched = null;
var nr_of_deletions = 0;
var addbounds = true;
for(var inner_bbox_i = 0; inner_bbox_i < current_bound.inner_polyboxes.length; inner_bbox_i++) {
current_inner_bbox = current_bound.inner_polyboxes[inner_bbox_i];
//if ! current_inner_bbox.intersects(bounds) continue (both boxes completely disjunct)
if(south >= current_inner_bbox._northEast.lat ||
north <= current_inner_bbox._southWest.lat ||
east <= current_inner_bbox._southWest.lng ||
west >= current_inner_bbox._northEast.lng)
continue;
/* 16 cases:
1.: bounds completely inside current_inner_bbox
-> is already covered by 1st for-loop with inner_polyboxes
2.: current_inner_bbox completely inside -> delete it; continue (empty array slots cleared afterwards)
-> use delete array[i], it does not reindex. reindex afterwards, remove all undefined...
3-10: 8 where one box is crosses only one side of the other
3-6: 4 where bounds is bigger
7-10: 4 where current_inner_bbox is bigger
11-14: 4 where they cross them on two sides (corner-crossing)
15,15: as stretching boxes can be longer, heigher it can happen that they form a "cross" -> simply add bounds, no special handling needed
=^= (bwb && beb && !bnb && !bsb) || (!bwb && !bwb && bnb && bsb)
* WHAT IF some bounds are equal? TODO
* FIXME a lot of dual boxes seem to be generated... -OK they were if a box hits one with same border
*/
/* TODO shrinking of bounds:
* stretching of inner_polyboxes is still needed, because: you don't know which side gets cut first, and if inner_polyboxes don't overlap,
* only a corner would get cutted out (which isn't possible on rectangles)
*
* with each run of the inner for-loop we can cut bounds smaller. if nothing left, it ... have to move first for-loop in!
*/
var boundsnorth_bigger = (north >= current_inner_bbox._northEast.lat),
boundssouth_bigger = (south <= current_inner_bbox._southWest.lat),
boundseast_bigger = (east >= current_inner_bbox._northEast.lng),
boundswest_bigger = (west <= current_inner_bbox._southWest.lng);
console.log("bnb:"+boundsnorth_bigger+" bsb:"+boundssouth_bigger+" beb:"+boundseast_bigger+" bwb:"+boundswest_bigger);
var bounds_bigger_on_howmany_sides = (boundsnorth_bigger ? 1 : 0) + (boundssouth_bigger ? 1 : 0) + (boundseast_bigger ? 1 : 0) + (boundswest_bigger);
console.log("bounds_bigger_on_howmany_sides: " + bounds_bigger_on_howmany_sides);
if(bounds_bigger_on_howmany_sides == 4) { // case 2
delete current_bound.inner_polyboxes[inner_bbox_i];
nr_of_deletions++;
continue;
}
//box is an autogenerated stretching box - these are always inside downloaded boxes, ignore for generating more.
if(current_inner_bbox.hasOwnProperty('stretch'))
continue;
if(bounds_bigger_on_howmany_sides == 3) { // cases 3-6
if(!boundsnorth_bigger) { // current_inner_bbox crosses bounds on north, stretch southward
console.log("3-6: !bnb");
var inner_height = current_inner_bbox._northEast.lat - current_inner_bbox._southWest.lat;
var max_to_stretch = north - inner_height;
current_inner_bbox._southWest.lat = (max_to_stretch < south) ? south : max_to_stretch;
continue;
}
if(!boundssouth_bigger) {
console.log("3-6: !bsb");
var inner_height = current_inner_bbox._northEast.lat - current_inner_bbox._southWest.lat;
var max_to_stretch = south + inner_height;
current_inner_bbox._northEast.lat = (max_to_stretch > north) ? north : max_to_stretch;
continue;
}
if(!boundseast_bigger) {
console.log("3-6: !beb");
var inner_width = current_inner_bbox._northEast.lng - current_inner_bbox._southWest.lng;
var max_to_stretch = east - inner_width;
current_inner_bbox._southWest.lng = (max_to_stretch < west) ? west : max_to_stretch;
continue;
}
if(!boundswest_bigger) {
console.log("3-6: !bwb");
var inner_width = current_inner_bbox._northEast.lng - current_inner_bbox._southWest.lng;
var max_to_stretch = west + inner_width;
current_inner_bbox._northEast.lng = (max_to_stretch > east) ? east : max_to_stretch;
continue;
}
console.log("shouldn't have reached bounds_bigger_on_howmany_sides == 3 after ????????????");
}
if(bounds_bigger_on_howmany_sides == 1) { // cases 7-10
addbounds = false; // we add a bigger box instead
if(boundssouth_bigger) { // bounds crosses current_inner_bbox on south, stretch northwards
console.log("7-10: bsb");
var max_to_stretch = current_inner_bbox._southWest.lat + b_height;
var new_north = (max_to_stretch > current_inner_bbox._northEast.lat) ? current_inner_bbox._northEast.lat : max_to_stretch;
if(!new_bounds_north_stretched) {
new_bounds_north_stretched = new L.latLngBounds( [ south, west ], [ new_north, east ] );
} else {
if(new_bounds_north_stretched._northEast.lat < new_north)
new_bounds_north_stretched._northEast.lat = new_north;
}
//TODO shrink bounds!
continue;
}
if(boundsnorth_bigger) { // bounds crosses current_inner_bbox on north, stretch southwards
console.log("7-10: bnb");
var max_to_stretch = current_inner_bbox._northEast.lat - b_height;
var new_south = (max_to_stretch < current_inner_bbox._southWest.lat) ? current_inner_bbox._southWest.lat : max_to_stretch;
if(!new_bounds_south_stretched) {
new_bounds_south_stretched = new L.latLngBounds( [ new_south, west ], [ north, east ] );
} else {
if(new_bounds_south_stretched._southWest.lat > new_south)
new_bounds_south_stretched._southWest.lat = new_south;
}
//TODO shrink bounds!
continue;
}
if(boundseast_bigger) { // bounds crosses current_inner_bbox on east, stretch westwards
console.log("7-10: beb");
var max_to_stretch = current_inner_bbox._northEast.lng - b_width;
var new_west = (max_to_stretch < current_inner_bbox._southWest.lng) ? current_inner_bbox._southWest.lng : max_to_stretch;
if(!new_bounds_west_stretched) {
new_bounds_west_stretched = new L.latLngBounds( [ south, new_west ], [ north, east ] );
} else {
if(new_bounds_west_stretched._southWest.lng > new_west)
new_bounds_west_stretched._southWest.lng = new_west;
}
//TODO shrink bounds!
continue;
}
if(boundswest_bigger) { // bounds crosses current_inner_bbox on west, stretch eastwards
console.log("7-10: bwb");
var max_to_stretch = current_inner_bbox._southWest.lng + b_width;
var new_east = (max_to_stretch > current_inner_bbox._northEast.lng) ? current_inner_bbox._northEast.lng : max_to_stretch;
if(!new_bounds_east_stretched) {
new_bounds_east_stretched = new L.latLngBounds( [ south, west ], [ north, new_east ] );
} else {
if(new_bounds_east_stretched._northEast.lng < new_east)
new_bounds_east_stretched._northEast.lng = new_east;
}
//TODO shrink bounds!
continue;
}
console.log("shouldn't have reached bounds_bigger_on_howmany_sides == 1 after ????????????");
}
if(bounds_bigger_on_howmany_sides == 2) { //cases 11-16
if( (boundswest_bigger && boundseast_bigger && !boundsnorth_bigger && !boundssouth_bigger) ||
(!boundswest_bigger && !boundseast_bigger && boundsnorth_bigger && boundssouth_bigger) )
continue; // case 15+16
/*we only need an stretching box if:
* xbox only if overlapping_x / width_to_height < overlap_y
* ybox only if overlapping_x < overlap_y * width_to_height
* -> either an x OR an y-box!
*/
if(boundsnorth_bigger && boundseast_bigger && !boundssouth_bigger && !boundswest_bigger) {
console.log("11-14: b topright, cib bottomleft ");
var overlap_x = current_inner_bbox._northEast.lng - west,
overlap_y = current_inner_bbox._northEast.lat - south;
if(overlap_x < overlap_y * width_to_height) {
//x stretching box
var b_N = current_inner_bbox._northEast.lat,
b_S = south,
xb_height = b_N - b_S;
if(xb_height <= min_height) continue; //console.log("no xb, to small");
var x_stretch_value = xb_height * width_to_height;
var xb_E_max = west + x_stretch_value,
b_E = (xb_E_max > east) ? east : xb_E_max;
var xb_W_max = current_inner_bbox._northEast.lng - x_stretch_value,
b_W = (xb_W_max < current_inner_bbox._southWest.lng) ? current_inner_bbox._southWest.lng : xb_W_max;
console.log("new xb");
} else {
//y stretching box
var b_E = current_inner_bbox._northEast.lng,
b_W = west,
yb_width = b_E - b_W;
if(yb_width <= min_width) continue; //console.log("no yb, to small");
var y_stretch_value = yb_width / width_to_height;
var yb_N_max = south + y_stretch_value,
b_N = (yb_N_max > north) ? north : yb_N_max;
var yb_S_max = current_inner_bbox._northEast.lat - y_stretch_value,
b_S = (yb_S_max < current_inner_bbox._southWest.lat) ? current_inner_bbox._southWest.lat : yb_S_max;
console.log("new yb");
}
}
if(boundsnorth_bigger && !boundseast_bigger && !boundssouth_bigger && boundswest_bigger) {
console.log("11-14: b topleft, cib bottomright ");
var overlap_x = east - current_inner_bbox._southWest.lng,
overlap_y = current_inner_bbox._northEast.lat - south;
if(overlap_x < overlap_y * width_to_height) {//x stretching box
var b_N = current_inner_bbox._northEast.lat,
b_S = south,
xb_height = b_N - b_S;
if(xb_height <= min_height) continue;//console.log("no xb, to small");
var x_stretch_value = xb_height * width_to_height;
var xb_E_max = current_inner_bbox._southWest.lng + x_stretch_value,
b_E = (xb_E_max > current_inner_bbox._northEast.lng) ? current_inner_bbox._northEast.lng : xb_E_max;
var xb_W_max = east - x_stretch_value,
b_W = (xb_W_max < west) ? west : xb_W_max;
console.log("new xb");
} else {//y stretching box
var b_E = east,
b_W = current_inner_bbox._southWest.lng,
yb_width = b_E - b_W;
if(yb_width <= min_width) continue; //console.log("no yb, to small");
var y_stretch_value = yb_width / width_to_height;
var yb_N_max = south + y_stretch_value,
b_N = (yb_N_max > north) ? north : yb_N_max;
var yb_S_max = current_inner_bbox._northEast.lat - y_stretch_value,
b_S = (yb_S_max < current_inner_bbox._southWest.lat) ? current_inner_bbox._southWest.lat : yb_S_max;
console.log("new yb");
}
}
if(!boundsnorth_bigger && !boundseast_bigger && boundssouth_bigger && boundswest_bigger) {
console.log("11-14: b bottomleft, cib topright ");
var overlap_x = east - current_inner_bbox._southWest.lng,
overlap_y = north - current_inner_bbox._southWest.lat;
if(overlap_x < overlap_y * width_to_height) {//x stretching box
var b_N = north,
b_S = current_inner_bbox._southWest.lat,
xb_height = b_N - b_S;
if(xb_height <= min_height) continue;//console.log("no xb, to small");
var x_stretch_value = xb_height * width_to_height;
var xb_E_max = current_inner_bbox._southWest.lng + x_stretch_value,
b_E = (xb_E_max > current_inner_bbox._northEast.lng) ? current_inner_bbox._northEast.lng : xb_E_max;
var xb_W_max = east - x_stretch_value,
b_W = (xb_W_max < west) ? west : xb_W_max;
console.log("new xb");
} else {//y stretching box
var b_E = east,
b_W = current_inner_bbox._southWest.lng,
yb_width = b_E - b_W;
if(yb_width <= min_width) continue; //console.log("no yb, to small");
var y_stretch_value = yb_width / width_to_height;
var yb_N_max = current_inner_bbox._southWest.lat + y_stretch_value,
b_N = (yb_N_max > current_inner_bbox._northEast.lat) ? current_inner_bbox._northEast.lat : yb_N_max;
var yb_S_max = north - y_stretch_value,
b_S = (yb_S_max < south) ? south : yb_S_max;
console.log("new yb");
}
}
if(!boundsnorth_bigger && boundseast_bigger && boundssouth_bigger && !boundswest_bigger) {
console.log("11-14: b bottomright, cib topleft ");
var overlap_x = current_inner_bbox._northEast.lng - west,
overlap_y = north - current_inner_bbox._southWest.lat;
if(overlap_x < overlap_y * width_to_height) {//x stretching box
var b_N = north,
b_S = current_inner_bbox._southWest.lat,
xb_height = b_N - b_S;
if(xb_height <= min_height) continue;//console.log("no xb, to small");
var x_stretch_value = xb_height * width_to_height;
var xb_E_max = west + x_stretch_value,
b_E = (xb_E_max > east) ? east : xb_E_max;
var xb_W_max = current_inner_bbox._northEast.lng - x_stretch_value,
b_W = (xb_W_max < current_inner_bbox._southWest.lng) ? current_inner_bbox._southWest.lng : xb_W_max;
console.log("new xb");
} else {//y stretching box
var b_E = current_inner_bbox._northEast.lng,
b_W = west,
yb_width = b_E - b_W;
if(yb_width <= min_width) continue; //console.log("no yb, to small");
var y_stretch_value = yb_width / width_to_height;
var yb_N_max = current_inner_bbox._southWest.lat + y_stretch_value,
b_N = (yb_N_max > current_inner_bbox._northEast.lat) ? current_inner_bbox._northEast.lat : yb_N_max;
var yb_S_max = north - y_stretch_value,
b_S = (yb_S_max < south) ? south : yb_S_max;
console.log("new yb");
}
}
stretching_box = new L.latLngBounds( [ b_S, b_W ], [ b_N, b_E ] );
stretching_box.stretch = true; //add distinguishment from an orig box
new_bboxes.push( stretching_box );
continue;
}
}
/* if(new_bboxes) {
console.log("checkIfInRequestedBboxesAndIfNotaddTo: new stretching bboxes to add:");
console.log(new_bboxes);
} else
console.log("checkIfInRequestedBboxesAndIfNotaddTo: no net stretching bboxes to add.");*/
//delete
if(nr_of_deletions)
console.log(nr_of_deletions + " to delete");
for(var inner_bbox_i = 0; nr_of_deletions ; inner_bbox_i++) {
if(! current_bound.inner_polyboxes[inner_bbox_i]) {
current_bound.inner_polyboxes.splice(inner_bbox_i--,1);
nr_of_deletions--;
}
}
if(addbounds)
current_bound.inner_polyboxes.push(bounds);
for(var new_i=0; new_i < new_bboxes.length; new_i++)
current_bound.inner_polyboxes.push(new_bboxes[new_i]);
var stretchbounds = { 1: new_bounds_east_stretched, 2: new_bounds_west_stretched, 3: new_bounds_south_stretched, 4: new_bounds_north_stretched };
for (i in stretchbounds)
if(stretchbounds[i])
current_bound.inner_polyboxes.push(stretchbounds[i]);
console.log("checkIfInRequestedBboxesAndIfNotaddTo: " + current_bound.inner_polyboxes.length + " inner polyboxes now.");
return false;
}
//it is completely outside from every outer bbox, create a new one
var new_outer_box_deep_copy = new L.latLngBounds( [ south, west ], [ north, east ] );
var bounds_deep_copy = new L.latLngBounds( [ south, west ], [ north, east ] );
bboxes_requested.push( { outer_bbox: new_outer_box_deep_copy, inner_polyboxes: [ bounds_deep_copy ] } );
// console.log("checkIfInRequestedBboxesAndIfNotaddTo: outside other bboxes, add a new");
return false;
}
//https://stackoverflow.com/questions/1484506/random-color-generator-in-javascript
function rainbow(numOfSteps, step) {
// This function generates vibrant, "evenly spaced" colours (i.e. no clustering). This is ideal for creating easily distinguishable vibrant markers in Google Maps and other apps.
// Adam Cole, 2011-Sept-14
// HSV to RBG adapted from: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
var r, g, b;
var h = step / numOfSteps;
var i = ~~(h * 6);
var f = h * 6 - i;
var q = 1 - f;
switch(i % 6){
case 0: r = 1; g = f; b = 0; break;
case 1: r = q; g = 1; b = 0; break;
case 2: r = 0; g = 1; b = f; break;
case 3: r = 0; g = q; b = 1; break;
case 4: r = f; g = 0; b = 1; break;
case 5: r = 1; g = 0; b = q; break;
}
var c = "#" + ("00" + (~ ~(r * 255)).toString(16)).slice(-2) + ("00" + (~ ~(g * 255)).toString(16)).slice(-2) + ("00" + (~ ~(b * 255)).toString(16)).slice(-2);
return (c);
}
var debugLayerShown = false;
function toggleDebugLayer() {
debugLayerShown = !debugLayerShown;
disableLoadPOI = true;
if(!debugLayerShown) {
debugLayer.clearLayers();
disableLoadPOI = false;
return;
}
for(var i=0; i < bboxes_requested.length; i++) {
var current_bound = bboxes_requested[i];
for(var inner_bbox_i = 0; inner_bbox_i < current_bound.inner_polyboxes.length; inner_bbox_i++) {
current_inner_bbox = current_bound.inner_polyboxes[inner_bbox_i];
if(current_inner_bbox.stretch)
console.log("stretch");
var rect = L.rectangle(current_inner_bbox, {color: rainbow(256, Math.floor(Math.random() * 256)), weight: (current_inner_bbox.stretch) ? 2 : 8, fill: false}).on('click',clickOnLayer);
debugLayer.addLayer(rect);
//debugLayer.addLayer(L.rectangle(current_inner_bbox, {color: rainbow(256, 128), weight: 1, fill: false}));
}
}
var dup_dump = {};
var sum = 0;
//find dups - there were a LOT of dups!
for(var i=0; i < bboxes_requested.length; i++) {
var current_bound = bboxes_requested[i];