Subversion Repositories eFlore/Applications.moissonnage

Rev

Rev 28 | Rev 37 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
7 delphine 1
// Javascript Document
2
 
3
 
31 alex 4
// ===================================================================================
5
//  FONCTIONS ADDITIONNELLES POUR GERER LES URLS ET L'OUVERTRURE DE NOUVELLE FENETRE
28 alex 6
function convertirEnParametresUrl(objet) {
7 delphine 7
	var parametresUrl = '';
8
	for (attribut in objet) {
9
		if (typeof(objet[attribut]) == 'function' || typeof(objet[attribut]) == 'undefined' ||
31 alex 10
			objet[attribut] == null || objet[attribut] == '*' || objet[attribut] == 0)
7 delphine 11
			continue;
31 alex 12
		parametresUrl += (parametresUrl == '' ? '' : '&') + attribut + "=" + objet[attribut];
7 delphine 13
	}
14
	return parametresUrl;
15
};
16
 
31 alex 17
function recupererParametreDansUrl(nomParametre, chaineRecherche) {
18
	var split = chaineRecherche.split('?');
19
	chaineRecherche = split[split.length-1];
20
	var valeurParametre = null;
21
	var listeParametres = chaineRecherche.split("&");
7 delphine 22
	for (var index = 0; index < listeParametres.length; index ++) {
23
		var split = listeParametres[index].split("=");
24
		if (split[0] == nomParametre) {
31 alex 25
			valeurParametre = split[1];
26
			break;
7 delphine 27
		}
28
	}
31 alex 29
	return valeurParametre;
7 delphine 30
};
31
 
31 alex 32
function estValeurDansTableau(tableau, valeur) {
33
	var index;
34
	for (index = 0; index < tableau.length && tableau[index] != valeur; index ++);
35
	return (tableau.length > 0 && index != tableau.length);
36
}
7 delphine 37
 
31 alex 38
function ouvrirNouvelleFenetre(element, event) {
39
	window.open(element.href);
40
	return arreter(event);
41
}
7 delphine 42
 
31 alex 43
function arreter(event) {
44
	if (event.stopPropagation) {
45
		event.stopPropagation();
46
	} else if (window.event) {
47
		window.event.cancelBubble = true;
48
	}
49
	if (event.preventDefault) {
50
		event.preventDefault();
51
	}
52
	event.returnValue = false;
53
	return false;
54
}
7 delphine 55
 
31 alex 56
 
57
 
58
// =============================================================
59
 
7 delphine 60
var map = null,
28 alex 61
optionsCoucheOSM = {
62
	attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,'
63
	+ ' <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
64
	maxZoom: 18
65
},
66
optionsCoucheGoogle = {
31 alex 67
	attribution: 'Map data &copy;'+new Date().getFullYear()+' <a href="http://maps.google.com">Google</a>',
28 alex 68
	maxZoom: 18
69
},
70
coucheOSM = new L.TileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
71
	optionsCoucheOSM),
72
couchePlanGoogle = new L.TileLayer("http://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}",
73
	optionsCoucheGoogle),
74
coucheSatelliteGoogle = new L.TileLayer("http://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}",
75
	optionsCoucheGoogle),
7 delphine 76
optionsCarte = {
77
	center : new L.LatLng(46, 2),
78
	zoom : 6,
79
	minZoom : 3,
28 alex 80
	maxBounds : [[-85.051129, -180], [85.051129, 180]],
31 alex 81
	layers : [coucheOSM]
7 delphine 82
},
31 alex 83
zoom = 6,
28 alex 84
legende = null,
31 alex 85
coucheDepartement = null,
28 alex 86
infoBulle = null;
7 delphine 87
 
88
var coucheSites = new L.FeatureGroup(),
31 alex 89
points = new Array(),
90
coucheSites = new L.FeatureGroup(),
91
sources = new Object(),
92
formeDonnees = '',
93
popupMaille = null;
7 delphine 94
overlays = [];
95
 
96
var requeteChargementPoints = null,
31 alex 97
	chargementMaillesEnCours = false,
28 alex 98
doitRafraichirCarte = true,
31 alex 99
chargementCommunesEnCours = false,
7 delphine 100
timer = null,
101
url = '';
102
 
103
 
104
 
105
 
106
$(document).ready(function() {
107
	initialiserWidget();
108
});
109
 
110
function initialiserWidget() {
111
	initialiserCarte();
31 alex 112
	dimensionnerOverlay();
113
	initialiserPanneauControle();
114
	initialiserSources();
7 delphine 115
	initialiserListeners();
116
	chargerLimitesCommunales();
31 alex 117
	chargerMaillesVides();
7 delphine 118
	programmerRafraichissementCarte();
119
}
120
 
121
$(window).resize(function() {
122
	dimensionnerCarte();
28 alex 123
	if (infoBulle != null) {
124
		redimensionnerPopup();
125
	}
7 delphine 126
});
127
 
