summaryrefslogtreecommitdiff
path: root/ishtar_common/static/js/ishtar-map.js
blob: 46a31c28e8fed898a47c4e60a086aed72c945b25 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
/* default variables */

var default_pointer = "/media/images/default-pointer.png";
var marker_cluster = "/media/images/marker-cluster.png";

var view_projection = 'EPSG:3857';
var animation_duration = 250;

var cluster_threshold_1 = 8;
var cluster_threshold_2 = 25;

var base_color_R = 111;
var base_color_V = 66;
var base_color_B = 193;
var base_color_rvb;

var base_colors = [
    "rgba(230,0,73, 1)",
    "rgba(11,180,255, 1)",
    "rgba(80,233,145, 1)",
    "rgba(230,216,0, 1)",
    "rgba(155,25,245, 1)",
    "rgba(255,163,0, 1)",
    "rgba(220,10,180, 1)",
    "rgba(179,212,255, 1)",
    "rgba(0,191,160, 1)"
];

var map_default_center = 'SRID=4326;POINT (2.4397 46.5528)';
var map_default_zoom = '7';
var min_auto_zoom_on_cluster = 13;


/* custom control */
var track_me_msg = "Geolocalize me";
var geoloc_activated_msg = "Geolocation activated";
var geoloc_disabled_msg = "Geolocation disabled";
var geolocation = {};
var geoloc_feature = {};
var geoloc_activated = {};

var fetching_msg = "Fetching data...";

var base_maps_msg = "Base maps";
var layers_msg = "Layers";

var _map_submit_search = function(query_vars, name, source, extra){
    if (!extra) extra = "default";
    var modal_base_text = $('.modal-progress .modal-header').html();
    $('.modal-progress .modal-header').html(fetching_msg);
    $('.modal-progress').modal('show');
    var data = search_get_query_data(query_vars, name);
    var nb_select = jQuery("#id_" + name + "-length_map").val();
    if (!nb_select) nb_select = 10;

    var url = source + "json-map?length=" + nb_select + "&submited=1&" + data;
    var use_map_limit = false;
    if(data.indexOf("no_limit=true") == -1){
        url += "&limit=" + current_map_limit;
        use_map_limit = true;
    }
    var display_polygons = false;
    if(data.indexOf("display_polygon=true") != -1){
        display_polygons = true;
    }
    $.getJSON(url, function(data) {
        var timestamp = Math.floor(Date.now() / 1000);
        var map_id = "map-" + extra + "-" + timestamp;
        $('.modal-progress .modal-header').html("{% trans 'Render map...' %}");

        var html = render_map(map_id, use_map_limit, false, display_polygons);
        $("#tab-content-map-" + name + " #map-" + name + "-" + extra).html(html);
        $("#id_" + name + "-length_map").change(map_submit_search);
        if ($('.modal-progress').length > 0){
            $('.modal-progress').modal('hide');
            $('.modal-progress .modal-header').html(modal_base_text);
        }
        register_map(map_id, data);
    });

    return false;

};


var geoloc_activated_message = function(map_id){
    setTimeout(function(){
        navigator.geolocation.watchPosition(function(position) {
            if(!geoloc_activated[map_id]){
                if (display_info) display_info(geoloc_activated_msg);
                geoloc_activated[map_id] = true;
            }
        },
        function (error) {
            if (error.code == error.PERMISSION_DENIED)
                if (display_info) display_info(geoloc_disabled_msg);
        });
    }, 200);
};


var set_geoloc_source = function(map_id){
    geolocation[map_id] = new ol.Geolocation({
        projection: view_projection
    });

    geolocation[map_id].setTracking(true);

    geoloc_feature[map_id] = new ol.Feature();
    geoloc_feature[map_id].setStyle(new ol.style.Style({
        image: new ol.style.Circle({
            radius: 6,
            fill: new ol.style.Fill({color: '#3399CC'}),
        stroke: new ol.style.Stroke({color: '#fff', width: 2})
        })
    }));

    var accuracy_feature = new ol.Feature();
    geolocation[map_id].on('change:accuracyGeometry', function() {
        accuracy_feature.setGeometry(geolocation[map_id].getAccuracyGeometry());
    });

    geolocation[map_id].on('change:position', function() {
        var coordinates = geolocation[map_id].getPosition();
        geoloc_feature[map_id].setGeometry(
            coordinates ? new ol.geom.Point(coordinates) : null);
        var v = map[map_id].getView();
        v.animate({center: coordinates, duration: animation_duration * 2});
    });

    new ol.layer.Vector({
        map: map[map_id],
        source: new ol.source.Vector({
            features: [geoloc_feature[map_id], accuracy_feature]
        })
    });
    geoloc_activated_message(map_id);
};

