Subversion Repositories eFlore/Applications.moissonnage

Rev

Rev 28 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
7 delphine 1
// Javascript Document
2
 
3
 
4
//==============================================================
5
//  FONCTIONS ADDITIONNELLES POUR GERER LES URLS
6
convertirEnParametresUrl = function(objet) {
7
	var parametresUrl = '';
8
	for (attribut in objet) {
9
		if (typeof(objet[attribut]) == 'function' || typeof(objet[attribut]) == 'undefined' ||
10
			objet[attribut] == null)
11
			continue;
12
		parametresUrl += (parametresUrl == '' ? '' : '&') + attribut + "=" + objet[attribut].toString();
13
	}
14
	return parametresUrl;
15
};
16
 
17
parametreDansUrl = function(nomParametre) {
18
	var listeParametres = location.search.substring(1).split("&");
19
	for (var index = 0; index < listeParametres.length; index ++) {
20
		var split = listeParametres[index].split("=");
21
		if (split[0] == nomParametre) {
22
			return true;
23
		}
24
	}
25
	return false;
26
};
27
 
28
//=============================================================
29
 
30
 
31
 
32
var map = null,
33
optionsCarte = {
34
	center : new L.LatLng(46, 2),
35
	zoom : 6,
36
	minZoom : 3,
37
	maxBounds : [[-85.051129, -180], [85.051129, 180]]
38
},
39
coucheOSM, couchePlanGoogle, coucheSatelliteGoogle,
40
bordure = null,
41
legende = null;
42
 
43
var iconePoint = new L.Icon({ iconUrl : pointImageUrl,   iconSize : [16, 16] }),
44
iconeCommune   = new L.Icon({ iconUrl : communeImageUrl, iconSize : [24, 32] });
45
 
46
var coucheSites = new L.FeatureGroup(),
47
overlays = [];
48
 
49
var requeteChargementPoints = null,
50
timer = null,
51
url = '';
52
 
53
 
54
 
55
 
56
$(document).ready(function() {
57
	initialiserWidget();
58
});
59
 
60
function initialiserWidget() {
61
	initialiserCarte();
62
	initialiserListeners();
63
	initialiserPanneauControle();
64
	chargerLimitesCommunales();
65
	if (!parametreDansUrl('source')) {
66
		initialiserSources();
67
	}
68
	programmerRafraichissementCarte();
69
}
70
 
71
$(window).resize(function() {
72
	dimensionnerCarte();
73
});
74
 
75
 
76
function dimensionnerCarte() {
77
	$('#map').height($(window).height());
78
	$('#map').width($(window).width());
79
}
80
 
81
function initialiserCarte() {
82
	dimensionnerCarte();
83
	// afficher la carte et ajouter un fond cartographique OpenStreetMap
84
	map = L.map('map', optionsCarte);
85
	coucheSites.addTo(map);
86
 
87
	var optionsCoucheOSM = {
88
		attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors,'
89
		+ ' <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
90
		maxZoom: 18
91
	};
92
	var optionsCoucheGoogle = {
93
		attribution: 'Map data &copy;' + new Date().getFullYear() + ' <a href="http://maps.google.com">Google</a>',
94
		maxZoom: 18
95
	};
96
	coucheOSM = new L.TileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
97
		optionsCoucheOSM);
98
	coucheOSM.addTo(map);
99
	couchePlanGoogle = new L.TileLayer("http://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}",
100
		optionsCoucheGoogle);
101
	couchePlanGoogle.addTo(map);
102
	coucheSatelliteGoogle = new L.TileLayer("http://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}",
103
		optionsCoucheGoogle);
104
	coucheSatelliteGoogle.addTo(map);
105
 
106
	// ajout echelle
107
	var echelle = new L.Control.Scale({
108
		maxWidth : 100,
109
		metric : true,
110
		imperial : false,
111
		updateWhenIdle : true
112
	});
113
	map.addControl(echelle);
114
}
115
 
116
function chargerLimitesCommunales() {
117
	/*if (urlsLimitesCommunales != null) {
118
		for (urlId in urlsLimitesCommunales) {
119
			var url = urlsLimitesCommunales[urlId];
120
			var track = new L.KML(url, {async: true});
121
			/*ctaLayer = new google.maps.KmlLayer(url, {preserveViewport: true});
122
			alert(url);
123
			ctaLayer.setMap(map);
124
		}
125
	}*/
126
}
127
 
128
function initialiserListeners() {
129
	// evenements sur deplacement ou zoom sur la carte
130
	map.on('moveend', programmerRafraichissementCarte);
131
	map.on('zoomend', programmerRafraichissementCarte);
132
 
133
	map.on('popupclose', function(e) {
134
		masquerInfoBulle();
135
	});
136
}
137
 