31 alex 128
function dimensionnerOverlay() {
129
	var taille = '1.6';
130
	var tailleMaxIcones = 20;
131
	var padding_icones = 8;
132
	$("#zone-titre h1").css('font-size', (taille)+'em');
133
	$("#zone-titre").css('padding', padding_icones+"px "+padding_icones+"px "+Math.round(padding_icones/4)+"px");
134
	$('#zone-titre').height(tailleMaxIcones*2);
135
	var left = ($(window).width()-$('#zone-titre').width())/2;
136
	$('#zone-titre').css('left',left);
137
}
7 delphine 138
 
31 alex 139
 
7 delphine 140
function dimensionnerCarte() {
141
	$('#map').height($(window).height());
142
	$('#map').width($(window).width());
143
}
144
 
145
function initialiserCarte() {
146
	dimensionnerCarte();
147
	map = L.map('map', optionsCarte);
148
	coucheSites.addTo(map);
149
	coucheOSM.addTo(map);
150
	couchePlanGoogle.addTo(map);
151
	coucheSatelliteGoogle.addTo(map);
152
	var echelle = new L.Control.Scale({
31 alex 153
		maxWidth : 32,
7 delphine 154
		metric : true,
155
		imperial : false,
156
		updateWhenIdle : true
157
	});
158
	map.addControl(echelle);
31 alex 159
	zoom = map.getZoom();
7 delphine 160
}
31 alex 161
 
7 delphine 162
function initialiserListeners() {
28 alex 163
	map.on('moveend', surChangementVueSurCarte);
164
	map.on('zoomend', surChangementVueSurCarte);
7 delphine 165
	map.on('popupclose', function(e) {
166
		masquerInfoBulle();
28 alex 167
		programmerRafraichissementCarte();
7 delphine 168
	});
169
}
170
 
171
function initialiserPanneauControle() {
172
	var baseMaps = {
31 alex 173
		"OpenStreetMap" : coucheOSM,
7 delphine 174
		"Plan" : couchePlanGoogle,
175
		"Satellite" : coucheSatelliteGoogle
176
	};
177
 
178
	var overlayMaps = {};
31 alex 179
	for (var index = 0; index < listeSources.length; index ++) {
180
		sources[listeSources[index]] = estValeurDansTableau(source, listeSources[index]);
181
		overlayMaps[listeSources[index]] = new L.LayerGroup();
7 delphine 182
	}
183
	L.control.layers(baseMaps, overlayMaps).addTo(map);
31 alex 184
	coucheOSM.bringToFront();
185
	couchePlanGoogle.bringToBack();
28 alex 186
	coucheSatelliteGoogle.bringToBack();
7 delphine 187
 
188
	// garder par defaut la couche plan google comme selectionnee dans le panel
189
	var selecteursFonds = $('.leaflet-control-layers-base .leaflet-control-layers-selector');
31 alex 190
	selecteursFonds[0].checked = true;
191
	selecteursFonds[1].checked = false;
7 delphine 192
	selecteursFonds[2].checked = false;
193
}
194
 
28 alex 195
function chargerLimitesCommunales() {
31 alex 196
	coucheDepartement = new L.KML(null, {async : true}).addTo(map);
28 alex 197
	if (urlsLimitesCommunales != null) {
31 alex 198
		coucheDepartement.addKMLFiles(urlsLimitesCommunales);
28 alex 199
	}
200
}
201
 
7 delphine 202
function initialiserSources() {
203
	overlays = $('.leaflet-control-layers-overlays .leaflet-control-layers-selector');
204
	$.each(overlays, function (index, input) {
31 alex 205
		input.value = listeSources[index];
7 delphine 206
		input.id = 'overlay' + (index+1);
31 alex 207
		var lien = '<a href="' + liensVersSources[index] + '" target="_blank">' + nomListeSources[index] + '</a>';
7 delphine 208
		$('#overlay' + (index+1) + ' ~ span').html(lien);
31 alex 209
		input.checked = sources[listeSources[index]];
210
		input.onclick = function(event) {
7 delphine 211
			changerSource(event.target.value);
212
		}
213
	});
214
}
215
 
31 alex 216
function determinerSourcesSelectionnees() {
217
	var sourcesSelectionnees = new Array();
218
	for (source in sources) {
219
		if (sources[source] == true) {
220
			sourcesSelectionnees.push(source);
221
		}
222
	}
223
	return sourcesSelectionnees;
224
}
225
 
28 alex 226
function surChangementVueSurCarte() {
227
	if (doitRafraichirCarte == false) {
228
		doitRafraichirCarte = true;
229
	} else {
31 alex 230
		supprimerTousLayers();
231
		zoom = map.getZoom();
232
		chargerMaillesVides();
28 alex 233
	}
234
}
7 delphine 235
 
31 alex 236
function chargerMaillesVides() {
237
	chargementMaillesEnCours = true;
238
	if (timer != null) {
7 delphine 239
        window.clearTimeout(timer);
31 alex 240
    }
241
	if (requeteChargementPoints != null) {
242
		stopperRequeteAjax();
7 delphine 243
	}
244
	timer = window.setTimeout(function() {
31 alex 245
		var coordonneesBordure = calculerCoordonneesBordure();
246
		var parametres = {
247
				"source" : "floradata",
248
				"bbox" : coordonneesBordure,
249
				"zoom" : map.getZoom()
250
			};
251
			url = urlBase + "mailles?" + convertirEnParametresUrl(parametres);
252
			fonctionCallback = traiterDonneesStations;
253
			executerAJAX();
254
	}, 400);
7 delphine 255
}
256
 