var TrackPositionControl = (function (Control) {
    function TrackPositionControl(opt_options) {
        var options = opt_options || {};

        this.map_id = options['map_id'];

        var button = document.createElement('button');

        button.type = "button";
        button.innerHTML = '<i class="fa fa-map-marker" aria-hidden="true"></i>';
        button.title = track_me_msg;

        var element = document.createElement('div');
        element.className = 'track-position ol-unselectable ol-control';
        element.appendChild(button);

        Control.call(this, {
            element: element,
            target: options.target
        });

        button.addEventListener(
            'click', this.handleTrackPosition.bind(this),
            false
        );
    }

    if ( Control ) TrackPositionControl.__proto__ = Control;
    TrackPositionControl.prototype = Object.create( Control && Control.prototype );
    TrackPositionControl.prototype.constructor = TrackPositionControl;

    TrackPositionControl.prototype.handleTrackPosition = function handleTrackPosition () {
        if (!geolocation[this.map_id]){
            set_geoloc_source(this.map_id);
        } else {
            if (!geoloc_activated[this.map_id]) return;
            if (geolocation[this.map_id].getTracking()){
                geolocation[this.map_id].setTracking(false);
                if (display_info) display_info(geoloc_disabled_msg);
            } else {
                geolocation[this.map_id].setTracking(true);
                if (display_info) display_info(geoloc_activated_msg);
            }
        }
        return false;
    };

    return TrackPositionControl;
}(ol.control.Control));



/* base layers */

var source_osm = function(options){
    options["source"] = new ol.source.OSM();
    return new ol.layer.Tile(options);
};

var ign_resolutions = [
    156543.03392804103,
    78271.5169640205,
    39135.75848201024,
    19567.879241005125,
    9783.939620502562,
    4891.969810251281,
    2445.9849051256406,
    1222.9924525628203,
    611.4962262814101,
    305.74811314070485,
    152.87405657035254,
    76.43702828517625,
    38.218514142588134,
    19.109257071294063,
    9.554628535647034,
    4.777314267823517,
    2.3886571339117584,
    1.1943285669558792,
    0.5971642834779396,
    0.29858214173896974,
    0.14929107086948493,
    0.07464553543474241
] ;

var source_ign = function(options){
    options["source"] = new ol.source.WMTS({
        url: "https://data.geopf.fr/wmts",
        layer: "ORTHOIMAGERY.ORTHOPHOTOS",
        matrixSet: "PM",
        format: "image/jpeg",
        style: "normal",
        tileGrid : new ol.tilegrid.WMTS({
            origin: [-20037508,20037508], // topLeftCorner
            resolutions: ign_resolutions, // résolutions
            matrixIds: ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"] // ids des TileMatrix
        })
    });
    return new ol.layer.Tile(options);
}

var source_ign_cadastral = function(options){
    options["source"] = new ol.source.WMTS({
        url: "https://data.geopf.fr/wmts",
        layer: "CADASTRALPARCELS.PARCELLAIRE_EXPRESS",
        matrixSet: "PM",
        format: "image/png",
        style: "normal",
        tileGrid : new ol.tilegrid.WMTS({
            origin: [-20037508,20037508], // topLeftCorner
            resolutions: ign_resolutions, // résolutions
            matrixIds: ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"] // ids des TileMatrix
        })
    });
    return new ol.layer.Tile(options);
}


var default_map_layers = {
    'osm': source_osm,
    'ign': source_ign,
    'ign_cadastral': source_ign_cadastral
};

var get_layers = function(layers){
    if (!layers){
        layers = [
            {
                'type': 'ign',
                'options': {'title': "IGN aérien (France)", 'visible': false, "type": 'base'}
            },
            {
                'type': 'osm',
                'options': {'title': "OpenStreetMap", 'visible': true, "type": 'base'}
            }
        ];
    }
    var ol_layers = [];
    for (idx in layers){
        var layer_attr = layers[idx];
        ol_layers.push(
            default_map_layers[layer_attr['type']](layer_attr['options'])
        );
    }
    return ol_layers;
};

