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

pokemon.maps.js ➔ initMap   A

Complexity

Conditions 1
Paths 4

Size

Total Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
c 3
b 0
f 0
nc 4
nop 0
dl 0
loc 60
rs 9.5555

1 Function

Rating   Name   Duplication   Size   Complexity  
A pokemon.maps.js ➔ ... ➔ $.getJSON(ꞌcore/json/variables.jsonꞌ) 0 58 2

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