31 alex 257
function programmerRafraichissementCarte(source) {
258
	source = (source == null || source == 'null') ? null : source;
259
	if (!chargementMaillesEnCours) {
260
		if (timer != null) {
261
			window.clearTimeout(timer);
262
		}
263
		if (requeteChargementPoints != null) {
264
			if (source == null) {
265
				stopperRequeteAjax();
266
			}
267
		}
268
		timer = window.setTimeout("rafraichirDonnnees('"+source+"')", 250);
269
    } else {
270
    	window.setTimeout("programmerRafraichissementCarte('"+source+"')", 400);
271
    }
272
}
7 delphine 273
 
31 alex 274
function stopperRequeteAjax() {
275
	requeteChargementPoints.abort();
276
	requeteChargementPoints = null;
277
}
278
 
279
function rafraichirDonnnees(source) {
280
	source = (source == null || source == 'null') ? null : source;
281
	if (coucheDepartement == null || coucheDepartement.getStatus() == KML_READY) {
282
		if (source != null) {
283
			chargerLocalisations(source);
284
		} else {
285
			supprimerLocalisations();
286
			for (source in sources) {
287
				if (sources[source] == true) {
288
					chargerLocalisations(source);
289
				}
290
			}
291
		}
292
	} else {
293
		window.setTimeout("rafraichirDonnnees('"+source+"')", 800);
294
	}
295
}
296
 
297
function supprimerTousLayers() {
7 delphine 298
	coucheSites.clearLayers();
31 alex 299
	points = [];
300
	formeDonnees = '';
7 delphine 301
}
302
 
31 alex 303
function supprimerLocalisations(source) {
304
	source = (typeof(source) == 'undefined') ? null : source;
305
	if (source != null) {
306
		var sourceUrl = recupererParametreDansUrl('source', url);
307
		if (requeteChargementPoints != null && sourceUrl == source && source != null) {
308
			stopperRequeteAjax();
309
		}
310
		coucheSites.eachLayer(function(layer) {
311
			supprimerLayer(layer, source);
312
		});
313
		if (source != null) {
314
			supprimerPointsListe(source);
315
		}
316
		var sourcesSelectionnees = determinerSourcesSelectionnees();
317
		if (sourcesSelectionnees.length == 1 && determinerNombreMarqueurs(sourcesSelectionnees[0]) > 0) {
318
			transformerMaillesEnPoints(sourcesSelectionnees[0]);
319
		}
320
		var sontPointsAffiches = (points.length>0 && determinerNombreMailles(false)==0);
321
		formeDonnees = sontPointsAffiches ? 'point' : 'maille';
322
	}
323
}
7 delphine 324
 
31 alex 325
function estLayerUtilisePourSource(layer, source) {
326
	return (
327
		(layer.typeSite == 'MAILLE' && typeof(layer.nombrePoints[source]) != 'undefined') ||
328
		(layer.typeSite != 'MAILLE' && layer.source == source)
329
	);
330
}
331
 
332
function supprimerLayer(layer, source) {
333
	if (estLayerUtilisePourSource(layer, source)) {
334
		if (layer.typeSite == 'MAILLE') {
335
			supprimerSourceDansMaille(layer, source);
336
		} else {
337
			coucheSites.removeLayer(layer);
338
		}
339
	}
340
}
341
 
342
 
7 delphine 343
function changerSource(projetClique) {
31 alex 344
	var indexProjetClique;
7 delphine 345
	for (var index = 0; index < overlays.length; index ++) {
31 alex 346
		if (overlays[index].value == projetClique) {
347
			indexProjetClique = index;
7 delphine 348
		}
349
	}
31 alex 350
	masquerInfoBulle();
351
	sources[projetClique] = overlays[indexProjetClique].checked;
352
	if (sources[projetClique] == true) {
353
		programmerRafraichissementCarte(projetClique);
354
	} else {
355
		supprimerLocalisations(projetClique);
7 delphine 356
	}
357
}
358
 
359
function afficherMessageChargement(element) {
31 alex 360
	if ($("#zone-chargement").css('display') == 'none') {
361
		var divTmplElement = 'tpl-chargement-' + element;
362
		$("#zone-chargement").append($("#" + divTmplElement).text());
363
		$("#zone-chargement").css('display', 'block');
364
	}
7 delphine 365
}
366
 
367
function masquerMessageChargement() {
368
	$("#zone-chargement").css('display', 'none');
369
	$("#zone-chargement").children().remove();
370
}
371
 
372
 
373
// execution d'une requete AJAX
374
function executerAJAX() {
375
	if (requeteEnCours()) {
376
		masquerMessageChargement();
377
		requeteChargementPoints.abort();
378
	}
379
	requeteChargementPoints = $.getJSON(url).complete(function() {
28 alex 380
		fonctionCallback();
7 delphine 381
	});
382
}
383
 