var get_overlays = function(overlays){
    if (!overlays){
        overlays = [
            {
                'type': 'ign_cadastral',
                'options': {'title': "IGN cadastre (France)", 'visible': false, "opacity": 0.5}
            }
        ];
    }
    var ol_overlays = [];
    for (idx in overlays){
        var layer_attr = overlays[idx];
        ol_overlays.push(
            default_map_layers[layer_attr['type']](layer_attr['options'])
        );
    }
    return ol_overlays;
}


/* styles */
var get_icon_style = function(feature){
    return new ol.style.Style({
        image: new ol.style.Icon({
            anchor: [17, 50],
            anchorXUnits: 'pixels',
            anchorYUnits: 'pixels',
            size: [35, 50],
            src: static_path + default_pointer
        })
    });
};

var get_random_int = function(max) {
    return Math.floor(Math.random() * max);
}

var _vector_style_cache = {};
var tmp;


var get_vector_style = function(feature){
    let feature_id = feature.getProperties()["id"]
    if (!(feature_id in _vector_style_cache)){
        _vector_style_cache[feature_id] = new ol.style.Style({
            stroke: new ol.style.Stroke({
            color: base_colors[get_random_int(base_colors.length)],
            width: 2})
        });
    }
    return _vector_style_cache[feature_id];
};

var cluster_get_style = function(feature, resolution){
    feature.set('key', 'cluster');
    var cluster_features = feature.get('features');

    var size = cluster_features.length;
    feature.set('size', size);

    var style = _styleCache[size];

    if (!style && size == 1){
        style = new Array();
        if (ishtar_display_buffer){
            let _current_feature = feature.getProperties()["features"][0];
            let _feat_properties = _current_feature.getProperties();
            let _buffer = _feat_properties["buffer"];
            if (_buffer){
                let point_resolution = ol.proj.getPointResolution(
                    map[_feat_properties["map_id"]].getView().getProjection(), 1,
                    _current_feature.getGeometry().flatCoordinates
                );
                let radius = _buffer * point_resolution / resolution * 2;
                let color = "255,128,0";
                style.push(
                    new ol.style.Style({
                        image: new ol.style.Circle({
                            radius: radius,
                            stroke: new ol.style.Stroke({
                                color:"rgba("+color+", 0.8)",
                                width: 2
                            }),
                            fill: new ol.style.Fill({
                                color:"rgba("+color+", 0.5)"
                            })
                        })
                    })

                )
            }
        }
        style.push(get_icon_style());
        if (!ishtar_display_buffer){
            _styleCache[size] = style;
        }
    } else if (!style && size > 1){
        let color = size > cluster_threshold_2 ? "192,0,0" : size > cluster_threshold_1 ? "255,128,0" : "0,128,0";
        let radius = Math.max(8, Math.min(size * 0.75, 20));
        let lbl = size.toString();
        style = _styleCache[size] = [
            new ol.style.Style({
                image: new ol.style.Circle({
                    radius: radius,
                    stroke: new ol.style.Stroke({
                        color:"rgba("+color+",0.5)",
                        width: 15
                    }),
                    fill: new ol.style.Fill({
                        color:"rgba("+color+",1)"
                    })
                }),
                text: new ol.style.Text({
                    text: lbl,
                    fill: new ol.style.Fill({
                        color: '#fff'
                    })
                })
            })
        ];
    }
    return style;
}

/* clustering */

var _styleCache;
var cluster_source = {};
var cluster_layer = {};

var enable_clustering = function(map_id){
    // cache for styles
    _styleCache = {};

    // cluster Source
    cluster_source[map_id] = new ol.source.Cluster({
        distance: 40,
        source: new ol.source.Vector()
    });
    // animated cluster layer
    cluster_layer[map_id] = new ol.layer.Vector({
        name: 'Cluster',
        source: cluster_source[map_id],
        // cluster style
        style: cluster_get_style
    });
    map[map_id].addLayer(cluster_layer[map_id]);
};

var reinit_clustering = function(map_id){
    if (map_id in cluster_source) {
        cluster_source[map_id].getSource().clear();
    }
    _styleCache = {};
};

/* manage clicks */

var current_feature;
var animate_in_progress = false;

var animate_end = function(){animate_in_progress = false};

var wait_animation_end = function(callback, retry){
    if (!retry) retry = 1;
    setTimeout(function(){
        retry += 1
        if (retry < 5 && animate_in_progress){
            wait_animation_end(callback)
        } else {
            callback();
        }
    }, 100);
};