138
function initialiserPanneauControle() {
139
	var baseMaps = {
140
		"OSM" : coucheOSM,
141
		"Plan" : couchePlanGoogle,
142
		"Satellite" : coucheSatelliteGoogle
143
	};
144
 
145
	var overlayMaps = {};
146
	if (!parametreDansUrl('source')) {
147
		for (var index = 0; index < nomSources.length; index ++) {
148
			overlayMaps[nomSources[index]] = new L.LayerGroup();
149
		}
150
	}
151
	L.control.layers(baseMaps, overlayMaps).addTo(map);
152
 
153
	// garder par defaut la couche plan google comme selectionnee dans le panel
154
	var selecteursFonds = $('.leaflet-control-layers-base .leaflet-control-layers-selector');
155
	selecteursFonds[0].checked = false;
156
	selecteursFonds[1].checked = true;
157
	selecteursFonds[2].checked = false;
158
	coucheOSM.bringToBack();
159
	couchePlanGoogle.bringToFront();
160
	coucheSatelliteGoogle.bringToBack();
161
}
162
 
163
function initialiserSources() {
164
	overlays = $('.leaflet-control-layers-overlays .leaflet-control-layers-selector');
165
	$.each(overlays, function (index, input) {
166
		input.value = sources[index];
167
		input.id = 'overlay' + (index+1);
168
		var lien = '<a href="' + liensVersSources[index] + '" target="_blank">' + nomSources[index] + '</a>';
169
		$('#overlay' + (index+1) + ' ~ span').html(lien);
170
		input.type = 'radio';
171
		input.checked = (sources[index] == source);
172
		input.onchange = function(event) {
173
			// evenement sur selection/deselection overlay dans sa checkbox
174
			changerSource(event.target.value);
175
		}
176
	});
177
}
178
 
179
 
180
function programmerRafraichissementCarte() {
181
	if(timer != null) {
182
        window.clearTimeout(timer);
183
    }
184
	if(requeteChargementPoints != null) {
185
		requeteChargementPoints.abort();
186
		requeteChargementPoints = null;
187
	}
188
	timer = window.setTimeout(function() {
189
		supprimerLocalisations();
190
		afficherMessageChargement('stations');
191
		chargerLocalisations();
192
    }, 400);
193
}
194
 
195
 
196
function supprimerLocalisations() {
197
	coucheSites.clearLayers();
198
}
199
 
200
 
201
function changerSource(projetClique) {
202
	// dechecker les autres controles d'overlays dans le panel
203
	for (var index = 0; index < overlays.length; index ++) {
204
		if (overlays[index].value != projetClique) {
205
			overlays[index].checked = false;
206
		}
207
	}
208
	// afficher les sites dans la carte pour le projet selectionne
209
	if (infoBulle != null) {
210
		masquerInfoBulle();
211
	}
212
	source = projetClique;
213
	programmerRafraichissementCarte();
214
}
215
 
216
 
217
function afficherMessageChargement(element) {
218
	var divTmplElement = 'tpl-chargement-' + element;
219
	$("#zone-chargement").append($("#" + divTmplElement).text());
220
	$("#zone-chargement").css('display', 'block');
221
}
222
 
223
function masquerMessageChargement() {
224
	$("#zone-chargement").css('display', 'none');
225
	$("#zone-chargement").children().remove();
226
}
227
 
228
 
229
// execution d'une requete AJAX
230
function executerAJAX() {
231
	if (requeteEnCours()) {
232
		masquerMessageChargement();
233
		requeteChargementPoints.abort();
234
	}
235
	requeteChargementPoints = $.getJSON(url).complete(function() {
236
		fonctionCallback(requeteChargementPoints.responseText);
237
	});
238
}
239
 
240
function requeteEnCours() {
241
	return (requeteChargementPoints != null && requeteChargementPoints.readyState != 4);
242
}
243
 
244
 
245
 
246
function chargerLocalisations() {
247
	// generer l'URL du script a interroger sur le serveur
248
	bordure = map.getBounds();
249
	var coordonneesBordure = calculerCoordonneesBordure();
250
	var parametres = {"num_taxon" : num_taxon, "referentiel" : referentiel, "dept" : dept,
251
			"utilisateur" : utilisateur, "bbox" : coordonneesBordure, "zoom" : map.getZoom()};
252
	url = urlBase + source + "/stations?" + convertirEnParametresUrl(parametres);
253
 
254
	fonctionCallback = function(JSONtext) {
255
		masquerMessageChargement();
256
		if (requeteChargementPoints.status != 200 && requeteChargementPoints.status != 304
257
			&& typeof(JSONtext) != 'undefined') {
258
			alert(JSONtext);
259
			return;
260
		}
261
 
262
		var data = eval("(function(){return " + JSONtext + ";})()");
263
		if (typeof(data) != 'undefined' && typeof(data.features) != 'undefined') {
264
			ajouterObjets(data);
265
		}
266
	}
267
	executerAJAX();
268
}
269
 
