Blame view

flaskr/static/js/plots/emissions-equidistant-map.js 14.6 KB
1d31d3ff   Antoine Goutenoir   feat: move the ce...
1
// jQuery-free
02e514b8   Antoine Goutenoir   docs: add some in...
2
function draw_emissions_equidistant_map(containerSelector, worldDataUrl, emissionsDataUrl) {
7ab0c489   Adrenesis   add equidistant-e...
3
4
5
    let margin = {top: 48, right: 88, bottom: 68, left: 98},
        width = 960 - margin.left - margin.right,
        height = 540 - margin.top - margin.bottom;
1d31d3ff   Antoine Goutenoir   feat: move the ce...
6
    const baseAttendeeCircleRadius = 2;
7ab0c489   Adrenesis   add equidistant-e...
7
    const legendAmount = 5;
1d31d3ff   Antoine Goutenoir   feat: move the ce...
8
    const baseAttendeeCircleRadiusRatio = 10.0;
7ab0c489   Adrenesis   add equidistant-e...
9
10
    const baseAttendeeCircleColorRatio = 1500.0;

1d31d3ff   Antoine Goutenoir   feat: move the ce...
11
12
    let emissionsData = null;
    let worldData = null;
7ab0c489   Adrenesis   add equidistant-e...
13
14

    let svg = null;
1d31d3ff   Antoine Goutenoir   feat: move the ce...
15
    let cartaContainer = null;
7ab0c489   Adrenesis   add equidistant-e...
16

1d31d3ff   Antoine Goutenoir   feat: move the ce...
17
18
19
20
    let geoPath = d3.geoPath();
    let mapProjection = null;
    let center_latitude = 0.0;
    let center_longitude = 0.0;
7ab0c489   Adrenesis   add equidistant-e...
21

1d31d3ff   Antoine Goutenoir   feat: move the ce...
22
    // Per city
7ab0c489   Adrenesis   add equidistant-e...
23
    let maxAttendeeAmount = 0;
1d31d3ff   Antoine Goutenoir   feat: move the ce...
24
    let maxFootprint = 0;
7ab0c489   Adrenesis   add equidistant-e...
25

1d31d3ff   Antoine Goutenoir   feat: move the ce...
26
27
    // let coordinatesFromFile = null;
    // let geoJsonFromFile = null;
7ab0c489   Adrenesis   add equidistant-e...
28

1d31d3ff   Antoine Goutenoir   feat: move the ce...
29
30
    // let attendeeAmountPerCountry = [];
    // let countryCoordinates = [];
7ab0c489   Adrenesis   add equidistant-e...
31
32


1d31d3ff   Antoine Goutenoir   feat: move the ce...
33
    // let rotateForm = document.createElement("select");
7ab0c489   Adrenesis   add equidistant-e...
34

1d31d3ff   Antoine Goutenoir   feat: move the ce...
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
    // let processGeoJson = function (geojson, firstRead = true) {
    //     geoJsonFromFile = geojson;
    //     cartaContainer.selectAll("path")
    //         .data(geojson.features)
    //         .enter()
    //         .append("path")
    //         .attr("d", geoPath)
    //         .style("fill", "#444444AA");
    //     if (firstRead) {
    //         // Prepare country data
    //         geojson.features.forEach((element) => {
    //             let countryFound = false;
    //             coordinatesFromFile.forEach((countryCoord) => {
    //                 if (countryFound) {
    //                     return;
    //                 }
    //                 if (countryCoord.country === element.properties.iso_a2 || countryCoord.country === element.properties.wb_a2) {
    //                     countryCoordinates.push({
    //                         name: element.properties.name_long,
    //                         latitude: countryCoord.latitude,
    //                         longitude: countryCoord.longitude
    //                     });
    //                     countryFound = true;
    //                 }
    //             });
    //             if (!countryFound) {
    //                 console.log("missing country:" + element.properties.name_long + " by the alpha2:" + element.properties.iso_a2 + " or " + element.properties.wb_a2);
    //             }
    //         });
    //
    //         // Sort country data
    //         function compare(a, b) {
    //             if (a.name < b.name) {
    //                 return -1;
    //             }
    //             if (a.name > b.name) {
    //                 return 1;
    //             }
    //             return 0;
    //         }
    //
    //         countryCoordinates.sort(compare);
    //         // Create Option Elements
    //         countryCoordinates.forEach((element) => {
    //             let option = document.createElement("option");
    //             option.text = element.name;
    //             option.value = JSON.stringify([
    //                 element.latitude,
    //                 element.longitude,
    //             ]);
    //             rotateForm.append(option);
    //         });
    //         // Read actual data Sample
    //         d3.csv(emissionsDataUrl, onEmissionsDatum)
    //             .then(onEmissionsReady);
    //     }
    // };
7ab0c489   Adrenesis   add equidistant-e...
92
93


1d31d3ff   Antoine Goutenoir   feat: move the ce...
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    // let processCountryCoords = function (countryCoords) {
    //     coordinatesFromFile = countryCoords;
    //     if (geoJsonFromFile) {
    //         processGeoJson(geoJsonFromFile, false);
    //         onEmissionsReady();
    //     } else {
    //         d3.json(worldDataUrl).then(processGeoJson);
    //     }
    //     let selector = containerSelector.slice(1, containerSelector.length);
    //     document.getElementById(selector).insertAdjacentElement("beforeend", rotateForm);
    //     rotateForm.onchange = function (event) {
    //         const [latitude, longitude] = JSON.parse(rotateForm.value);
    //         recenterOnLatLon(latitude, longitude);
    //         // console.log(rotateForm.value);
    //         cartaContainer.remove();
    //         cartaContainer = svg.append("g");
    //         processCountryCoords(coordinatesFromFile, false);
    //     };
    //     // d3.select("svg").on("mousedown", function(event) {
    //     //     console.log(mapProjection.invert(d3.pointer(event)));
    //     // });
    // };
7ab0c489   Adrenesis   add equidistant-e...
116

1d31d3ff   Antoine Goutenoir   feat: move the ce...
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

    // const onEmissionsDatum = function (datum) {
    //     let trainAttendee = parseInt(datum["train trips_amount"]);
    //     let planeAttendee = parseInt(datum["plane trips_amount"]);
    //     if (trainAttendee === 0 && planeAttendee === 0) {
    //         return;
    //     }
    //     let attendeeAmount = trainAttendee + planeAttendee;
    //     let distance_km = datum.distance_km / attendeeAmount;
    //     let co2_kg = parseFloat(datum.co2_kg);
    //     if (co2_kg === "NaN" || distance_km === "NaN") {
    //         return;
    //     }
    //     let countryFound = false;
    //     let countryName = datum["country"].slice(1, datum["country"].length);
    //     attendeeAmountPerCountry.forEach((element) => {
    //         if (element.country === countryName) {
    //             element.attendeeAmount += attendeeAmount;
    //             maxAttendeeAmount = Math.max(maxAttendeeAmount, element.attendeeAmount);
    //             countryFound = true;
    //         }
    //
    //     });
    //     if (!countryFound) {
    //         attendeeAmountPerCountry.push({
    //             country: countryName,
    //             attendeeAmount: attendeeAmount
    //         });
    //         maxAttendeeAmount = Math.max(maxAttendeeAmount, attendeeAmount);
    //     }
    // };
7ab0c489   Adrenesis   add equidistant-e...
148
149


1d31d3ff   Antoine Goutenoir   feat: move the ce...
150
    const drawCircle = function (x, y, radius, color, className = "circle") {
7ab0c489   Adrenesis   add equidistant-e...
151
152
153
        svg.append("circle")
            .attr("class", className)
            .attr("cx", x)
1d31d3ff   Antoine Goutenoir   feat: move the ce...
154
            .attr("cy", y)
7ab0c489   Adrenesis   add equidistant-e...
155
156
157
158
159
160
161
            .attr("r", radius)
            .style("fill", color)
            .style("stroke", "rgba(0,0,0,0.7)")
            .style("stroke-width", "1");
    };


1d31d3ff   Antoine Goutenoir   feat: move the ce...
162
    const setupLegend = function () {
7ab0c489   Adrenesis   add equidistant-e...
163
164
165
        svg.append("rect")
            .attr("class", "legend")
            .attr("transform", "translate(" + 2 + "," + 2 + ")")
1d31d3ff   Antoine Goutenoir   feat: move the ce...
166
            .attr("width", 155)
7ab0c489   Adrenesis   add equidistant-e...
167
168
169
170
171
172
173
            .attr("height", legendAmount * 34 + 15)
            .style("fill", "#EEEEEEFF")
            .style("stroke", "#000000")
            .style("stroke-width", "2");
        svg.append("text")
            .attr("class", "legend")
            .attr("transform",
1d31d3ff   Antoine Goutenoir   feat: move the ce...
174
                "translate(" + 50 + " ," +
7ab0c489   Adrenesis   add equidistant-e...
175
176
177
178
179
                (28) + ")")
            .style("text-anchor", "left")
            .text((1).toFixed(0) + " attendees");
        let x = 10 + 20;
        let y = 25;
1d31d3ff   Antoine Goutenoir   feat: move the ce...
180
181
182
        let radius = baseAttendeeCircleRadius + (baseAttendeeCircleRadiusRatio / maxAttendeeAmount);
        let color = "rgba(" + (-(baseAttendeeCircleColorRatio / maxAttendeeAmount) + 255.0) +
            ", " + (-(baseAttendeeCircleColorRatio / maxAttendeeAmount) + 255.0) +
7ab0c489   Adrenesis   add equidistant-e...
183
184
            ", 240, 0.7)";
        drawCircle(x, y, radius, color);
1d31d3ff   Antoine Goutenoir   feat: move the ce...
185
        for (let i = 1; i < legendAmount; i++) {
7ab0c489   Adrenesis   add equidistant-e...
186
187
188
            svg.append("text")
                .attr("class", "legend")
                .attr("transform",
1d31d3ff   Antoine Goutenoir   feat: move the ce...
189
                    "translate(" + 50 + " ," +
7ab0c489   Adrenesis   add equidistant-e...
190
191
192
193
194
                    (28 + 34 * i) + ")")
                .style("text-anchor", "left")
                .text((Math.floor(maxAttendeeAmount * (i / legendAmount))).toFixed(0) + " attendees");
            let x = 10 + 20;
            let y = 25 + 34 * i;
1d31d3ff   Antoine Goutenoir   feat: move the ce...
195
196
197
            let radius = baseAttendeeCircleRadius + Math.sqrt(maxAttendeeAmount * (i / legendAmount)) * (baseAttendeeCircleRadiusRatio / maxAttendeeAmount);
            let color = "rgba(" + (-Math.sqrt(maxAttendeeAmount * (i / legendAmount)) * (baseAttendeeCircleColorRatio / maxAttendeeAmount) + 255.0) +
                ", " + (-Math.sqrt(maxAttendeeAmount * (i / legendAmount)) * (baseAttendeeCircleColorRatio / maxAttendeeAmount) + 255.0) +
7ab0c489   Adrenesis   add equidistant-e...
198
                ", 240, 0.7)";
1d31d3ff   Antoine Goutenoir   feat: move the ce...
199
            drawCircle(x, y, radius, color, "legend");
7ab0c489   Adrenesis   add equidistant-e...
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
        }

        // todo: describe those in the legend
        // svg.append("circle")
        //     .attr("cx", function (d) { return width /2; })
        //     .attr("cy", function (d) { return height/2; })
        //     .attr("r", function (d) { return 25; })
        //     .style("fill", function(d) { return "rgba(255, 0, 0, 0.7)"; });
        // svg.append("circle")
        //     .attr("class", "attendee-dot")
        //     .attr("cx", function (d) { return width /2; })
        //     .attr("cy", function (d) { return height/2; })
        //     .attr("r", function (d) { return 3; })
        //     .style("fill", function(d) { return "rgba(255, 0, 0, 1.0)"; });
    };


1d31d3ff   Antoine Goutenoir   feat: move the ce...
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
    // const onEmissionsReady = function () {
    //     svg.selectAll("circle.attendee-dot").remove();
    //     svg.selectAll("rect.legend").remove();
    //     svg.selectAll("circle.legend").remove();
    //     svg.selectAll("text.legend").remove();
    //
    //     setupLegend();
    //     attendeeAmountPerCountry.forEach((element) => {
    //         countryCoordinates.forEach((coordinate) => {
    //             if (element.country === coordinate.name) {
    //                 let x = mapProjection([coordinate.longitude, coordinate.latitude])[0];
    //                 let y = mapProjection([coordinate.longitude, coordinate.latitude])[1];
    //                 let radius = baseAttendeeCircleRadius + Math.sqrt(element.attendeeAmount) * (baseAttendeeCircleRadiusRatio / maxAttendeeAmount);
    //                 let color = "rgba(" + (-Math.sqrt(element.attendeeAmount) * (baseAttendeeCircleColorRatio / maxAttendeeAmount) + 255.0) +
    //                     ", " + (-Math.sqrt(element.attendeeAmount) * (baseAttendeeCircleColorRatio / maxAttendeeAmount) + 255.0) +
    //                     ", 240, 0.7)";
    //
    //                 drawCircle(x, y, radius, color, "attendee-dot");
    //             }
    //         })
    //     });
    //     svg.append("circle")
    //         .attr("class", "attendee-dot")
    //         .attr("cx", width / 2)
    //         .attr("cy", height / 2)
    //         .attr("r", 3)
    //         .style("fill", "rgba(255, 0, 0, 1.0)");
    // };


    const crunchEmissionsData = () => {
        emissionsData.forEach((datum, idx) => {
            let trainAttendeesAmount = parseInt(datum["train trips_amount"]);
            let planeAttendeesAmount = parseInt(datum["plane trips_amount"]);
            if (trainAttendeesAmount === 0 && planeAttendeesAmount === 0) {
                return;
            }
            let attendeesAmount = trainAttendeesAmount + planeAttendeesAmount;
            maxAttendeeAmount = Math.max(maxAttendeeAmount, attendeesAmount);
            emissionsData[idx].attendeeAmount = attendeesAmount;

            maxFootprint = Math.max(maxFootprint, datum.co2_kg);
7ab0c489   Adrenesis   add equidistant-e...
259
        });
1d31d3ff   Antoine Goutenoir   feat: move the ce...
260
261
262
263
264
265
    };


    const redrawCentralCircle = () => {
        svg.selectAll("circle.central-dot").remove();

7ab0c489   Adrenesis   add equidistant-e...
266
        svg.append("circle")
1d31d3ff   Antoine Goutenoir   feat: move the ce...
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
            .attr("cx", width / 2)
            .attr("cy", height / 2)
            .attr("r", 2)
            .classed("central-dot", true)
            .style("fill", "rgba(255, 0, 0, 0.777)");
    };


    const redrawDistanceCircles = () => {
        // TODO: draw a few circles and a label with the distance for each
        // …
        // or not.
        // We might instead draw the circle under the mouse
    };


    const redrawAttendees = () => {
        svg.selectAll("circle.attendee-dot").remove();

        emissionsData.forEach((datum) => {
            // console.log("Emission datum", datum);
            let x = mapProjection([datum.longitude, datum.latitude])[0];
            let y = mapProjection([datum.longitude, datum.latitude])[1];
            let radius = (
                baseAttendeeCircleRadius
                +
                (
                    baseAttendeeCircleRadiusRatio
                    *
                    Math.sqrt(
                        datum.attendeeAmount
                        /
                        maxAttendeeAmount
                    )
                )
            );
            let color = (
                255.0
                -
                (
                    baseAttendeeCircleColorRatio
                    *
                    Math.sqrt(
                        datum.co2_kg
                        /
                        maxFootprint
                    )
                )
            );
            drawCircle(
                x, y, radius,
                `rgba(${color}, ${color}, 240.0, 0.618)`,
                "attendee-dot"
            );
        });
    };


    const redrawWorldMap = () => {
        cartaContainer.selectAll("path").remove();
        cartaContainer.selectAll("path")
            .data(worldData.features)
            .enter()
            .append("path")
            .attr("d", geoPath)
            .style("fill", "#d5d5d5");
    };


    const rebuildProjection = () => {
        mapProjection = d3.geoAzimuthalEquidistant()
            .scale(79.4188)
            .rotate([
                // Don't ask me why
                -1 * center_longitude,
                -1 * center_latitude,
            ])
            .translate([width / 2, height / 2]);
        geoPath.projection(mapProjection);
    };


    const recenterOnLatLon = (latitude, longitude) => {
        center_latitude = latitude;
        center_longitude = longitude;

        rebuildProjection();
        // Draw in order from back to front
        redrawWorldMap();
        redrawDistanceCircles();
        redrawAttendees();
        redrawCentralCircle();

        //setupLegend();
7ab0c489   Adrenesis   add equidistant-e...
361
362
363
364
    };


    document.addEventListener("DOMContentLoaded", () => {
02e514b8   Antoine Goutenoir   docs: add some in...
365
        console.info("[Emissions Equidistant Map] Starting…");
1d31d3ff   Antoine Goutenoir   feat: move the ce...
366
        width = document.querySelector(containerSelector).parentElement.offsetWidth;
7ab0c489   Adrenesis   add equidistant-e...
367
368
369
370
371
        width = width - margin.left - margin.right;
        svg = d3.select(containerSelector)
            .append("svg")
            .attr("width", width)
            .attr("height", height);
1d31d3ff   Antoine Goutenoir   feat: move the ce...
372
373
374
375
376
        cartaContainer = svg.append("g");
        Promise.all([
            d3.csv(emissionsDataUrl),
            d3.json(worldDataUrl),
        ]).then((allTheData) => {
02e514b8   Antoine Goutenoir   docs: add some in...
377
            console.info("[Emissions Equidistant Map] Generating…");
1d31d3ff   Antoine Goutenoir   feat: move the ce...
378
379
380
381
382
383
            [emissionsData, worldData] = allTheData;
            crunchEmissionsData();
            recenterOnLatLon(
                parseFloat(emissionsData[0].latitude),
                parseFloat(emissionsData[0].longitude)
            );
02e514b8   Antoine Goutenoir   docs: add some in...
384
            console.info("[Emissions Equidistant Map] Done.-");
1d31d3ff   Antoine Goutenoir   feat: move the ce...
385
386
387
388
389
390
        });

        d3.select(containerSelector+" svg").on("mousedown", function(event) {
            const pointerLonLat = mapProjection.invert(d3.pointer(event));
            recenterOnLatLon(pointerLonLat[1], pointerLonLat[0]);
        });
7ab0c489   Adrenesis   add equidistant-e...
391
392
    });
}