var manage_click_on_map = function(map_id){
    return function(e) {
        var feature = map[map_id].forEachFeatureAtPixel(
            e.pixel,
            function(feature, layer) {
                return feature;
            }
        );
        click_on_feature(map_id, feature, e);
    };
};

var current_event;

var click_on_feature = function(map_id, feature, e){
    // console.log("click_on_feature");
    current_event = e;

    if (!$(e.target).is($(popup_item[map_id]))
        && !$.contains($(popup_item[map_id])[0], e.target) ) {
        $(popup_item[map_id]).hide();
        $('#ishtar-map-window-' + map_id).hide();
    }

    if (typeof feature == 'undefined'){
        current_feature = null;
        return;
    }
    current_feature = feature;
    if (!feature) return;

    var timeout = 10;
    setTimeout(function(){
        // zoom on aggregated
        var key = feature.get('key');
        if (feature.get('name') || feature.get('key')){
            feature = click_on_cluster(map_id, feature);
        }
    }, timeout);
};

var auto_zoom = false;

var click_on_cluster = function(map_id, feature, zoom_level, duration, nb_zoom,
                                current_nb_items){
    // console.log("click_on_cluster");
    if (!duration){
        // zoom animation must be slower
        duration = animation_duration * 2;
    }

    if (!nb_zoom) nb_zoom = 0;

    var props = feature.getProperties();
    if (!'features' in props) return feature;

    if (!auto_zoom || props['features'].length == 1){
        return display_cluster_detail(map_id, feature);
    }

    if (!current_nb_items){
        current_nb_items = props['features'].length;
    } else if(current_nb_items != props['features'].length) {
        // stop zooming there less item in the cluster
        return feature;
    }

    var v = map[map_id].getView();
    if (!zoom_level) zoom_level = v.getZoom() + 1;

    // center
    var new_center = feature.getGeometry().getCoordinates();
    // max zoom reached
    if (zoom_level >= min_auto_zoom_on_cluster){
        animate_in_progress = true;
        v.animate({center: new_center, duration: duration}, animate_end);
        return display_cluster_detail(map_id, feature);
    }

    // zoom
    animate_in_progress = true;
    v.animate({center: new_center, zoom: zoom_level, duration: duration},
              animate_end);

    nb_zoom += 1;
    // something wrong stop zoom!
    if (nb_zoom > v.getMaxZoom()) return feature;

    // wait for the animation to finish before rezoom
    return setTimeout(
        function(){
            // our cluster must be at the center (if it exists after zoom)
            var pixel = map[map_id].getPixelFromCoordinate(v.getCenter());
            var new_feature;
            map.forEachFeatureAtPixel(
                pixel, function(feat, layer){
                    if (layer == cluster_layer[map_id]){
                        new_feature = feat;
                        return true
                    }
                }
            );
            if (new_feature){
                if (zoom_level < min_auto_zoom_on_cluster){
                    return display_cluster_detail(map_id, new_feature);
                }
                return click_on_cluster(
                    map_id, new_feature, zoom_level + 1, duration, nb_zoom,
                    current_nb_items);
            }
            // no more cluster feature here or min auto zoom reach: stop zooming
            return feature;
        }, duration + 200);
};

/* display info */

var display_cluster_detail = function(map_id, cluster){
    // console.log("display_cluster_detail");
    var features = cluster.getProperties()['features']

    var offset_x = 0;
    var offset_y = -21;
    if (!features){
        features = [cluster];
        offset_y = -7;
    } else if (features.length == 1){
        offset_y = -54;
    }
    display_items(map_id, features, offset_x, offset_y);
};

var display_items = function(map_id, features, offset_x, offset_y){
    wait_animation_end(function() {_display_items(map_id, features, offset_x, offset_y)});
};

var open_map_window = function(map_id){
    return function(){
        $('#ishtar-map-window-' + map_id).show();
    };
};

var complete_list_label = "complete list...";

var map_display_base_url_start = "<a class='display_details' href='#' onclick='load_window(\"";
var map_display_base_url_end = "\")'><i class='fa fa-info-circle' aria-hidden='true'></i></a>";

