Failed Conditions
Pull Request — master (#250)
by
unknown
09:06
created

pokemon.maps.js ➔ ... ➔ $.done   A

Complexity

Conditions 2
Paths 5

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
c 2
b 0
f 0
nc 5
nop 1
dl 0
loc 17
rs 9.4285
1
/** global: google */
2
/** global: pokemon_id */
3
/** global: navigator */
4
5
var map, heatmap;
6
var pokemonMarkers = [];
7
var updateLiveTimeout;
8
9
var ivMin = 80;
10
var ivMax = 100;
11
12
function initMap() {
13
	$.getJSON( "core/json/variables.json", function( variables ) {
14
		var latitude = Number(variables['system']['map_center_lat']);
15
		var longitude = Number(variables['system']['map_center_long']);
16
		var zoom_level = Number(variables['system']['zoom_level']);
17
		var pokeimg_suffix = variables['system']['pokeimg_suffix'];
18
19
		map = new google.maps.Map(document.getElementById('map'), {
20
			center: {
21
				lat: latitude,
22
				lng: longitude
23
			},
24
			zoom: zoom_level,
25
			zoomControl: true,
26
			scaleControl: false,
27
			scrollwheel: true,
28
			disableDoubleClickZoom: false,
29
			streetViewControl: false,
30
			mapTypeControlOptions: {
31
				mapTypeIds: [
32
					google.maps.MapTypeId.ROADMAP,
33
					'pogo_style',
34
					'dark_style',
35
				]
36
			}
37
		});
38
39
		$.getJSON( 'core/json/pogostyle.json', function( data ) {
40
			var styledMap_pogo = new google.maps.StyledMapType(data, {name: 'PoGo'});
41
			map.mapTypes.set('pogo_style', styledMap_pogo);
42
		});
43
		$.getJSON( 'core/json/darkstyle.json', function( data ) {
44
			var styledMap_dark = new google.maps.StyledMapType(data, {name: 'Dark'});
45
			map.mapTypes.set('dark_style', styledMap_dark);
46
		});
47
		$.getJSON( 'core/json/defaultstyle.json', function( data ) {
48
			map.set('styles', data);
49
		});
50
51
		$.ajax({
52
			'async': true,
53
			'type': "GET",
54
			'global': false,
55
			'dataType': 'json',
56
			'url': "core/process/aru.php",
57
			'data': {
58
				'request': "",
59
				'target': 'arrange_url',
60
				'method': 'method_target',
61
				'type': 'pokemon_coordinates_area'
62
			}
63
		}).done(function(coordinates) {
64
			getArea(coordinates);
65
			if (navigator.geolocation) {
66
				navigator.geolocation.getCurrentPosition(function(position) {
67
					var pos = {
68
						lat: position.coords.latitude,
69
						lng: position.coords.longitude
70
					};
71
					coordinate_area();
72
					if (position.coords.latitude <= max_latitude && position.coords.latitude >= min_latitude) {
0 ignored issues
show
Bug introduced by
The variable min_latitude seems to be never declared. If this is a global, consider adding a /** global: min_latitude */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Bug introduced by
The variable max_latitude seems to be never declared. If this is a global, consider adding a /** global: max_latitude */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
73
						if (position.coords.longitude <= max_longitude && position.coords.longitude >= min_longitude) {
0 ignored issues
show
Bug introduced by
The variable max_longitude seems to be never declared. If this is a global, consider adding a /** global: max_longitude */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
Bug introduced by
The variable min_longitude seems to be never declared. If this is a global, consider adding a /** global: min_longitude */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
74
							map.setCenter(pos);
75
						}
76
					}
77
				});
78
			}
79
		});
80
		
81
		initHeatmap();
82
		initSelector(pokeimg_suffix);
83
		
84
	});
85
}
86
87
function initSelector(pokeimg_suffix){
88
	$('#heatmapSelector').click(function(){
89
		hideLive();
90
		showHeatmap();
91
		$('#heatmapSelector').addClass('active');
92
		$('#liveSelector').removeClass('active');
93
	});
94
	$('#liveSelector').click(function(){
95
		hideHeatmap();
96
		map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
97
		initLive(pokeimg_suffix);
98
		
99
		
100
		$('#liveSelector').addClass('active');
101
		$('#heatmapSelector').removeClass('active');
102
	});
103
}
104
105
function initLive(pokeimg_suffix){
106
	showLive();
107
	$("#liveFilterSelector").rangeSlider({
108
		bounds:{
109
			min: 0,
110
			max: 100
111
		},
112
		defaultValues:{
113
			min: ivMin,
114
			max: ivMax
115
		},
116
		formatter:function(val) {
117
			return "IV: "+Math.round(val)+"%";
118
		}
119
	});
120
	
121
	$("#liveFilterSelector").bind("valuesChanged",function(e, data){
122
		clearTimeout(updateLiveTimeout);
123
		removePokemonMarkerByIv(data.values.min,data.values.max);
124
		ivMin = data.values.min;
125
		ivMax = data.values.max;
126
		updateLive(pokeimg_suffix);
127
	});
128
	updateLive(pokeimg_suffix);
129
	
130
}
131
132
function initHeatmap(){
133
	$.ajax({
134
		'async': true,
135
		'type': "GET",
136
		'global': false,
137
		'dataType': 'json',
138
		'url': "core/process/aru.php",
139
		'data': {
140
			'request': "",
141
			'target': 'arrange_url',
142
			'method': 'method_target',
143
			'type' : 'pokemon_slider_init'
144
		}
145
	}).done(function(bounds){
146
		initHeatmapData(bounds);
147
	});
148
	
149
}
150
151
function initHeatmapData(bounds){
152
	var boundMin = new Date(bounds.min.replace(/-/g, "/"));
153
	var boundMax = new Date(bounds.max.replace(/-/g, "/"));
154
	var selectorMax = boundMax;
155
	var selectorMin = boundMin;
156
157
	// two weeks in millisec
158
	var twoWeeks = 12096e5;
159
	var maxMinus2Weeks = new Date(selectorMax.getTime() - twoWeeks);
160
	if(selectorMin < maxMinus2Weeks){
161
		selectorMin = maxMinus2Weeks;
162
	}
163
164
	// dict with millisec => migration nr.
165
	var migrations = {};
166
	// start at 4 because 06. Oct 2016 was the 4th migration
167
	var migr_nr = 4;
168
	$("#timeSelector").dateRangeSlider({
169
		bounds:{
170
			min: boundMin,
171
			max: boundMax
172
		},
173
		defaultValues:{
174
			min: selectorMin,
175
			max: selectorMax
176
		},
177
		scales: [{
178
			first: function(value) {
179
				// 06. Oct 2016 (4th migration). 2 week schedule starts with this migration
180
				var migrationStart = new Date("2016-10-06T00:00:00Z");
181
				var now = new Date();
182
				var result = new Date();
183
				for (var migration = migrationStart; migration <= now; migration.setTime(migration.getTime() + twoWeeks)) {
184
					if (migration >= value) {
185
						result = migration;
186
						migrations[result.getTime()] = migr_nr;
187
						break;
188
					}
189
					migr_nr++;
190
				}
191
				return result;
192
			},
193
			next: function(value){
194
				var next = new Date(new Date(value).setTime(value.getTime() + twoWeeks));
195
				migr_nr++;
196
				migrations[next.getTime()] = migr_nr;
197
				return next;
198
			},
199
			label: function(value){
200
				if (isMobileDevice() && isTouchDevice()) {
201
					return "#" + migrations[value.getTime()];
202
				}
203
				return "Migration #" + migrations[value.getTime()];
204
			},
205
		}]
206
	});
207
	createHeatmap();
208
209
}
210
211
function createHeatmap() {
212
	
213
	heatmap = new google.maps.visualization.HeatmapLayer({
214
		data: [],
215
		map: map
216
	});
217
218
	var gradient = [
219
		'rgba(0, 255, 255, 0)',
220
		'rgba(0, 255, 255, 1)',
221
		'rgba(0, 191, 255, 1)',
222
		'rgba(0, 127, 255, 1)',
223
		'rgba(0, 63, 255, 1)',
224
		'rgba(0, 0, 255, 1)',
225
		'rgba(0, 0, 223, 1)',
226
		'rgba(0, 0, 191, 1)',
227
		'rgba(0, 0, 159, 1)',
228
		'rgba(0, 0, 127, 1)',
229
		'rgba(63, 0, 91, 1)',
230
		'rgba(127, 0, 63, 1)',
231
		'rgba(191, 0, 31, 1)',
232
		'rgba(255, 0, 0, 1)'
233
	];
234
	heatmap.set('gradient', gradient);
235
	heatmap.setMap(map);
236
	$("#timeSelector").bind("valuesChanged",function(){updateHeatmap()});
237
	$("#timeSelector").dateRangeSlider("min"); // will trigger valuesChanged
238
}
239
240
function updateHeatmap() {
241
	var dateMin = $("#timeSelector").dateRangeSlider("min");
242
	var dateMax = $("#timeSelector").dateRangeSlider("max");
243
	$("#loaderContainer").show();
244
	$.ajax({
245
		'async': true,
246
		'type': "GET",
247
		'global': false,
248
		'dataType': 'json',
249
		'url': "core/process/aru.php",
250
		'data': {
251
			'request': "",
252
			'target': 'arrange_url',
253
			'method': 'method_target',
254
			'type' : 'pokemon_heatmap_points',
255
			'pokemon_id' : pokemon_id,
256
			'start' : Math.floor(dateMin.getTime()/1000),
257
			'end' : Math.floor(dateMax.getTime()/1000)
258
		}
259
	}).done(function(points){
260
		var googlePoints = [];
261
		for (var i = 0; i < points.length; i++) {
262
			googlePoints.push(new google.maps.LatLng(points[i].latitude,points[i].longitude))
263
		}
264
		var newPoints = new google.maps.MVCArray(googlePoints);
265
		heatmap.set('data', newPoints);
266
		$("#loaderContainer").hide();
267
	});
268
}
269
270
function hideHeatmap() {
271
	$("#timeFilterContainer").hide();
272
	heatmap.set('map', null);
273
}
274
275
function showHeatmap() {
276
	$("#timeFilterContainer").show();
277
	heatmap.set('map', map);
278
	hideLive();
279
}
280
281
function hideLive() {
282
	$("#liveFilterContainer").hide();
283
	clearTimeout(updateLiveTimeout);
284
	clearPokemonMarkers();
285
}
286
287
function showLive() {
288
	hideHeatmap();
289
	clearTimeout(updateLiveTimeout);
290
	$("#liveFilterContainer").show();
291
	
292
}
293
294
function updateLive(pokeimg_suffix){
295
	$.ajax({
296
		'async': true,
297
		'type': "POST",
298
		'global': false,
299
		'dataType': 'json',
300
		'url': "core/process/aru.php",
301
		'data': {
302
			'request': "",
303
			'target': 'arrange_url',
304
			'method': 'method_target',
305
			'type' : 'pokemon_live',
306
			'pokemon_id' : pokemon_id,
307
			'inmap_pokemons' : extractEncountersId(),
308
			'ivMin' : ivMin,
309
			'ivMax' : ivMax
310
		}
311
	}).done(function(pokemons){
312
		for (var i = 0; i < pokemons.points.length; i++) {
313
			addPokemonMarker(pokemons.points[i],pokeimg_suffix, pokemons.locale)
314
		}
315
		updateLiveTimeout=setTimeout(function(){ updateLive(pokeimg_suffix) },5000);
316
	});
317
}
318
319
function addPokemonMarker(pokemon,pokeimg_suffix, locale) {
320
	var image = {
321
		url:'core/pokemons/'+pokemon.pokemon_id+pokeimg_suffix,
322
		scaledSize: new google.maps.Size(32, 32),
323
		origin: new google.maps.Point(0,0),
324
		anchor: new google.maps.Point(16, 16),
325
		labelOrigin : new google.maps.Point(16, 36)
326
	};
327
	var encounter = false;
328
	var ivPercent = 100;
329
	if (pokemon.individual_attack != null) {
0 ignored issues
show
Best Practice introduced by
Comparing pokemon.individual_attack to null using the != operator is not safe. Consider using !== instead.
Loading history...
330
		encounter = true;
331
		ivPercent = ((100/45)*(parseInt(pokemon.individual_attack)+parseInt(pokemon.individual_defense)+parseInt(pokemon.individual_stamina))).toFixed(2);
332
	}
333
	var marker = new google.maps.Marker({
334
		position: {lat: parseFloat(pokemon.latitude), lng:parseFloat(pokemon.longitude)},
335
		map: map,
336
		icon: image,
337
		encounterId: pokemon.encounter_id,
338
		ivPercent: ivPercent
339
	});
340
	if (encounter) {
341
		marker.setLabel({
342
			color:getIvColor(ivPercent),
343
			text:ivPercent+"%"
344
		});
345
	}
346
	var contentString = '<div>'+
347
			'<h4> '+pokemon.name+' #'+pokemon.pokemon_id+ (encounter?' IV: '+ivPercent+'% ':'')+'</h4>'+
348
			'<div id="bodyContent">'+
349
				'<p class="disappear_time_display text-center">'+pokemon.disappear_time_real+'<span class="disappear_time_display_timeleft"></span></p>';
350
	if (encounter) {
351
		contentString +=
352
				'<p></p>'+
353
				'<div class="progress" style="height: 6px; width: 120px; margin-bottom: 10px; margin-top: 2px; margin-left: auto; margin-right: auto">'+
354
					'<div title="'+locale.ivAttack+': '+pokemon.individual_attack+'" class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="'+pokemon.individual_attack+'" aria-valuemin="0" aria-valuemax="45" style="width: '+(((100/15)*pokemon.individual_attack)/3)+'%">'+
355
						'<span class="sr-only">'+locale.ivAttack+': '+pokemon.individual_attack+'</span>'+
356
					'</div>'+
357
					'<div title="'+locale.ivDefense+': '+pokemon.individual_defense+'" class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="'+pokemon.individual_defense+'" aria-valuemin="0" aria-valuemax="45" style="width: '+(((100/15)*pokemon.individual_defense)/3)+'%">'+
358
						'<span class="sr-only">'+locale.ivDefense+': '+pokemon.individual_defense+'</span>'+
359
					'</div>'+
360
					'<div title="'+locale.ivStamina+': '+pokemon.individual_stamina+'" class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="'+pokemon.individual_stamina+'" aria-valuemin="0" aria-valuemax="45" style="width: '+(((100/15)*pokemon.individual_stamina)/3)+'%">'+
361
						'<span class="sr-only">'+locale.ivStamina+': '+pokemon.individual_stamina+'</span>'+
362
					'</div>'+
363
				'</div>'+
364
				'<p class="text-center">('+pokemon.individual_attack+"/"+pokemon.individual_defense+"/"+pokemon.individual_stamina+')</p>'+
365
				'<p class="text-center">'+pokemon.quick_move+"/"+pokemon.charge_move+'</p>';
366
		}
367
		contentString +='</div>';
368
369
	var infoWindow = new google.maps.InfoWindow({
370
		content: contentString
371
	});
372
	infoWindow.isClickOpen = false;
373
	marker.addListener('click', function() {
374
		infoWindow.isClickOpen = true;
375
		infoWindow.open(map, this);
376
	});
377
	google.maps.event.addListener(infoWindow,'closeclick',function(){
378
		this.isClickOpen = false;
379
	});
380
	marker.addListener('mouseover', function() {
381
		infoWindow.open(map, this);
382
	});
383
384
	// assuming you also want to hide the infowindow when user mouses-out
385
	marker.addListener('mouseout', function() {
386
		if(infoWindow.isClickOpen === false){
387
			infoWindow.close();
388
		}
389
	});
390
	pokemonMarkers.push(marker);
391
	var now = new Date().getTime();
392
	var endTime = new Date(pokemon.disappear_time_real.replace(/-/g, "/")).getTime();
393
	
394
	setTimeout(function(){ removePokemonMarker(pokemon.encounter_id) },endTime-now);
395
}
396
397
398
function getIvColor(ivPercent){
399
	var ivColor="rgba(0, 0, 0, 0)";
400
	if(ivPercent>80){
401
		ivColor="rgba(0, 0, 255, 0.70)";
402
	}
403
	if(ivPercent>90){
404
		ivColor="rgba(246, 178, 107, 0.90)";
405
	}
406
	if(ivPercent>99){
407
		ivColor="rgba(255, 0, 0, 1)";
408
	}
409
	return ivColor;
410
}
411
412
function clearPokemonMarkers() {
413
	for (var i = 0; i < pokemonMarkers.length; i++) {
414
		pokemonMarkers[i].setMap(null);
415
	}
416
	pokemonMarkers = [];
417
}
418
function removePokemonMarker(encounter_id) {
419
	for (var i = 0; i < pokemonMarkers.length; i++) {
420
		if(pokemonMarkers[i].encounterId == encounter_id){
421
			pokemonMarkers[i].setMap(null);
422
			pokemonMarkers.splice(i,1);
423
			break;
424
		}
425
		
426
	}
427
	
428
}
429
430
function removePokemonMarkerByIv(ivMin,ivMax) {
431
	var cleanMarkers=[];
432
	for (var i = 0; i < pokemonMarkers.length; i++) {
433
		if(pokemonMarkers[i].ivPercent < ivMin || pokemonMarkers[i].ivPercent > ivMax){
434
			pokemonMarkers[i].setMap(null);
435
		}
436
		else{
437
			cleanMarkers.push(pokemonMarkers[i]);
438
		}
439
		
440
	}
441
	pokemonMarkers = cleanMarkers;
442
}
443
444
function extractEncountersId(){
445
	var inmapEncounter = [];
446
	for (var i = 0; i < pokemonMarkers.length; i++) {
447
		inmapEncounter[i]=pokemonMarkers[i].encounterId;
448
	}
449
	
450
	return inmapEncounter;
451
}
452
453
function isTouchDevice() {
454
	// Should cover most browsers
455
	return 'ontouchstart' in window || navigator.maxTouchPoints
456
}
457
458
function isMobileDevice() {
459
	// Basic mobile OS (not browser) detection
460
	return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))
461
}
462
463
function getArea(coordinates){
464
	max_latitude = coordinates.max_latitude;
0 ignored issues
show
Bug introduced by
The variable max_latitude seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.max_latitude.
Loading history...
465
	min_latitude = coordinates.min_latitude;
0 ignored issues
show
Bug introduced by
The variable min_latitude seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.min_latitude.
Loading history...
466
	max_longitude = coordinates.max_longitude;
0 ignored issues
show
Bug introduced by
The variable max_longitude seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.max_longitude.
Loading history...
467
	min_longitude = coordinates.min_longitude;
0 ignored issues
show
Bug introduced by
The variable min_longitude seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.min_longitude.
Loading history...
468
}
469