-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
684 lines (582 loc) · 20.7 KB
/
Copy pathapp.js
File metadata and controls
684 lines (582 loc) · 20.7 KB
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
"use strict";
/**
* Mit der Projektarbeit soll geprüft werden, ob ihr den vermittelten Stoff verstanden habt. Dazu ist es notwendig, dass wichtige Teilbereiche des vermittelten Stoffes genutzt werden.
Enthalten sein müssen daher:
- Arbeit mit Events
- Nutzung von Webstorage oder Cookies
- Erzeugung und Integration von DOM-Teilbäumen
- AJAX
Wenn ihr euch mit vertiefenden Möglichkeiten auseinandersetzen wollt, ist dies natürlich erlaubt.
Es ist zudem erlaubt, in Gruppen zu arbeiten, und jQuery zu nutzen
*/
//---------------DOM referenzieren--------------------------
const canvas= document.getElementById("mapCanvas");
const imgMap= document.querySelector("img.bg-map");
const output= document.getElementById("output");
const navBar= document.querySelector("nav-bar");
const geocode= document.getElementById("geocodeBtn");
const drawBtn= document.getElementById("drawBtn");
const distanceBtn= document.getElementById("distanceBtn");
const areaBtn= document.getElementById("areaBtn");
const timeBtn= document.getElementById("currenttime");
const geojsonBtn= document.getElementById("saveGeoJsonBtn");
const ctx = canvas.getContext('2d'); //2d context
const title= document.createElement("title");
title.innerText = "Interaktive Karte";
document.head.appendChild(title);
// --- Resize Canvas to Image ---rechteckige ausschnitt
function resizeCanvasToImage() {
const rect = imgMap.getBoundingClientRect();
canvas.width = rect.width;
canvas.height = rect.height;
canvas.style.position = 'absolute';
canvas.style.left = rect.left + "px";
canvas.style.top = rect.top + "px";
canvas.style.width = rect.width + "px";
canvas.style.height = rect.height + "px";
}
//Canvas matches always the size
//and the position of the image (canvas is over the image)
if (imgMap.complete) {
resizeCanvasToImage();
} else {
imgMap.onload = resizeCanvasToImage;
}
window.addEventListener("resize", resizeCanvasToImage);
// Mouse move tracking (fixed)
canvas.addEventListener("mousemove", function(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
output.textContent = `X: ${x.toFixed(0)}px, Y: ${y.toFixed(0)}px`;
}
);
//----------------------TIME BUTTON-------------------------------------
// Function to draw the pin body
function drawPin(x, y, label) {
const pinHeadRadius = 6;
const tailLength = 10;
// Shift the head of the pin upward so the bottom of the pin lands on (x, y)
const circleCenterY = y - tailLength - pinHeadRadius;
// Draw the pin head (Kreis) --Nadel
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(x, circleCenterY, pinHeadRadius, 0, Math.PI * 2);
ctx.fill();
// Draw the tail from the circle center to the absolute position
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.moveTo(x, circleCenterY + pinHeadRadius); // bottom of the circle
ctx.lineTo(x, y); // absolute position
ctx.stroke(); //
// Draw the label next to the pin
ctx.font = "12px Arial";
ctx.fillStyle = "green";
ctx.fillText(label, x + 10, circleCenterY); // next to the circle
}
// --- Handle current time button ---
const citiesTime = [];
const xhr = new XMLHttpRequest();
timeBtn.addEventListener("click", function () {
hidePlaceholders();
document.getElementById("popover").classList.remove("show");
// Clear canvas before drawing new pins
ctx.clearRect(0, 0, canvas.width, canvas.height);
const xhrTime = new XMLHttpRequest();
xhrTime.onload = function () {
if (xhrTime.status !== 200) return;
const timezoneData = xhrTime.response;
const timePosArray = timezoneData.timePos;
citiesTime.length = 0; // Clear previous time data
for (let i = 0; i < timePosArray.length; i++) {
const city = timePosArray[i];
const name = city.name;
const timezone = city.timezone;
const x = city["absolute position"].X;
const y = city["absolute position"].Y;
// Get current local time in city's timezone
const currentTime = new Intl.DateTimeFormat('en-US', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: timezone
}).format(new Date());
// Draw the pin and label on the map
const label = `${currentTime}`;
drawPin(x, y, label);
// Save to array
citiesTime.push({
name: name,
timezone: timezone,
x: x,
y: y,
currentTime: currentTime
});
}
};
xhrTime.responseType = "json";
xhrTime.open("GET", "/timezone.json");
xhrTime.send();
});
//-------------------GEOCODE BUTTON-------------------
// --- Load cities data ---
let cities = [];
let citiesLoaded = false;
// Load cities.json via AJAX
function loadCities(callback) {
if (citiesLoaded) {
callback(cities);
return;
}
const xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status !== 200) {
alert("Failed to load city data.");
return;
}
const data = xhr.response;
cities = data.cities;
citiesLoaded = true;
callback(cities);
};
xhr.responseType = "json";
xhr.open("GET", "/cities.json");
xhr.send();
}
// --- Show Geocode Info ---
function showgeocode(city) {
const lat = city.coordinates.lat;
const lon = city.coordinates.lon;
const popover = document.getElementById("popover");
popover.innerHTML = `
<strong>${city.city}</strong><br>
Latitude: ${lat}<br>
Longitude: ${lon}<br>
Population: ${city.population.toLocaleString()}<br>
State: ${city.state}<br>
<a href="${city.wikipedia}" target="_blank">Wikipedia</a>
`;
popover.classList.add("show");
}
// --- Search for city ---
function findCityByName(name) {
const search = name.trim().toLowerCase();
return cities.find(c => c.city.toLowerCase() === search) || null;
}
//Function to reset the canvas
function resetCanvasContext() {
ctx.setTransform(1, 0, 0, 1, 0, 0); // Reset any scaling or translation
ctx.globalAlpha = 1.0;
ctx.lineWidth = 1;
ctx.strokeStyle = 'black';
ctx.fillStyle = 'black';
ctx.font = "12px Arial";
}
// Geocode button
geocode.addEventListener("click", function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
hidePlaceholders()
loadCities(function () {
const cityName = prompt("Enter a city name to find its coordinates:");
if (!cityName) return;
const city = findCityByName(cityName);
if (!city) {
alert("City not found.");
return;
}
showgeocode(city);
});
});
// --- Drawing mode (measuring pixel distance)
let drawModeActive = false;
let drawClickCount = 0;
let drawX1, drawY1, drawX2, drawY2;
function handleDrawClick(event) {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
if (drawClickCount === 0) {
drawX1 = x;
drawY1 = y;
drawClickCount = 1;
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(drawX1, drawY1, 5, 0, 2 * Math.PI);
ctx.fill();
} else if (drawClickCount === 1) {
drawX2 = x;
drawY2 = y;
ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(drawX2, drawY2, 5, 0, 2 * Math.PI);
ctx.fill();
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(drawX1, drawY1);
ctx.lineTo(drawX2, drawY2);
ctx.stroke();
const distance = Math.sqrt((drawX2 - drawX1) ** 2 + (drawY2 - drawY1) ** 2);
output.textContent = `Distance: ${distance.toFixed(2)} pixels`;
drawClickCount = 0;
drawModeActive = false; // <-- Reset here
}
};
drawBtn.addEventListener("click", function(){
document.getElementById("popover").classList.remove("show");
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawModeActive = true;
drawClickCount = 0;
output.textContent = "Draw mode: click two points.";
function scaleToCanvas(x, y) {
const scaleX = canvas.width / imgMap.naturalWidth;
const scaleY = canvas.height / imgMap.naturalHeight;
return {
x: x * scaleX,
y: y * scaleY
};
}
});
canvas.addEventListener("click", function(event){
if (drawModeActive) {
handleDrawClick(event);
drawScaleBar(100)
}
});
//-------------------------------DISTANCE Button------------------------
let distanceMode = false;
let validCities = [];
let points = []; // selected points to draw polyline
function hidePlaceholders() {
// Hide distance and area input placeholders if they exist
const distanceInput = document.getElementById("distanceDisplay");
if (distanceInput) distanceInput.style.display = "none";
const areaInput = document.getElementById("areaDisplay");
if (areaInput) areaInput.style.display = "none";
}
function drawPoints() {
for (const city of validCities) {
const x = city["absolute position"].X;
const y = city["absolute position"].Y;
ctx.beginPath();
ctx.arc(x, y, 5, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
}
};
function drawPolyline() {
if (points.length < 2) return;
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.stroke();
}
// Haversine formula to calculate distance (km) between lat/lon points
function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371;
const toRad = deg => deg * Math.PI / 180;
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a = Math.sin(dLat/2)**2 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon/2)**2;
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
function drawScaleBar(lengthInKm = 100) {
if (!validCities || validCities.length < 2) return;
const cityA = validCities[0];
const cityB = validCities[1];
if (!cityA["absolute position"] || !cityB["absolute position"]) return;
// Calculate real distance between these two cities (km)
const realDistKm = calculateDistance(
cityA.coordinates.lat, cityA.coordinates.lon,
cityB.coordinates.lat, cityB.coordinates.lon
);
// Calculate pixel distance between these two points on canvas
const pixelDist = Math.sqrt(
Math.pow(cityB["absolute position"].X - cityA["absolute position"].X, 2) +
Math.pow(cityB["absolute position"].Y - cityA["absolute position"].Y, 2)
);
// Calculate pixels per km
const pixelsPerKm = pixelDist / realDistKm;
// Now calculate the pixel length for the barLengthKm
const barPixelLength = lengthInKm * pixelsPerKm;
// Save the current context state
ctx.save();
// Draw the scale bar at the bottom-right corner
const rect = imgMap.getBoundingClientRect();
const x = rect.width - barPixelLength - 20; // 20px padding from the right edge
const y = rect.height - 20; // 20px padding from the bottom edge
ctx.strokeStyle = "black";
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + barPixelLength, y);
ctx.stroke();
// Draw text above the bar
ctx.fillStyle = "black";
ctx.font = "16px Arial";
ctx.fillText(`${lengthInKm} km`, x, y - 5);
ctx.restore();
}
distanceBtn.addEventListener("click", function () {
document.getElementById("popover").classList.remove("show");
ctx.clearRect(0, 0, canvas.width, canvas.height);
hidePlaceholders();
distanceMode = true;
areaMode = false; // Disable area mode if active
xhr.open("GET", "cities.json", true);
xhr.responseType = "json";
xhr.onload = function () {
if (xhr.status !== 200) return;
const data = xhr.response;
validCities = data.cities.filter(function(city) {
return city["absolute position"] && city.coordinates;
});
points = [];
drawPoints();
drawScaleBar();
};
xhr.send();
});
//
canvas.addEventListener("click", function(event) {
if (!distanceMode) return;
const rect = canvas.getBoundingClientRect();
const clickX = event.clientX - rect.left;
const clickY = event.clientY - rect.top;
const radius = 10;
let selected = null;
for (const city of validCities) {
const x = city["absolute position"].X;
const y = city["absolute position"].Y;
const distance = Math.sqrt((x - clickX) ** 2 + (y - clickY) ** 2);
if (distance <= radius) {
selected = {
x,
y,
lat: city.coordinates.lat,
lon: city.coordinates.lon,
city: city.city
};
break;
}
}
if (selected) {
points.push(selected);
drawPoints();
drawPolyline();
if (points.length > 1) {
let totalDistance = 0;
for (let i = 1; i < points.length; i++) {
const d = calculateDistance(
points[i-1].lat, points[i-1].lon,
points[i].lat, points[i].lon
);
totalDistance += d;
}
updateDistanceDisplay(totalDistance);
}
}
const distanceInput = document.getElementById("distanceDisplay");
if (distanceInput && points.length > 0) {
const lastPoint = points[points.length - 1];
distanceInput.style.left = `${lastPoint.x + 10}px`;
distanceInput.style.top = `${lastPoint.y + 10}px`;
distanceInput.style.display = "block";
localStorage.setItem("distance",distanceInput.value);
const storedVal = localStorage.getItem("distance");
}
drawScaleBar();
});
function updateDistanceDisplay(distance) {
const distanceInput = document.getElementById("distanceDisplay");
if (distanceInput && points.length > 0) {
const lastPoint = points[points.length - 1];
distanceInput.style.left = `${lastPoint.x + 10}px`;
distanceInput.style.top = `${lastPoint.y + 10}px`;
distanceInput.value = `${distance.toFixed(2)} km`;
distanceInput.style.display = "block";
}
}
//------------------------Area button functionality----------------------
let areaMode = false;
areaBtn.addEventListener("click", function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
document.getElementById("popover").classList.remove("show");
hidePlaceholders();
areaMode = true;
distanceMode = false; // Disable distance mode if active
points = []; // Reset points for area calculation
output.textContent = "Area mode: click to add points.";
drawScaleBar();
});
function drawPolygon() {
if (points.length < 2) return;
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.closePath();
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.stroke();
}
canvas.addEventListener("click", function(event) {
if (!areaMode) return;
const rect = canvas.getBoundingClientRect();
const clickX = event.clientX - rect.left;
const clickY = event.clientY - rect.top;
if (points.length > 3 && isNearStartPoint(clickX, clickY)) {
points.push(points[0]);
drawPolygon();
areaMode = false; // Disable area mode after closing the polygon
output.textContent = "Polygon closed.";
} else {
points.push({ x: clickX, y: clickY });
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(clickX, clickY, 5, 0, 2 * Math.PI);
ctx.fill();
// Clear the canvas and redraw the polygon up to the third point
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPolygon();
}
if (points.length > 2) {
const area = calculateArea(points);
output.textContent = `Area: ${area.toFixed(2)} square pixels`;
updateAreaDisplay(area);
drawScaleBar();
localStorage.setItem("area",output.textContent);
const storedVal = localStorage.getItem("area");
}
});
function calculateArea(points) {
let area = 0;
const n = points.length;
for (let i = 0; i < n; i++) {
const j = (i + 1) % n; // wrap around to the first point
area += points[i].x * points[j].y - points[j].x * points[i].y;
}
return Math.abs(area / 2);
}
function updateAreaDisplay(area) {
const areaInput = document.getElementById("areaDisplay");
if (areaInput && points.length > 0) {
const lastPoint = points[points.length - 1];
areaInput.style.left = `${lastPoint.x + 10}px`;
areaInput.style.top = `${lastPoint.y + 10}px`;
areaInput.value = `${area.toFixed(2)} square pixels`;
areaInput.style.display = "block";
}
}
function isNearStartPoint(clickX, clickY) {
const start = points[0];
const distance = Math.sqrt(Math.pow(clickX - start.x, 2) + Math.pow(clickY - start.y, 2));
return distance <= 10;
}
// --- ----------------Save GeoJSON Button ---
geojsonBtn.addEventListener("click", function () {
// Prepare GeoJSON features for cities with time data
const cityFeatures = citiesTime.map(function(city) {
return {
type: "Feature",
properties: {
name: city.name,
timezone: city.timezone,
currentTime: city.currentTime
},
geometry: {
type: "Point",
coordinates: [city.x, city.y]
}
};
});
// Prepare GeoJSON feature for distance polyline if points exist
let distanceFeature = null;
if (points && points.length > 1) {
distanceFeature = {
type: "Feature",
properties: {
type: "distancePath"
},
geometry: {
type: "LineString",
coordinates: points.map(pt => [pt.x, pt.y]),
length: points.map(pt => Math.sqrt(Math.pow(pt.x - points[0].x, 2) + Math.pow(pt.y - points[0].y, 2))).reduce((a, b) => a + b, 0) // Calculate total length
}
};
}
// Combine features
const features = cityFeatures.slice();
if (distanceFeature) {
features.push(distanceFeature);
}
if (features.length === 0) {
alert("There is no data to be saved");
return;
}
const geojson = {
type: "FeatureCollection",
features: features
};
const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
/*
Created an invisible `<a>` (anchor) element,
sets its `href` attribute to the blob URL, and assigns a filename
(`"interactive_map.geojson"`) to the `download` attribute.
By calling `a.click()`, it programmatically triggers a download of the file without requiring any user interaction with the anchor.
*/
const a = document.createElement("a");
a.href = url;
a.download = "interactive_map.geojson";
a.click();
URL.revokeObjectURL(url);
});
// ----------------------- Animate Button in jquery -----------------------
const $animate = $("#animate");
$animate.on("click", function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
$.getJSON("./cities.json", function(data) {
const citiesA = data.cities;
const pinHeadRadius = 6;
const $canvas = $("#mapCanvas");
const canvas = $canvas[0];
const ctx = canvas.getContext('2d');
ctx.font = "bold 24px Arial";
ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.textBaseline = "top";
// Draw the title at the top center of the canvas
ctx.fillText(title.innerText, canvas.width / 2, 0);
$.each(citiesA, function(i, city) {
// Use the cities that have absolute position, since in json not all cities have it!!
let x, y;
if (city["absolute position"] && typeof city["absolute position"].X === "number" && typeof city["absolute position"].Y === "number") {
x = city["absolute position"].X;
y = city["absolute position"].Y;
} else if (city.x !== undefined && city.y !== undefined) {
x = city.x;
y = city.y;
}
if (x !== undefined && y !== undefined) {
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(x, y, pinHeadRadius, 0, Math.PI * 2);
ctx.fill();
} else {
console.warn(`Data for the city ${city.city || i} are missing.`);
}
});
$canvas.effect("pulsate", { times: 5 }, 500);
}).fail(function(xhrObj, error, errorMsg) {
console.log(xhrObj);
console.log(error, errorMsg);
});
});
//----Projekt ENDE