var _display_items = function(map_id, features, offset_x, offset_y){
    // console.log("display_items");
    var feature = features[0];
    var geom = feature.getGeometry();
    var ul_class = "map-list-" + map_id;
    var popup_content = "<ul class='" + ul_class + "'>";
    var window_content = "<ul>";
    var has_extra = false;
    for (idx_feat in features){
        if (idx_feat == 5){
            popup_content += "<li class='text-center'><a href='#' class='map-list-detail'>";
            popup_content += complete_list_label;
            popup_content += "</a></li>";
        }
        var feat = features[idx_feat];
        var properties = feat.getProperties();
        var link = "";
        if (link_template[map_id]){
            link = link_template[map_id].replace("<pk>", properties["id"]);
        }
        if ("url" in properties){
            link = map_display_base_url_start + properties["url"] + map_display_base_url_end;
        }
        var txt = "<li>" + link + " " + properties["name"] + "</li>";
        window_content += txt;
        if (idx_feat < 5){
            popup_content += txt;
        }
    }
    popup_content += "</ul>";
    window_content += "</ul>";
    $("#ishtar-map-window-" + map_id + " .modal-body").html(window_content);
    $(popup_item[map_id]).html(popup_content);
    $("." + ul_class + " .map-list-detail").click(open_map_window(map_id));

    if (geom.getType() == "Point"){
        popup[map_id].setPosition(geom.getCoordinates());
    } else {
        popup[map_id].setPosition(current_event.coordinate);
    }
    popup[map_id].setOffset([offset_x, offset_y]);
    $(popup_item[map_id]).css({opacity: 0});
    $(popup_item[map_id]).show(0, function(){
        setTimeout(function(){
            popup[map_id].setOffset([offset_x, offset_y]);
            $(popup_item[map_id]).css({opacity: 1});
        }, 200);
    });
};

/* hover */

var manage_hover = function(map_id){
    return function(e) {
        var pixel = map[map_id].getEventPixel(e.originalEvent);
        var feature = map[map_id].forEachFeatureAtPixel(
            e.pixel,
            function(feature, layer) {
                return feature;
            }
        );
        var hit = map[map_id].hasFeatureAtPixel(pixel);
        var target = map[map_id].getTarget();
        target = typeof target === "string" ?
            document.getElementById(target) : target;
        target.style.cursor = hit ? 'pointer' : '';
    }
};

/* popup */

var popup = {};
var popup_item = {};

var init_popup = function(map_id){
    popup_item[map_id] = document.getElementById("ishtar-map-popup-" + map_id);
    var popup_options = {
        element: popup_item[map_id],
        positioning: 'bottom-center'
    }
    popup[map_id] = new ol.Overlay(popup_options);
    map[map_id].addOverlay(popup[map_id]);
};


/* display map */

var center;
var point_features = {};
var map = {};
var map_view = {};
var map_layers = {};
var proj_options = {
    dataProjection:'EPSG:4326', featureProjection: view_projection
}
var geojson_format = new ol.format.GeoJSON(proj_options);
var wkt_format = new ol.format.WKT(proj_options);
var link_template = {};
var vector_source = {};
var vector_layer = {};
var vector_features = {};

/* for test */

let geo_items_features = null;
let current_test = false;
var initialize_test_map = function (slug_pk) {
    const id = "http-geo-items-ready-" + slug_pk;
    geo_items_features = {};
    current_test = true;
    if ($("#"+id).length === 0) {
        $("#display-geo-items-for-" + slug_pk).after('<div id="'+id+'">Ready!</div>');
    }
    $("#"+id).hide();
}


var initialize_base_map = function(map_id, layers){
    center = wkt_format.readGeometry(map_default_center).getCoordinates();

    map_layers[map_id] = [
        new ol.layer.Group({
            title: base_maps_msg,
            visible: true,
            layers: get_layers(layers)
        })
    ];

    var overlays = get_overlays();
    if (overlays){
        map_layers[map_id].push(
            new ol.layer.Group({
                title: layers_msg,
                visible: true,
                layers: overlays
            })
        );
    }

    // console.log(map_id);
    map_view[map_id] = new ol.View({
        projection: view_projection,
        center: ol.proj.fromLonLat([center[0], center[1]]),
        zoom: map_default_zoom
    });

    var map_controls = ol.control.defaults().extend([
        new ol.control.OverviewMap({
            layers: map_layers[map_id]
        }),
        new ol.control.FullScreen(),
        new ol.control.ScaleLine()
    ]);

    if (location.protocol == 'https:'){
        map_controls.push(
            new TrackPositionControl({map_id: map_id})
        );
    }

    map[map_id] = new ol.Map({
        controls: map_controls,
        target: map_id,
        layers: map_layers[map_id],
        view: map_view[map_id]
    });
    var layer_switcher = new ol.control.LayerSwitcher({
        tipLabel: 'Légende',
        groupSelectStyle: 'children'
    });
    map[map_id].addControl(layer_switcher);
}

