Subversion Repositories eFlore/Applications.cel

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3120 delphine 1
/**
2
 * Constructeur WidgetSaisie par défaut
3
 */
4
function WidgetSaisie() {
5
	this.map = null;
6
	this.marker = null;
7
	this.latLng = null; // position en cours
8
	this.geocoder = null;
9
	this.serviceNomCommuneUrl = null;
10
	this.serviceNomCommuneUrlAlt = null;
11
	this.googleMapMarqueurUrl = null;
12
	this.chargementIconeUrl = null;
13
	this.chargementImageIconeUrl = null;
14
}
15
 
16
/**
17
 * Initialisation du widget
18
 */
19
WidgetSaisie.prototype.init = function() {
20
	this.initCarto();
21
	this.initEvts();
22
};
23
 
24
/**
25
 * Initialise la cartographie
26
 */
27
WidgetSaisie.prototype.initCarto = function() {
28
	this.initialiserGoogleMap();
29
	this.initialiserAutocompleteCommune();
30
};
31
 
32
/**
33
 * Initialise les écouteurs d'événements
34
 */
35
WidgetSaisie.prototype.initEvts = function() {
36
	// Autocompletion du champ adresse
37
	$("#carte-recherche").on('focus', function() {
38
		$(this).select();
39
	});
40
	$("#carte-recherche").on('mouseup', function(event) {// Pour Safari...
41
		event.preventDefault();
42
	});
43
	$("#carte-recherche").keypress(function(e) {
44
		if (e.which == 13) {
45
			e.preventDefault();
46
		}
47
	});
48
};
49
 
50
/**
51
 * Initialise l'autocomplétion de la commune, en fonction du référentiel
52
 */
53
WidgetSaisie.prototype.initialiserAutocompleteCommune = function() {
54
	var geocoderOptions = {
55
	},
56
	addressSuffix = '',
57
	lthis = this;
58
 
59
	switch(this.nomSciReferentiel) {
60
		case 'isfan':
61
			// Si des résultats se trouvent dans ce rectangle, ils apparaîtront en premier.
62
			// Ça marche moyen...
63
			geocoderOptions.bounds = new google.maps.LatLngBounds(
64
				new google.maps.LatLng(20.756114, -22.023927),
65
				new google.maps.LatLng(38.065392, 33.78662)
66
			);
67
			break;
68
		case 'apd':
69
			geocoderOptions.bounds = new google.maps.LatLngBounds(
70
					new google.maps.LatLng(-6.708254, -26.154786),
71
					new google.maps.LatLng(27.488781, 30.490722)
72
				);
73
			break;
74
		case 'bdtfx':
75
		case 'bdtxa':
76
			geocoderOptions.region = 'fr';
77
			addressSuffix = ', France';
78
	}
79
 
80
	$("#carte-recherche").autocomplete({
81
		//Cette partie utilise geocoder pour extraire des valeurs d'adresse
82
		source: function(request, response) {
83
			geocoderOptions.address = request.term + addressSuffix;
84
			lthis.geocoder.geocode( geocoderOptions, function(results, status) {
85
				if (status == google.maps.GeocoderStatus.OK) {
86
					response($.map(results, function(item) {
87
						var retour = {
88
							label: item.formatted_address,
89
							value: item.formatted_address,
90
							latitude: item.geometry.location.lat(),
91
							longitude: item.geometry.location.lng()
92
						};
93
						return retour;
94
					}));
95
				} else {
96
					lthis.afficherErreurGoogleMap(status);
97
				}
98
			});
99
		},
100
		// Cette partie est executee a la selection d'une adresse
101
		select: function(event, ui) {
102
			lthis.latLng = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
103
			lthis.deplacerMarker(lthis.latLng);
104
		}
105
	});
106
};
107
 
108
WidgetSaisie.prototype.afficherErreurGoogleMap = function(status) {
109
	if (this.debug) {
110
		$('#dialogue-google-map .contenu').empty().append(
111
			'<pre class="msg-erreur">'+
112
			"Le service de Géocodage de Google Map a échoué à cause de l'erreur : "+status+
113
			'</pre>');
114
		this.afficherPanneau('#dialogue-google-map');
115
	}
116
};
117
 
118
WidgetSaisie.prototype.surDeplacementMarker = function() {
119
	this.latLng = this.marker.getPosition();
120
	this.trouverCommune(this.latLng);
121
	this.mettreAJourMarkerPosition(this.marker.getPosition());
122
};
123
 
124
WidgetSaisie.prototype.surClickDansCarte = function(event) {
125
	this.latLng = event.latLng;
126
	this.deplacerMarker(this.latLng);
127
};
128
 
129
/**
130
 * Place le marqueur aux coordonnées indiquées dans les champs "latitude" et "longitude"
131
 */
