Subversion Repositories eFlore/Applications.moissonnage

Rev

Rev 7 | Rev 31 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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