summaryrefslogtreecommitdiff
path: root/src/static/main.js
blob: ac442fa378e3cdc28ea0c6ef5d6e5f9eaddeab20 (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
/* Map */

const map = L.map('map').setView([55.69, 12.57], 12);

const tiles = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
	maxZoom: 19,
	attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
}).addTo(map);


/* Load image */

current_image = null;

var main_image = document.getElementById('main-image');
var background_image = document.getElementById('background-image');

main_image.onload = function() {
	/* Re-trigger animation */
	main_image.style.animation = 'none';
	main_image.offsetHeight; /* trigger reflow */
	main_image.style.animation = null;
};

function load_image (image_name) {
	current_image_name = image_name;
	url = `/static/pics/mine/${image_name}`;
	/* JS foo to change image https://stackoverflow.com/questions/19396390/load-image-from-javascript */ 
	var newImg = new Image;
	newImg.onload = function() {
		main_image.src = this.src;
		background_image.style.backgroundImage = `url("${this.src}")`;
		
		map.invalidateSize(); // Re-calc the map size after image load, to re-center view & fix fit answer in bounds

		/* Zoom script */
		WZoom.create('#main-image',
			{
				smoothTime: 0,
				width:  main_image.naturalWidth,
				height: main_image.naturalHeight,
				minScale: 1,
				maxScale: 10,
				onGrab: function () {
					main_image.style.cursor = 'grabbing';
				},
				onDrop: function () {
					main_image.style.cursor = 'grab';
				},
			}
		);
	}
	newImg.src = url;
}


async function get_random_image() {
	const url = "/get_random_image.json";
	try {
		const response = await fetch(url);
		if (!response.ok) {
			throw new Error(`Response status: ${response.status}`);
		}

		const img_name = await response.text();

		load_image(img_name);
		
	} catch (error) {
		console.error(error.message);
	}
}

get_random_image()

/* Guess */
current_guess_coordinates = null;
document.getElementById('guess-button').addEventListener("click", function(){ guess(current_image_name, current_guess_coordinates); });
const overlay_distance = document.getElementById('overlay-distance');
const next_button = document.getElementById('next-button');

async function guess(image_name, coordinates) {
	const url = "/guess.json";
	var json = null;
	try {
		const response = await fetch(url,
			{
				method: "POST",
				body: JSON.stringify({ image_name: image_name, coordinates: coordinates})
			}
		);
		if (!response.ok) {
			throw new Error(`Response status: ${response.status}`);
		}

		json = await response.json();
	} catch (error) {
		console.error(error.message);
		throw (error)
	}
	var correct_marker = L.marker(json.correct_coordinates, {'icon': correctIcon, 'title': 'Correct location'}).addTo(correctMarkersGroup);

	/* Add line between guess and correct answer */
	var firstpolyline = new L.Polyline([correct_marker._latlng, guess_marker._latlng], {
		color: 'black',
		weight: 4,
		opacity: 0.5,
		smoothFactor: 1
	});
	firstpolyline.addTo(map);

	// Fit answer & guess in view
	var group = new L.featureGroup([correct_marker, guess_marker]);
	map.fitBounds(group.getBounds(), {padding: [50, 50]});

	overlay_distance.hidden = false;
	overlay_distance.children[1].innerHTML = `≈ ${json.distance_meters} meters` ;
	guess_button.hidden = true;
	next_button.hidden = false;
}

/* Correct location marker */
var correctMarkersGroup = L.layerGroup();
map.addLayer(correctMarkersGroup);

var correctIcon = L.icon({
	iconUrl: '/static/leaflet/images/correct-marker-icon.png',
	shadowUrl: '/static/leaflet/images/marker-shadow.png',
	iconSize: [25, 41], // Size of the icon
	iconAnchor: [12, 41], // Point of the icon which will correspond to marker's location
	shadowSize: [41, 41] // Size of the shadow
});

/* Click map to add marker */

var guess_marker = null;
const guess_button = document.getElementById('guess-button');

var guessIcon = L.icon({
	iconUrl: '/static/leaflet/images/guess-marker-icon.png',
	shadowUrl: '/static/leaflet/images/marker-shadow.png',
	iconSize: [25, 41], // Size of the icon
	iconAnchor: [12, 41], // Point of the icon which will correspond to marker's location
	shadowSize: [41, 41] // Size of the shadow
});

// a layer group, used here like a container for markers
var userMarkersGroup = L.layerGroup();
map.addLayer(userMarkersGroup);

map.on('click', function(e) {
	/* Disallow re-guessing if already submitted */
	if (!next_button.hidden) {
		return;
	}

	// get the count of currently displayed markers
	var markersCount = userMarkersGroup.getLayers().length;

	if (markersCount > 0) {
		userMarkersGroup.clearLayers();
	}
	guess_marker = L.marker(e.latlng, {'icon': guessIcon, 'title': 'Guess location'}).addTo(userMarkersGroup);
	current_guess_coordinates = e.latlng;

	guess_button.hidden = false;
});

/* */

function next() {
	window.location.reload();
}

/* Key bindings */

document.addEventListener('keydown', function(e) {
	if (e.key === 'Escape' || e.keyCode === 27) {
		userMarkersGroup.clearLayers();
		document.getElementById('guess-button').hidden = true;
	} else if (e.key === 'Enter' || e.keyCode === 13 || e.key === 'Space' || e.keyCode === 32) {
		if (guess_marker != null) {
			guess(current_image_name, current_guess_coordinates);
		}
		if (!next_button.hidden) {
			next();
		}
	}
});