var redraw_map = function(map_id, layers){
    if (!map || !map[map_id]) return;
    map[map_id].setTarget(null);
    map[map_id] = null;
    initialize_base_map(map_id, layers);
    reinit_clustering(map_id);
    current_feature = null;
};


var display_map = function(map_id, points, lines_and_polys, layers){
    base_color_rvb = base_color_R + ', ' + base_color_V + ', ' + base_color_B;

    if (points){
        link_template[map_id] = points['link_template'];
    } else if (lines_and_polys) {
        link_template[map_id] = lines_and_polys['link_template'];
    }
    if (map[map_id]){
        redraw_map(map_id, layers);
    } else {
        initialize_base_map(map_id, layers);
    }
    if (lines_and_polys) display_lines_and_polys(map_id, lines_and_polys);
    if (points) display_points(map_id, points);
    zoom_to_extent(map_id);
    init_popup(map_id);

    map[map_id].on('click', manage_click_on_map(map_id));
    map[map_id].on('pointermove', manage_hover(map_id));

    if (current_test) {
        geo_items_features[map_id] = []; // for test
    }
};

var ishtar_display_buffer = false;

var display_points = function(map_id, points){
    if (!points) return;
    point_features[map_id] = geojson_format.readFeatures(points);
    if (!cluster_source[map_id]){
        enable_clustering(map_id);
    } else {
        reinit_clustering(map_id);
    }
    point_features[map_id].forEach(function(feat){feat.set("map_id", map_id)});
    cluster_source[map_id].getSource().addFeatures(point_features[map_id]);
};

var display_lines_and_polys = function(map_id, lines_and_polys){
    if (!lines_and_polys) return;
    vector_features[map_id] = geojson_format.readFeatures(lines_and_polys);
    if (!vector_source[map_id]){
        vector_source[map_id] = new ol.source.Vector();
    } else {
        vector_source[map_id].clear();
        vector_source[map_id].refresh();
    }
    vector_source[map_id].addFeatures(vector_features[map_id]);
    vector_layer[map_id] = new ol.layer.Vector({
        source: vector_source[map_id],
        style: get_vector_style
    });

    map[map_id].addLayer(vector_layer[map_id]);
};

var zoom_to_extent = function(map_id){
    let extent;
    if (cluster_source[map_id]) extent = cluster_source[map_id].getSource().getExtent();
    if (vector_source[map_id]){
        let vector_extent = vector_source[map_id].getExtent();
        if (vector_extent){
            if (extent){
                ol.extent.extend(extent, vector_extent);
            } else {
                extent = vector_extent;
            }
        }
    }
    if (extent) {
        map_view[map_id].fit(extent);
        if (map_view[map_id].getZoom() > 14){
            map_view[map_id].setZoom(14);
        }
    }
}

var _geo_points = new Array();
var _geo_other = new Array();
var _geo_extents = new Array();

var _point_list_crs = new Array();
var _other_list_crs = new Array();
var _point_list_finds = new Array();
var _other_list_finds = new Array();

const _refresh_map_crs = function(idx) {
    if (idx in _geo_points && idx in _point_list_crs){
        for (const feat of _point_list_crs[idx]){
            _geo_points[idx]["features"].push(feat);
        }
    }
    if (idx in _geo_other && idx in _other_list_crs){
        for (const feat of _other_list_crs[idx]){
            _geo_other[idx]["features"].push(feat);
        }
    }
}
const _refresh_map_finds = function(idx) {
    if (idx in _geo_points && idx in _point_list_finds){
        for (const feat of _point_list_finds[idx]){
            _geo_points[idx]["features"].push(feat);
        }
    }
    if (idx in _geo_other && idx in _other_list_finds){
        for (const feat of _other_list_finds[idx]){
            _geo_other[idx]["features"].push(feat);
        }
    }
}