132
WidgetSaisie.prototype.geolocaliser = function() {
133
	var latitude = $('#latitude').val();
134
	var longitude = $('#longitude').val();
135
	this.latLng = new google.maps.LatLng(latitude, longitude);
136
	this.deplacerMarker(this.latLng);
137
};
138
 
139
WidgetSaisie.prototype.initialiserGoogleMap = function(localisationNavigateur) {
140
	// par défaut on tente de localiser le navigateur (avec son sextant)
141
	if (localisationNavigateur === undefined) {
142
		localisationNavigateur = true;
143
	}
144
 
145
	var lthis = this;
146
	var latLng,
147
		zoomDefaut;
148
	// Carte @TODO mettre ça dans la config
149
	if(this.nomSciReferentiel == 'bdtre') {
150
		latLng = new google.maps.LatLng(-21.10, 55.30);// Réunion
151
		zoomDefaut = 7;
152
	} else if(this.nomSciReferentiel == 'lbf') {
153
		latLng = new google.maps.LatLng(33.72211, 35.8603);// Liban
154
		zoomDefaut = 7;
155
	} else if(this.nomSciReferentiel == 'bdtxa') {
156
		latLng = new google.maps.LatLng(14.6, -61.08334);// Fort-De-France
157
		zoomDefaut = 8;
158
	} else if(this.nomSciReferentiel == 'isfan') {
159
		latLng = new google.maps.LatLng(29.28358, 10.21884);// Afrique du Nord
160
		zoomDefaut = 4;
161
	} else if(this.nomSciReferentiel == 'apd') {
162
		latLng = new google.maps.LatLng(8.75624, 1.80176);// Afrique de l'Ouest et du Centre
163
		zoomDefaut = 4;
164
	} else if(this.nomSciReferentiel == 'florical') {
165
		latLng = new google.maps.LatLng(-21.40722, 165.4541);// Nouvelle-Calédonie
166
		zoomDefaut = 7;
167
	} else if(this.nomSciReferentiel == 'aublet') {
168
		latLng = new google.maps.LatLng(3.80287, -53.09692);// Guyane
169
		zoomDefaut = 7;
170
	} else {
171
		latLng = new google.maps.LatLng(46.30871, 2.54395);// Centre de la France - @WARNING Prémilhat !! :)
172
		zoomDefaut = 5;
173
	}
174
 
175
	var options = {
176
		zoom: zoomDefaut,
177
		center: latLng,
178
		mapTypeId: google.maps.MapTypeId.HYBRID,
179
		mapTypeControlOptions: {
180
			mapTypeIds: ['OSM', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN]}
181
	};
182
 
183
	// Ajout de la couche OSM à la carte
184
	osmMapType = new google.maps.ImageMapType({
185
		getTileUrl: function(coord, zoom) {
186
			return "http://tile.openstreetmap.org/" +
187
			zoom + "/" + coord.x + "/" + coord.y + ".png";
188
		},
189
		tileSize: new google.maps.Size(256, 256),
190
		isPng: true,
191
		alt: 'OpenStreetMap',
192
		name: 'OSM',
193
		maxZoom: 19
194
	});
195
 
196
	// Création de la carte Google
197
	this.map = new google.maps.Map(document.getElementById('map-canvas'), options); //affiche la google map dans la div map_canvas
198
	this.map.mapTypes.set('OSM', osmMapType);
199
 
200
	// Création du Geocoder
201
	this.geocoder = new google.maps.Geocoder();
202
 
203
	// Marqueur google draggable
204
	this.marker = new google.maps.Marker({
205
		map: this.map,
206
		draggable: true,
207
		title: 'Ma station',
208
		icon: this.googleMapMarqueurUrl,
209
		position: latLng
210
	});
211
 
212
	this.initialiserMarker(latLng);
213
 
214
	// Tentative de geocalisation depuis le navigateur
215
	if (localisationNavigateur && navigator.geolocation) {
216
		navigator.geolocation.getCurrentPosition(function(position) {
217
			var latitude = position.coords.latitude;
218
			var longitude = position.coords.longitude;
219
			lthis.latLng = new google.maps.LatLng(latitude, longitude);
220
			lthis.deplacerMarker(lthis.latLng);
221
		});
222
	}
223
 
224
	// intéraction carte
225
	$("#geolocaliser").on('click', this.geolocaliser.bind(this));
226
	google.maps.event.addListener(this.marker, 'dragend', this.surDeplacementMarker.bind(this));
227
	google.maps.event.addListener(this.map, 'click', this.surClickDansCarte.bind(this));
228
};
229
 
230
WidgetSaisie.prototype.initialiserMarker = function(latLng) {
231
	if (this.marker != undefined) {
232
		this.marker.setPosition(latLng);
233
		this.map.setCenter(latLng);
234
		// au chargement de la carte, la position est nulle
235
		this.viderMarkerPosition();
236
	}
237
};
238
 