384
function requeteEnCours() {
385
	return (requeteChargementPoints != null && requeteChargementPoints.readyState != 4);
386
}
387
 
31 alex 388
function estStatutRequeteOK() {
28 alex 389
	return ((requeteChargementPoints.status == 200 || requeteChargementPoints.status == 304)
390
		|| requeteChargementPoints.status == 0);
391
}
7 delphine 392
 
31 alex 393
function chargerLocalisations(source) {
394
	if (requeteEnCours()) {
395
		window.setTimeout("chargerLocalisations('"+source+"')", 400);
396
	} else {
397
		afficherMessageChargement('stations');
398
		// generer l'URL du script a interroger sur le serveur
399
		var coordonneesBordure = calculerCoordonneesBordure();
400
		var parametres = {
401
			"source" : source,
402
			"num_taxon" : numTaxon,
403
			"referentiel" : referentiel,
404
			"dept" : dept,
405
			"nn" : nn,
406
			"auteur" : auteur,
407
			"date_debut" : dateDebut,
408
			"date_fin" : dateFin,
409
			"bbox" : coordonneesBordure,
410
			"nb_jours" : nbJours,
411
			"zoom" : map.getZoom()
412
		};
413
		url = urlBase + "stations?" + convertirEnParametresUrl(parametres);
414
		fonctionCallback = traiterDonneesStations;
415
		executerAJAX();
416
	}
28 alex 417
}
7 delphine 418
 
419
function calculerCoordonneesBordure() {
28 alex 420
	var bordure = map.getBounds();
31 alex 421
	var ouest = bordure.getSouthWest().lng.toFixed(6),
422
		sud = Math.max(bordure.getSouthWest().lat, -85.051129).toFixed(6),
423
		est = bordure.getNorthEast().lng.toFixed(6),
424
		nord = Math.min(bordure.getNorthEast().lat, 85.051129).toFixed(6);
7 delphine 425
	// appliquer les limites possibles de la projection actuellement utilisee aux coordonnees
426
	// longitudes ouest et est de la bbox (permettra d'eviter de renvoyer des messages d'erreur)
427
	if (ouest < -180) {
428
		ouest += 360;
429
	} else if (ouest > 180) {
430
		ouest -= 360;
431
	}
432
	if (est < -180) {
433
		est += 360;
434
	} else if (est > 180) {
435
		est -= 360;
436
	}
437
	return [ouest, sud, est, nord].join(',');
438
}
439
 
28 alex 440
function traiterDonneesStations() {
441
	masquerMessageChargement();
442
	var texte = requeteChargementPoints.responseText;
31 alex 443
	if (!estStatutRequeteOK()) {
28 alex 444
		alert(texte);
445
	} else {
446
		var donneesJSON = eval("(function(){return " + texte + ";})()");
31 alex 447
		if (donneesJSON != null && typeof(donneesJSON.features) != 'undefined') {
448
			ajouterStationsSurCarte(donneesJSON);
28 alex 449
		}
450
	}
451
}
7 delphine 452
 
31 alex 453
function ajouterStationsSurCarte(data) {
454
	if (doitTransformerEnMaille(data.stats)) {
455
		if (points.length > 0 && data.stats.source != '') {
456
			combinerMaillesEtPoints();
7 delphine 457
		}
31 alex 458
		formeDonnees = 'maille';
459
	} else {
460
		formeDonnees = data.stats.formeDonnees;
7 delphine 461
	}
31 alex 462
	var sourceDonnees = data.stats.source;
463
	for (var index = 0; index < data.features.length; index ++) {
464
		ajouterStation(data.features[index]);
465
	}
466
	if (formeDonnees == 'maille' && data.stats.sites > 0) {
7 delphine 467
		afficherLegende();
31 alex 468
		regenererInfobulleMailles();
469
	} else {
7 delphine 470
		masquerLegende();
471
	}
31 alex 472
	if (chargementMaillesEnCours) {
473
		chargementMaillesEnCours = false;
474
		programmerRafraichissementCarte();
475
	}
7 delphine 476
}
477
 
31 alex 478
function ajouterStation(feature) {
479
	if (feature.properties.typeSite == 'MAILLE') {
480
		traiterMaille(feature);
481
	} else {
482
		ajouterPoint(feature);
483
	}
484
}
485
 
486
function doitTransformerEnMaille(statsFeatures) {
487
	var condition1 = (formeDonnees == 'point' && statsFeatures.formeDonnees =='maille');
488
	var condition2 = (formeDonnees == 'maille' && statsFeatures.formeDonnees =='point'
489
		&& determinerNombreMailles(false) > 0);
490
	var condition3 = (statsFeatures.formeDonnees == 'point' && map.getZoom() <= ZOOM_MAXIMUM_MAILLAGE
491
		&& (points.length+statsFeatures.sites) > SEUIL_MAILLAGE);
492
	return (condition1 || condition2 || condition3);
493
}
494
 
495
 
496
 
497
// ====================================================================
498
// Gestion des mailles
499
 