const refresh_map_finds_crs = function(url, attrs, idx, crs_check, finds_check) {
    if (idx in _point_list_finds){
        if (crs_check) _refresh_map_crs(idx);
        if (finds_check) _refresh_map_finds(idx);
        return;
    }
    _point_list_crs[idx] = new Array();
    _other_list_crs[idx] = new Array();
    _point_list_finds[idx] = new Array();
    _other_list_finds[idx] = new Array();
    $.get(url, attrs).done(
        function(data) {
            data = JSON.parse(data);
            if (data) {
                if (data["context-records"] && data["context-records"]["features"]) {
                    for (let feat of data["context-records"]["features"]){
                        if (feat["geometry"]){
                            if (feat["geometry"]["type"] === 'Point' ||
                                feat["geometry"]["type"] === 'MultiPoint'){
                                _point_list_crs[idx].push(feat);
                            } else {
                                _other_list_crs[idx].push(feat);
                            }
                        }
                    }
                    if (crs_check) _refresh_map_crs(idx);
                }
                if (data["finds"] && data["finds"]["features"]) {
                    for (let feat of data["finds"]["features"]){
                        if (feat["geometry"]){
                            if (feat["geometry"]["type"] === 'Point' ||
                                feat["geometry"]["type"] === 'MultiPoint'){
                                _point_list_finds[idx].push(feat);
                            } else {
                                _other_list_finds[idx].push(feat);
                            }
                        }
                    }
                    if (finds_check) _refresh_map_finds(idx);
                }
            }
        }
    );
}


var BASE_GEOJSON = {
    'type': 'FeatureCollection',
    'crs': {
        'type': 'name',
        'properties': {
            'name': 'EPSG:4326'
        }
    },
    'features': []
};


const refresh_map = function(idx, geodata_list, url, attrs) {
    _geo_points[idx] = {"type": "FeatureCollection", "features": []};
    _geo_other[idx] = {"type": "FeatureCollection", "features": []};
    _geo_extents[idx] = new Array();
    for (const key in geodata_list){
        if ($("#map-ol-" + key).prop('checked')){
            let geo_type = geodata_list[key][0];
            let geojson = geodata_list[key][1];
            if (geo_type === 'POINT'){
                Array.prototype.push.apply(
                    _geo_points[idx]["features"], geojson["features"]);
                if (_geo_extents[idx].indexOf(key) === -1){
                    _geo_extents[key] = new ol.geom.Circle(
                        ol.proj.transform(geojson["features"][0]["geometry"]["coordinates"], 'EPSG:4326', 'EPSG:3857'),
                        1000
                    ).getExtent();
                    register_zoom_on_map("#map-zoom-" + key);
                }
            } else {
                Array.prototype.push.apply(
                    _geo_other[idx]["features"], geojson["features"]);
                if (_geo_extents[idx].indexOf(key) === -1){
                    let feat = BASE_GEOJSON;
                    feat["features"] = geojson["features"];
                    let extent = new ol.source.Vector(
                            {features: new ol.format.GeoJSON().readFeatures(feat)}
                    ).getExtent();
                    let coords_1 = ol.proj.transform([extent[0], extent[1]], 'EPSG:4326', 'EPSG:3857');
                    let coords_2 = ol.proj.transform([extent[2], extent[3]], 'EPSG:4326', 'EPSG:3857');
                    _geo_extents[key] = [
                        coords_1[0], coords_1[1],
                        coords_2[0], coords_2[1]
                    ];
                    register_zoom_on_map("#map-zoom-" + key);
                }
            }
            $("#map-zoom-" + key).attr('aria-disabled', 'false');
        } else {
            $("#map-zoom-" + key).attr('aria-disabled', 'true');
        }
    }
    if (url && attrs){
        let finds_check = $("#map-ol-" + idx + "-finds").prop('checked');
        let crs_check = $("#map-ol-" + idx + "-crs").prop('checked');
        refresh_map_finds_crs(url, attrs, idx, crs_check, finds_check);
    }
}

var click_delay;

const register_zoom_on_map = function(){
    $(".map-zoom-link").click(
        function(){
            if (click_delay && (Date.now() - click_delay) < 1000){
                click_delay = Date.now();
                return false;
            }
            click_delay = Date.now();
            let feat_key = $(this).attr("data-geo-id");
            let map_idx = $(this).attr("data-map-id");
            if (! ol.extent.isEmpty(_geo_extents[feat_key])) {
                map_view[map_idx].fit(_geo_extents[feat_key]);
            }
            return false;
        }
    )
}

var update_all_map_display = function(){
    for (idx in map){
        map[idx].updateSize()
    }
}