Subversion Repositories eFlore/Applications.moissonnage

Rev

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

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