270
function calculerCoordonneesBordure() {
271
	var ouest = bordure.getSouthWest().lng,
272
		sud = Math.max(bordure.getSouthWest().lat, -85.051129),
273
		est = bordure.getNorthEast().lng,
274
		nord = Math.min(bordure.getNorthEast().lat, 85.051129);
275
 
276
	// appliquer les limites possibles de la projection actuellement utilisee aux coordonnees
277
	// longitudes ouest et est de la bbox (permettra d'eviter de renvoyer des messages d'erreur)
278
	if (ouest < -180) {
279
		ouest += 360;
280
	} else if (ouest > 180) {
281
		ouest -= 360;
282
	}
283
	if (est < -180) {
284
		est += 360;
285
	} else if (est > 180) {
286
		est -= 360;
287
	}
288
 
289
	return [ouest, sud, est, nord].join(',');
290
}
291
 
292
 
293
function ajouterObjets(data) {
294
	coucheSites.clearLayers();
295
	var contientMailles = false;
296
	// ajout des nouveaux points a la couche
297
	for (var i = 0; i < data.features.length; i ++) {
298
		var typeSite = data.features[i].properties.typeSite;
299
		var objet = null;
300
		switch (typeSite) {
301
			case 'MAILLE' : {
302
				contientMailles = true;
303
				ajouterMaille(data.features[i]);
304
				break;
305
			}
306
			case 'COMMUNE' :
307
			case 'STATION' : {
308
				ajouterPoint(data.features[i]);
309
				break;
310
			}
311
		}
312
	}
313
	// afficher/masquer la legende
314
	if (contientMailles) {
315
		afficherLegende();
316
	} else {
317
		masquerLegende();
318
	}
319
}
320
 
321
 
322
function ajouterMaille(feature) {
323
	var coordonnees = [];
324
	for (var i = 0; i < feature.geometry.coordinates.length; i++) {
325
		var sommet = new L.LatLng(feature.geometry.coordinates[i][0], feature.geometry.coordinates[i][1]);
326
		coordonnees.push(sommet);
327
	}
328
 
329
	var objet = new L.Polygon(coordonnees, {
330
		color: '#FFFFFF',
331
		opacity : 0.7,
332
		weight: 1,
333
		fillColor : getColor(feature.properties.nombrePoints),
334
		fillOpacity : 0.6
335
	});
336
	objet.typeSite = feature.properties.typeSite;
337
	objet.nombrePoints = feature.properties.nombrePoints;
338
	objet.on('click', clicSurMaille);
339
	coucheSites.addLayer(objet);
340
	// afficher le nombre de points inclus dans la maille
341
	afficherNombreStationsDansMaille(objet);
342
}
343
 
344
function afficherNombreStationsDansMaille(maille) {
345
	var recul = 0;
346
	if (maille.nombrePoints >= 10000) {
347
		recul = 14;
348
	} else if (maille.nombrePoints >= 1000) {
349
		recul = 9;
350
	} else if (maille.nombrePoints >= 100) {
351
		recul = 5;
352
	}
353
	var sudMaille    = maille._originalPoints[0].y,
354
		ouestMaille  = maille._originalPoints[0].x,
355
		nordMaille   = maille._originalPoints[2].y,
356
		estMaille    = maille._originalPoints[2].x,
357
		centreMaille = new L.Point((ouestMaille + estMaille) / 2 - recul, (sudMaille + nordMaille) / 2);
358
 
359
	var divIcon = new L.divIcon({
360
		className : "nombre-sites",
361
		html : maille.nombrePoints
362
	});
363
	var marqueurDiv = new L.Marker(map.layerPointToLatLng(centreMaille), {
364
		icon : divIcon,
365
		maille : maille.getBounds()
366
	});
367
	marqueurDiv.on('click', clicSurMaille);
368
	coucheSites.addLayer(marqueurDiv);
369
}
370
 
371
function clicSurMaille(event) {
372
	if (event.target._zIndex != null) {
373
		map.fitBounds(event.target.options.maille)
374
	} else {
375
		map.fitBounds(event.target.getBounds());
376
	}
377
}
378
 
