summaryrefslogtreecommitdiff
path: root/ishtar_common/static/js/ishtar-map.js
blob: 226767914c058336f20a5dd9cf51a96c284e5abc (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
/* 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 map_default_center = 'SRID=4326;POINT (2.4397 46.5528)';
var map_default_zoom = '7';
var min_auto_zoom_on_cluster = 13;

/* base layers */

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

var default_map_layers = {
    'osm': source_osm
};

var get_layers = function(layers){
    if (!layers){
        layers = [{'type': 'osm', 'options': null}];
    }
    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;
};

/* 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 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 = _styleCache[size] = [get_icon_style()];
    } else if (!style && size > 1){
        var color = size > cluster_threshold_2 ? "192,0,0" : size > cluster_threshold_1 ? "255,128,0" : "0,128,0";
        var radius = Math.max(8, Math.min(size * 0.75, 20));
        var 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(){
    // cache for styles
    _styleCache = {};


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

var reinit_clustering = function(){
    cluster_source.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(e) {
    var feature = map.forEachFeatureAtPixel(
        e.pixel,
        function(feature, layer) {
            return feature;
        }
    );
    click_on_feature(feature, e);
};

var click_on_feature = function(feature, e){

    if (!$(e.target).is($(popup_item))
        && !$.contains($(popup_item)[0],e.target) ) {
        $(popup_item).hide();
    }

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

    var timeout = 200;
    setTimeout(function(){
        // zoom on aggregated
        var key = feature.get('key');
        if (key && key.length > 6 && key.substring(0, 7) == 'cluster'){
            feature = click_on_cluster(feature);
        }
    }, timeout);
};

var auto_zoom = false;

var click_on_cluster = function(feature, zoom_level, duration, nb_zoom,
                                current_nb_items){
    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(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.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(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.getPixelFromCoordinate(v.getCenter());
            var new_feature;
            map.forEachFeatureAtPixel(
                pixel, function(feat, layer){
                    if (layer == cluster_layer){
                        new_feature = feat;
                        return true
                    }
                }
            );
            if (new_feature){
                if (zoom_level < min_auto_zoom_on_cluster){
                    return display_cluster_detail(new_feature);
                }
                return click_on_cluster(
                    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(cluster){
    // console.log("display_cluster_detail");
    var features = cluster.getProperties()['features']
    var offset_x = 0;
    var offset_y = -21;
    if (features.length == 1){
        offset_y = -54;
    }
    display_items(features, offset_x, offset_y);
};

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

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

var complete_list_label = "complete list...";

var _display_items = function(features, offset_x, offset_y){
    // console.log("display_items");
    var feature = features[0];
    var geom = feature.getGeometry();
    var popup_content = "<ul>";
    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 = link_template.replace("<pk>", properties["id"]);
        var txt = "<li>" + link + " " + properties['name'] + "</li>";
        window_content += txt;
        if (idx_feat < 5){
            popup_content += txt;
        }
    }
    popup_content += "</ul>";
    window_content += "</ul>";
    $(".simple-window-content .modal-body").html(window_content);
    $(popup_item).html(popup_content);
    $(".map-list-detail").click(open_map_window);
    popup.setPosition(geom.getCoordinates());
    popup.setOffset([offset_x, offset_y]);
    $(popup_item).css({opacity: 0});
    $(popup_item).show(0, function(){
        setTimeout(function(){
            popup.setOffset([offset_x, offset_y]);
            $(popup_item).css({opacity: 1});
        }, 200);
    });
};

/* hover */

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

/* popup */

var popup;
var popup_item;

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


/* display map */

var center;
var point_features;
var map;
var map_id;
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 initialize_base_map = function(layers){
    center = wkt_format.readGeometry(map_default_center).getCoordinates();

    map_layers = get_layers(layers);

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

    map = new ol.Map({
        target: map_id,
        layers: map_layers,
        view: map_view
    });

}

var redraw_map = function(layers){
    map.setTarget(null);
    map = null;
    initialize_base_map(layers);
    reinit_clustering();
    current_feature = null;
};


var display_map = function(current_map_id, points, layers){
    link_template = points['link_template'];
    map_id = current_map_id;
    if (map){
        redraw_map(layers);
    } else {
        initialize_base_map(layers);
    }
    point_features = geojson_format.readFeatures(points);

    enable_clustering();
    cluster_source.getSource().addFeatures(point_features);
    init_popup();

    if (points.features.length){
        map_view.fit(cluster_source.getSource().getExtent());
        if (map_view.getZoom() > 12){
            map_view.setZoom(12);
        }
    }

    map.on('click', manage_click_on_map);
    map.on('pointermove', manage_hover);
}