500
var optionsMaille = {
501
	color: '#FFFFFF',
502
	opacity : 0.7,
503
	weight: 1,
504
	fillOpacity : 0.6
505
};
506
 
507
function determinerNombreMailles(prendToutesMailles) {
508
	var nombreMailles = 0;
509
	coucheSites.eachLayer(function(layer) {
510
		if ('typeSite' in layer && layer.typeSite == 'MAILLE') {
511
			var nombrePoints = 0;
512
			for (var source in layer.nombrePoints) {
513
				nombrePoints = layer.nombrePoints[source];
514
			}
515
			if (prendToutesMailles || nombrePoints>0) {
516
				nombreMailles ++;
517
			}
518
		}
519
	});
520
	return nombreMailles;
521
}
522
 
523
function traiterMaille(feature) {
7 delphine 524
	var coordonnees = [];
525
	for (var i = 0; i < feature.geometry.coordinates.length; i++) {
526
		var sommet = new L.LatLng(feature.geometry.coordinates[i][0], feature.geometry.coordinates[i][1]);
527
		coordonnees.push(sommet);
528
	}
31 alex 529
	var maille = rechercherMailleExistante(coordonnees);
530
	if (maille) {
531
		mettreAJourMaille(maille, feature);
532
	} else if (feature.properties.nombrePoints > 0) {
533
		ajouterMaille(feature);
534
	}
7 delphine 535
}
536
 
31 alex 537
function rechercherMailleExistante(coordonnees) {
538
	var mailleTrouvee = null;
539
	coucheSites.eachLayer(function(layer) {
540
		if ('typeSite' in layer && layer.typeSite == 'MAILLE') {
541
			if (sontMaillesIdentiques(coordonnees, layer._latlngs)) {
542
				mailleTrouvee = layer;
543
				return;
544
			}
545
		}
7 delphine 546
	});
31 alex 547
	return mailleTrouvee;
7 delphine 548
}
549
 
31 alex 550
function sontMaillesIdentiques(coordonnees1, coordonnees2) {
551
	return (
552
		coordonnees1[0].lat == coordonnees2[0].lat &&
553
		coordonnees1[0].lng == coordonnees2[0].lng &&
554
		coordonnees1[2].lat == coordonnees2[2].lat &&
555
		coordonnees1[2].lng == coordonnees2[2].lng
556
	);
557
}
558
 
559
function ajouterMaille(feature) {
560
	var coordonnees = [];
561
	for (var i = 0; i < feature.geometry.coordinates.length; i++) {
562
		var sommet = new L.LatLng(feature.geometry.coordinates[i][0], feature.geometry.coordinates[i][1]);
563
		coordonnees.push(sommet);
28 alex 564
	}
31 alex 565
	var maille = new L.Polygon(coordonnees);
566
	maille.setStyle(optionsMaille);
567
	maille.typeSite = feature.properties.typeSite;
568
	maille.nombrePoints = new Object();
569
	var nombreAAjouter = feature.properties.nombrePoints == null ? 0 : parseInt(feature.properties.nombrePoints);
570
	maille.nombrePoints[feature.properties.source] = nombreAAjouter;
571
	coucheSites.addLayer(maille);
572
	colorerMaille(maille);
28 alex 573
}
574
 
31 alex 575
function mettreAJourMaille(maille, feature) {
576
	var nombreAAjouter = feature.properties.nombrePoints == null ? 0 : parseInt(feature.properties.nombrePoints);
577
	/*if (typeof(maille.nombrePoints[feature.properties.source]) == 'undefined') {
578
		maille.nombrePoints[feature.properties.source] = nombreAAjouter;
7 delphine 579
	} else {
31 alex 580
		maille.nombrePoints[feature.properties.source] += nombreAAjouter;
581
	}*/
582
	maille.nombrePoints[feature.properties.source] = nombreAAjouter;
583
	colorerMaille(maille);
584
}
585
 
586
function regenererInfobulleMailles() {
587
	$('.leaflet-clickable').addClass('tooltip');
588
	coucheSites.eachLayer(function(layer) {
589
		if (layer.typeSite == 'MAILLE') {
590
			genererInfobulle(layer);
591
		}
592
	});
593
}
594
 
595
function colorerMaille(maille) {
596
	var nombrePoints = 0;
597
	for (sourceMaille in maille.nombrePoints) {
598
		nombrePoints += maille.nombrePoints[sourceMaille];
7 delphine 599
	}
31 alex 600
	if (nombrePoints > 0) {
601
		maille.on('click', surClicMaille);
602
		maille.setStyle({fillColor : genererCouleur(nombrePoints), fillOpacity: 0.45, opacity: 0.7});
603
	} else {
604
		maille.setStyle({fillOpacity: 0, opacity: 0});
605
		maille.off('click', surClicMaille);
606
	}
7 delphine 607
}
608
 
31 alex 609
function surClicMaille(event) {
610
	map.fitBounds(event.layer.getBounds());
611
}
612
 
