Failed Conditions
Pull Request — master (#250)
by
unknown
02:27
created

getJSON(ꞌcore/json/variables.jsonꞌ)   A

Complexity

Conditions 2
Paths 5

Size

Total Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 2
c 3
b 0
f 0
nc 5
nop 1
dl 0
loc 58
rs 9.639

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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