239
WidgetSaisie.prototype.deplacerMarker = function(latLng) {
240
	if (this.marker != undefined) {
241
		this.marker.setPosition(latLng);
242
		this.map.setCenter(latLng);
243
		this.mettreAJourMarkerPosition(latLng);
244
		this.trouverCommune(latLng);
245
	}
246
};
247
 
248
WidgetSaisie.prototype.viderMarkerPosition = function() {
249
	this.remplirChampLatitude(null);
250
	this.remplirChampLongitude(null);
251
};
252
 
253
WidgetSaisie.prototype.mettreAJourMarkerPosition = function(latLng) {
254
	var lat = latLng.lat().toFixed(5);
255
	var lng = latLng.lng().toFixed(5);
256
	this.remplirChampLatitude(lat);
257
	this.remplirChampLongitude(lng);
258
};
259
 
260
/**
261
 * Définit la valeur de latitude, à travers la "value" du champ "#latitude";
262
 * pour définir une valeur vraiment vide (et non 0), passer null en argument
263
 */
264
WidgetSaisie.prototype.remplirChampLatitude = function(latDecimale) {
265
	var lat = '';
266
	if (latDecimale !== null) {
267
		lat = Math.round(latDecimale * 100000) / 100000;
268
	}
269
	$('#latitude').val(lat);
270
};
271
 
272
/**
273
 * Définit la valeur de longitude, à travers la "value" du champ "#longitude";
274
 * pour définir une valeur vraiment vide (et non 0), passer null en argument
275
 */
276
WidgetSaisie.prototype.remplirChampLongitude = function(lngDecimale) {
277
	var lng = '';
278
	if (lngDecimale !== null) {
279
		lng = Math.round(lngDecimale * 100000) / 100000;
280
	}
281
	$('#longitude').val(lng);
282
};
283
 
284
WidgetSaisie.prototype.trouverCommune = function(pos) {
285
	if (this.latLng == null) { // tentative de protection contre le démon de Prémilhat
286
		return;
287
	}
288
	var lthis = this;
289
	$(function() {
290
 
291
		var url_service = lthis.serviceNomCommuneUrl;
292
 
293
		var urlNomCommuneFormatee = url_service.replace('{lat}', pos.lat()).replace('{lon}', pos.lng());
294
		$.ajax({
295
			url : urlNomCommuneFormatee,
296
			type : "GET",
297
			dataType : "jsonp",
298
			beforeSend : function() {
299
				$(".commune-info").empty();
300
				$("#dialogue-erreur .alert-txt").empty();
301
			},
302
			success : function(data, textStatus, jqXHR) {
303
				$(".commune-info").empty();
304
				$("#commune-nom").append(data.nom);
305
				$("#commune-code-insee").append(data.codeINSEE);
306
				$("#marqueur-commune").data('commune', {'nom' : data.nom, 'codeInsee' : data.codeINSEE});
307
			},
308
			statusCode : {
309
			    500 : function(jqXHR, textStatus, errorThrown) {
310
					if (this.debug) {
311
						$("#dialogue-erreur .alert-txt").append('<p id="msg">Un problème est survenu lors de l\'appel au service fournissante le nom des communes.</p>');
312
						reponse = jQuery.parseJSON(jqXHR.responseText);
313
						var erreurMsg = "";
314
						if (reponse != null) {
315
							$.each(reponse, function (cle, valeur) {
316
								erreurMsg += valeur + "<br />";
317
							});
318
						}
319
 
320
						$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur 500 : '+errorThrown+"<br />"+erreurMsg+'</p>');
321
					}
322
			    }
323
			},
324
			error : function(jqXHR, textStatus, errorThrown) {
325
				if (this.debug) {
326
					$("#dialogue-erreur .alert-txt").append('<p class="msg">Une erreur Ajax est survenue lors de la recherche de la commune.</p>');
327
					reponse = jQuery.parseJSON(jqXHR.responseText);
328
					var erreurMsg = "";
329
					if (reponse != null) {
330
						$.each(reponse, function (cle, valeur) {
331
							erreurMsg += valeur + "<br />";
332
						});
333
					}
334
 
335
					$("#dialogue-erreur .alert-txt").append('<p class="msg-erreur">Erreur Ajax : '+errorThrown+' (type : '+textStatus+') <br />'+erreurMsg+'</p>');
336
				}
337
			},
338
			complete : function(jqXHR, textStatus) {
339
				var debugMsg = extraireEnteteDebug(jqXHR);
340
				if (debugMsg != '') {
341
					if (this.debug) {
342
						$("#dialogue-erreur .alert-txt").append('<pre class="msg-debug msg">Débogage : '+debugMsg+'</pre>');
343
					}
344
				}
345
				if ($("#dialogue-erreur .msg").length > 0) {
346
					$("#dialogue-erreur").show();
347
				}
348
			}
349
		});
350
	});
351
};