613
function genererCouleur(nombrePoints) {
28 alex 614
	var couleur = {'bleu': 231, 'vert': 224, 'rouge': 64},
615
		seuils = [1, 10, 50 ,100, 500, 1000, 2500],
616
		pas = 26,
617
		position = 0;
618
	for (var index = 1; index < seuils.length-1 && nombrePoints >= seuils[index]; index ++) {
619
		position ++;
7 delphine 620
	}
28 alex 621
	couleur.vert -= position*pas;
622
	return 'rgb('+couleur.bleu+','+couleur.vert+','+couleur.rouge+')';
7 delphine 623
}
624
 
625
function afficherLegende() {
31 alex 626
	if (legende == null) {
627
		legende = new L.Control({position : 'bottomright'});
628
		legende.onAdd = function(map) {
629
			return construireContenuHtmlLegende();
630
		};
631
		map.addControl(legende);
632
	}
7 delphine 633
}
634
 
28 alex 635
function construireContenuHtmlLegende() {
636
	var div = L.DomUtil.create('div', 'info');
637
	div.innerHTML = '<h4>' + titreLegende + '</h4>';
638
	var seuils = [1, 10, 50 ,100, 500, 1000, 2500];
639
	var labels = [];
640
	for (var i = 0; i < seuils.length; i ++) {
641
		div.innerHTML +=
642
			'<div class="legend">'+
31 alex 643
				'<span style="background:' + genererCouleur(seuils[i] + 1) + '"></span>'+
28 alex 644
				seuils[i]+ (i + 1 < seuils.length ? '&ndash;' + seuils[i + 1] : '+')+
645
			'</div>';
7 delphine 646
	}
28 alex 647
	return div;
7 delphine 648
}
649
 
28 alex 650
function masquerLegende() {
31 alex 651
	if (legende != null) {
652
		map.removeControl(legende);
653
		legende = null;
654
	}
28 alex 655
}
7 delphine 656
 
31 alex 657
function supprimerSourceDansMaille(maille, sourceSuppression) {
658
	if (typeof(maille.nombrePoints[sourceSuppression]) != 'undefined') {
659
		maille.nombrePoints[sourceSuppression] = 0;
660
		colorerMaille(maille);
661
		genererInfobulle(maille);
662
	}
663
}
7 delphine 664
 
31 alex 665
function genererInfobulle(maille) {
666
	var nombrePoints = 0,
667
		nombreSources = 0;
668
		contenuTexte = '';
669
	for (sourceMaille in maille.nombrePoints) {
670
		nombrePoints = maille.nombrePoints[sourceMaille];
671
		if (nombrePoints > 0) {
672
			contenuTexte += (contenuTexte.length==0 ?'' : '\n')+
673
				sourceMaille+' : '+maille.nombrePoints[sourceMaille];
674
		}
675
		nombreSources ++;
676
	}
677
	if (nombreSources > 0) {
678
		$(maille._path).addClass('tooltip');
679
		$(maille._path).attr('title',contenuTexte);
680
	}
681
}
28 alex 682
 
31 alex 683
 
684
 
685
 
686
// ====================================================================
687
// Gestion des marqueurs
688
 
689
function ajouterPoint(feature) {
690
	var iconePoint = new L.Icon({ iconUrl : pointImageUrl,   iconSize : [16, 16] }),
691
		iconeCommune   = new L.Icon({ iconUrl : communeImageUrl, iconSize : [24, 32] }),
692
		icone = (feature.properties.typeSite == 'STATION') ? iconePoint : iconeCommune,
693
		point = new L.LatLng(feature.geometry.coordinates[0], feature.geometry.coordinates[1]),
694
		marker = new L.Marker(point, {
695
			icon  : icone,
696
			title : feature.properties.nom
697
		})
698
	marker.typeSite = feature.properties.typeSite;
699
	marker.source = feature.properties.source;
700
	marker.on('click', surClicMarqueur);
701
	points.push(marker);
702
	if (formeDonnees != 'maille') {
703
		coucheSites.addLayer(marker);
704
	} else {
705
		ajouterPointDansMaille(marker);
706
	}
707
}
708
 
709
function ajouterPointDansMaille(point) {
710
	var maille = null;
711
	coucheSites.eachLayer(function(layer) {
712
		if (layer.typeSite == 'MAILLE' && layer.getBounds().contains(point.getLatLng())) {
713
			maille = layer;
714
			return;
715
		}
716
	});
717
	if (typeof(maille.nombrePoints[point.source]) == 'undefined') {
718
		maille.nombrePoints[point.source] = 1;
719
	} else {
720
		maille.nombrePoints[point.source] += 1;
721
	}
722
	colorerMaille(maille);
723
}
724
 
725
function combinerMaillesEtPoints() {
726
	enleverMarqueursCarte();
727
	coucheSites.eachLayer(function(layer) {
728
		if (layer.typeSite == 'MAILLE') {
729
			var nombrePoints = compterNombrePointsDansMaille(layer);
730
			ajouterNombrePointsDansMaille(layer, nombrePoints);
731
		}
732
	});
733
}
734
 