379
function getColor(nbPoints) {
380
	if (nbPoints >= 2500) {
381
		return '#E74440';
382
	} else if (nbPoints >= 1000) {
383
		return '#E75E40';
384
	} else if (nbPoints >= 500) {
385
		return '#E77840';
386
	} else if (nbPoints >= 100) {
387
		return '#E79240';
388
	} else if (nbPoints >= 50) {
389
		return '#E7AC40';
390
	} else if (nbPoints >= 10) {
391
		return '#E7C640';
392
	} else {
393
		return '#E7E040';
394
	}
395
}
396
 
397
 
398
function ajouterPoint(feature) {
399
	var point = new L.LatLng(feature.geometry.coordinates[0], feature.geometry.coordinates[1]),
400
		icone = (feature.properties.typeSite == 'STATION') ? iconePoint : iconeCommune,
401
		marker = new L.Marker(point, {
402
		icon : icone,
403
		type : feature.properties.typeSite,
404
		title : feature.properties.nom
405
	}).addTo(map);
406
	// evenement onclick sur marqueur pour recuperer les observations sur ce point
407
	marker.on('click', clicSurMarqueur);
408
	coucheSites.addLayer(marker);
409
}
410
 
411
 
412
function afficherLegende() {
413
	if (legende != null) {
414
		return;
415
	}
416
	legende = new L.Control({position : 'bottomright'});
417
	legende.onAdd = function(map) {
418
		var div = L.DomUtil.create('div', 'info');
419
		div.innerHTML = '<h4>' + titreLegende + '</h4>';
420
		var seuils = [1, 10, 50 ,100, 500, 1000, 2500];
421
		var labels = [];
422
		for (var i = 0; i < seuils.length; i ++) {
423
			div.innerHTML += '<div class="legend"><i style="background:' + getColor(seuils[i] + 1) + '"></i>' + seuils[i]
424
				+ (i + 1 < seuils.length ? '&ndash;' + seuils[i + 1] : '+') + '</div>';
425
		}
426
		return div;
427
	};
428
	map.addControl(legende);
429
}
430
 
431
function masquerLegende() {
432
	if (legende != null) {
433
		map.removeControl(legende);
434
		legende = null;
435
	}
436
}
437
 
438
 
439
 
440
function clicSurMarqueur(event) {
441
	// centrer la carte sur le marqueur
442
	var latitude = event.target.getLatLng().lat;
443
	var longitude = event.target.getLatLng().lng;
444
	pointClique = event.target;
445
	afficherMessageChargement('observations');
446
	// charger les observations se trouvant sur ce point
447
	var parametres = {"num_taxon" : num_taxon, "referentiel" : referentiel, "dept" : dept,
448
		"utilisateur" : utilisateur, "longitude" : longitude, "latitude" : latitude};
449
	url = urlBase + source + "/observations?" + convertirEnParametresUrl(parametres);
450
	fonctionCallback = function(JSONtext) {
451
		masquerMessageChargement();
452
		if (requeteChargementPoints.status != 200 && requeteChargementPoints.status != 304
453
				&& typeof(JSONtext) != 'undefined') {
454
			alert(JSONtext);
455
			return;
456
		}
457
 
458
		obsJSON = eval("(function(){return " + JSONtext + ";})()");
459
		// vider la liste des observations de l'infobulle precedente
460
		while (obsStation.length > 0) {
461
			obsStation.pop();
462
		}
463
		if (obsJSON.total > 0) {
464
			// centrer la vue de la carte sur la station
465
			map.setView(new L.LatLng(latitude, longitude), map.getZoom());
466
			// afficher les observations dans une infobulle
467
			afficherInfoBulle();
468
		} else if (infoBulle != null)  {
469
			// supprimer l'infobulle
470
			masquerInfoBulle();
471
		}
472
	}
473
	executerAJAX();
474
}
475
 
476
 
477
///////////////////////////////////////
478
//             INFOBULLE             //
479
///////////////////////////////////////
480
 
481
 
482
var infoBulle = null,
483
	obsJSON = null,
484
	pointClique = null,
485
	obsStation = [],
486
	typeAffichage = "";
487
 
488
function afficherInfoBulle() {
489
	// creer l'infobulle sur le marqueur qui a declenche l'evenement clicSurMarqueur
490
	var latitude = pointClique.getLatLng().lat;
491
	var longitude = pointClique.getLatLng().lng;
492
	infoBulle = new L.Popup({maxWidth : 600, maxHeight : 350});
493
	infoBulle.setLatLng(new L.LatLng(latitude, longitude));
494
	// afficher la popup sur la carte
495
	infoBulle.setContent($("#tpl-obs").html());
496
	infoBulle.openOn(map);
497
 
498
	// remplir le contenu de la popup
499
	ajouterTableauTriable("#obs-tableau");
500
	ajouterTitre();
501
	afficherOnglets();
502
	afficherTexteStationId();
503
}
504
 
