Failed Conditions
Pull Request — master (#275)
by Ramiro
02:38
created

pokemon.maps.js ➔ getMarkerLabel   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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