735
function determinerNombreMarqueurs(source) {
736
	var nombrePoints = 0;
737
	for (var index = 0; index < points.length; index ++) {
738
		if (points[index].source == source) {
739
			nombrePoints += 1;
740
		}
741
	}
742
	return nombrePoints;
743
}
744
 
745
function enleverMarqueursCarte() {
746
	coucheSites.eachLayer(function(layer) {
747
		if (layer.typeSite != 'MAILLE') {
748
			coucheSites.removeLayer(layer);
749
		}
750
	});
751
}
752
 
753
function compterNombrePointsDansMaille(maille) {
754
	var nombrePoints = {};
755
	for (var index = 0; index < points.length; index ++) {
756
		if (maille.getBounds().contains(points[index].getLatLng())) {
757
			var source = points[index].source;
758
			if (typeof(nombrePoints[source]) == 'undefined') {
759
				nombrePoints[source] = 1;
760
			} else {
761
				nombrePoints[source] += 1;
762
			}
763
		}
764
	}
765
	return nombrePoints;
766
}
767
 
768
function ajouterNombrePointsDansMaille(maille, nombrePoints) {
769
	for (sourceDonnees in nombrePoints) {
770
		if (typeof(maille.nombrePoints[sourceDonnees]) == 'undefined') {
771
			maille.nombrePoints[sourceDonnees] = nombrePoints[sourceDonnees];
772
		} else {
773
			maille.nombrePoints[sourceDonnees] += nombrePoints[sourceDonnees];
774
		}
775
	}
776
	colorerMaille(maille);
777
}
778
 
779
function supprimerPointsListe(sourceDonnees) {
780
	var index = 0;
781
	while (index < points.length) {
782
		if (points[index].source == sourceDonnees) {
783
			points.splice(index, 1);
784
		} else {
785
			index ++;
786
		}
787
	}
788
}
789
 
790
function transformerMaillesEnPoints(sourceDonnees) {
791
	coucheSites.eachLayer(function(layer) {
792
		if (layer.typeSite == 'MAILLE' && typeof(layer.nombrePoints[sourceDonnees]) != 'undefined') {
793
			supprimerSourceDansMaille(layer, sourceDonnees);
794
		}
795
	});
796
	for (var index = 0; index < points.length; index ++) {
797
		coucheSites.addLayer(points[index]);
798
	}
799
}
800
 
28 alex 801
function surClicMarqueur(event) {
7 delphine 802
	var latitude = event.target.getLatLng().lat;
803
	var longitude = event.target.getLatLng().lng;
804
	pointClique = event.target;
805
	afficherMessageChargement('observations');
28 alex 806
	var parametres = {
31 alex 807
		"source" : pointClique.source,
808
		"num_taxon" : numTaxon,
28 alex 809
		"referentiel" : referentiel,
810
		"auteur" : auteur,
31 alex 811
		"nn" : nn,
812
		"type_site" : pointClique.typeSite,
813
		"date_debut" : dateDebut,
814
		"date_fin" : dateFin,
28 alex 815
		"longitude" : longitude,
31 alex 816
		"latitude" : latitude,
817
		"nb_jours" : nbJours
28 alex 818
	};
819
	url = urlBase + "observations?" + convertirEnParametresUrl(parametres);
820
	fonctionCallback = traiterDonneesObservations;
821
	executerAJAX();
822
}
823
 
824
function traiterDonneesObservations() {
825
	masquerMessageChargement();
826
	var texte = requeteChargementPoints.responseText;
31 alex 827
	if (!estStatutRequeteOK()) {
28 alex 828
		alert(texte);
829
	} else {
830
		obsJSON = eval("(function(){return " + texte + ";})()");
31 alex 831
		if (obsJSON != null) {
832
			viderListeObservations();
833
			if (obsJSON.total > 0) {
834
				doitRafraichirCarte = false;
835
				map.setView(new L.LatLng(pointClique.getLatLng().lat, pointClique.getLatLng().lng), map.getZoom());
836
				afficherInfoBulle();
837
			} else if (infoBulle != null)  {
838
				masquerInfoBulle();
839
			}
7 delphine 840
		}
841
	}
842
}
843
 
28 alex 844
function viderListeObservations() {
845
	obsStation = new Array();
846
}
7 delphine 847
 
848
 
31 alex 849
 
850
 
28 alex 851
// ====================================================================
31 alex 852
// Gestion de l'infobulle
7 delphine 853
 
28 alex 854
var obsJSON = null,
7 delphine 855
	pointClique = null,
856
	obsStation = [],
857
	typeAffichage = "";
858
 
859
function afficherInfoBulle() {
860
	var latitude = pointClique.getLatLng().lat;
861
	var longitude = pointClique.getLatLng().lng;
28 alex 862
	infoBulle = new L.Popup({maxWidth : definirLargeurInfoBulle(), maxHeight : 350});
7 delphine 863
	infoBulle.setLatLng(new L.LatLng(latitude, longitude));
864
	infoBulle.setContent($("#tpl-obs").html());
28 alex 865
	infoBulle.openOn(map);
866
	remplirContenuPopup();
867
}
868
 