505
function masquerInfoBulle() {
506
	if (map.hasLayer(infoBulle) && infoBulle != null) {
507
		map.removeLayer(infoBulle);
508
	}
509
	infoBulle = null;
510
}
511
 
512
function ajouterTitre() {
513
	var texteStationTitre = obsJSON.total + ' observation' + (obsJSON.total > 1 ? 's' : '')
514
		+ ' pour ' + (pointClique.options.type=='STATION' ? 'la station : ' : 'la commune : ')
515
		+ pointClique.options.title;
516
	$('#obs-station-titre').text(texteStationTitre);
517
}
518
 
519
function selectionnerOnglet() {
520
	$("#obs-vue-" + typeAffichage).css("display", "block");
521
	$('#obs-tableau-lignes').empty();
522
	$('#obs-liste-lignes').empty();
523
	if (typeAffichage=='liste') {
524
		$("#obs-vue-tableau").css("display", "none");
525
	} else {
526
		$("#obs-vue-liste").css("display", "none");
527
	}
528
}
529
 
530
function ajouterObservationsDansHTML() {
531
	if (obsStation.length==0) {
532
		// premiere execution de la fonction : faire une copie des objets JSON decrivant les observations
533
		for (var index = 0; index < obsJSON.observations.length; index ++) {
534
			obsStation.push(obsJSON.observations[index]);
535
		}
536
	}
537
	// ajouter les observations dans le code HTML
538
	var obsPage = [];
539
	for (var index = 0; index < obsStation.length; index ++) {
540
		obsPage.push(obsStation[index]);
541
	}
542
	$("#tpl-obs-"+typeAffichage).tmpl(obsPage).appendTo("#obs-"+typeAffichage+"-lignes");
543
}
544
 
545
function afficherOnglets() {
546
	var $tabs = $('#obs').tabs();
547
	$('#obs').bind('tabsselect', function(event, ui) {
548
		if (ui.panel.id == 'obs-vue-tableau') {
549
			surClicAffichageTableau();
550
		} else if (ui.panel.id == 'obs-vue-liste') {
551
			surClicAffichageListe();
552
		}
553
	});
554
	if (obsJSON.total > 4) {
555
		surClicAffichageTableau();
556
	} else {
557
		$tabs.tabs('select', "#obs-vue-liste");
558
	}
559
}
560
 
561
function surClicAffichageTableau() {
562
	typeAffichage = 'tableau';
563
	selectionnerOnglet();
564
	ajouterObservationsDansHTML();
565
	mettreAJourTableauTriable("#obs-tableau");
566
}
567
 
568
function surClicAffichageListe() {
569
	typeAffichage = 'liste';
570
	selectionnerOnglet();
571
	ajouterObservationsDansHTML();
572
}
573
 
574
function ajouterTableauTriable(element) {
575
	// add parser through the tablesorter addParser method
576
	$.tablesorter.addParser({
577
		// Définition d'un id unique pour ce parsseur
578
		id: 'date_cel',
579
		is: function(s) {
580
			// doit retourner false si le parsseur n'est pas autodétecté
581
			return /^\s*\d{2}[\/-]\d{2}[\/-]\d{4}\s*$/.test(s);
582
		},
583
		format: function(date) {
584
			// Transformation date jj/mm/aaaa en aaaa/mm/jj
585
			date = date.replace(/^\s*(\d{2})[\/-](\d{2})[\/-](\d{4})\s*$/, "$3/$2/$1");
586
			// Remplace la date par un nombre de millisecondes pour trier numériquement
587
			return $.tablesorter.formatFloat(new Date(date).getTime());
588
		},
589
		// set type, either numeric or text
590
		type: 'numeric'
591
	});
592
	$(element).tablesorter({
593
        headers: {
594
			1: {
595
            	sorter:'date_cel'
596
        	}
597
    	}
598
	});
599
}
600
 
601
function mettreAJourTableauTriable(element) {
602
	$(element).trigger('update');
603
}
604
 
605
function afficherTexteStationId() {
606
	var latitude = pointClique.getLatLng().lat;
607
	var longitude = pointClique.getLatLng().lng;
608
	var texteStationId = pointClique.options.type + ':' + latitude + '|' + longitude;
609
	$('#obs-station-id').text(texteStationId);
610
}