869
function definirLargeurInfoBulle() {
870
	var largeurViewPort = $(window).width();
871
	var lageurInfoBulle = null;
872
	if (largeurViewPort < 800) {
873
		largeurInfoBulle = 400;
874
	} else if (largeurViewPort >= 800 && largeurViewPort < 1200) {
875
		largeurInfoBulle = 500;
876
	} else if (largeurViewPort >= 1200) {
877
		largeurInfoBulle = 600;
878
	}
879
	return largeurInfoBulle;
880
}
881
 
882
function redimensionnerPopup() {
883
	$('.leaflet-popup-content*').css('width',  definirLargeurInfoBulle());
884
	$('#info-bulle').css('width',  definirLargeurInfoBulle());
885
}
886
 
887
function remplirContenuPopup() {
7 delphine 888
	ajouterTableauTriable("#obs-tableau");
889
	ajouterTitre();
890
	afficherOnglets();
891
	afficherTexteStationId();
892
}
893
 
894
function masquerInfoBulle() {
31 alex 895
	if (infoBulle != null && map.hasLayer(infoBulle)) {
7 delphine 896
		map.removeLayer(infoBulle);
897
	}
898
	infoBulle = null;
899
}
900
 
901
function ajouterTitre() {
902
	var texteStationTitre = obsJSON.total + ' observation' + (obsJSON.total > 1 ? 's' : '')
903
		+ ' pour ' + (pointClique.options.type=='STATION' ? 'la station : ' : 'la commune : ')
904
		+ pointClique.options.title;
905
	$('#obs-station-titre').text(texteStationTitre);
906
}
907
 
908
function selectionnerOnglet() {
909
	$("#obs-vue-" + typeAffichage).css("display", "block");
910
	$('#obs-tableau-lignes').empty();
911
	$('#obs-liste-lignes').empty();
912
	if (typeAffichage=='liste') {
913
		$("#obs-vue-tableau").css("display", "none");
914
	} else {
915
		$("#obs-vue-liste").css("display", "none");
916
	}
917
}
918
 
919
function ajouterObservationsDansHTML() {
920
	if (obsStation.length==0) {
921
		// premiere execution de la fonction : faire une copie des objets JSON decrivant les observations
922
		for (var index = 0; index < obsJSON.observations.length; index ++) {
923
			obsStation.push(obsJSON.observations[index]);
924
		}
925
	}
926
	var obsPage = [];
927
	for (var index = 0; index < obsStation.length; index ++) {
928
		obsPage.push(obsStation[index]);
929
	}
930
	$("#tpl-obs-"+typeAffichage).tmpl(obsPage).appendTo("#obs-"+typeAffichage+"-lignes");
931
}
932
 
933
function afficherOnglets() {
934
	var $tabs = $('#obs').tabs();
935
	$('#obs').bind('tabsselect', function(event, ui) {
936
		if (ui.panel.id == 'obs-vue-tableau') {
937
			surClicAffichageTableau();
938
		} else if (ui.panel.id == 'obs-vue-liste') {
939
			surClicAffichageListe();
940
		}
941
	});
942
	if (obsJSON.total > 4) {
943
		surClicAffichageTableau();
944
	} else {
945
		$tabs.tabs('select', "#obs-vue-liste");
946
	}
947
}
948
 
949
function surClicAffichageTableau() {
950
	typeAffichage = 'tableau';
951
	selectionnerOnglet();
952
	ajouterObservationsDansHTML();
953
	mettreAJourTableauTriable("#obs-tableau");
954
}
955
 
956
function surClicAffichageListe() {
957
	typeAffichage = 'liste';
958
	selectionnerOnglet();
959
	ajouterObservationsDansHTML();
960
}
961
 
962
function ajouterTableauTriable(element) {
963
	$.tablesorter.addParser({
964
		id: 'date_cel',
965
		is: function(s) {
31 alex 966
			// doit retourner false si le parseur n'est pas autodétecté
7 delphine 967
			return /^\s*\d{2}[\/-]\d{2}[\/-]\d{4}\s*$/.test(s);
968
		},
969
		format: function(date) {
970
			// Transformation date jj/mm/aaaa en aaaa/mm/jj
971
			date = date.replace(/^\s*(\d{2})[\/-](\d{2})[\/-](\d{4})\s*$/, "$3/$2/$1");
972
			// Remplace la date par un nombre de millisecondes pour trier numériquement
973
			return $.tablesorter.formatFloat(new Date(date).getTime());
974
		},
975
		type: 'numeric'
976
	});
977
	$(element).tablesorter({
978
        headers: {
979
			1: {
980
            	sorter:'date_cel'
981
        	}
31 alex 982
    	}
7 delphine 983
	});
984
}
985
 
986
function mettreAJourTableauTriable(element) {
987
	$(element).trigger('update');
988
}
989
 
990
function afficherTexteStationId() {
991
	var latitude = pointClique.getLatLng().lat;
992
	var longitude = pointClique.getLatLng().lng;
31 alex 993
	var texteStationId = pointClique.typeSite+':'+latitude+'|'+longitude+', SOURCE:'+pointClique.source;
7 delphine 994
	$('#obs-station-id').text(texteStationId);
995
}