[SPIP] ~v3.0.21-->v3.0.22
[lhc/web/www.git] / www / plugins / gis / javascript / gis_init_map.js
1 var gis_init_map = function(mapcfg) {
2 var map_container = mapcfg["mapid"];
3
4 // Création de la carte Leafleat
5 var map = new L.Map(map_container,{
6 scrollWheelZoom: mapcfg["scrollWheelZoom"],
7 zoomControl: mapcfg["zoomControl"],
8 maxZoom: mapcfg["maxZoom"]
9 });
10 // affecter sur la globale homonyme a mapid/map_container (compat ascendante)
11 eval(map_container+"=map;");
12 // affecter sur l'objet du DOM
13 jQuery("#"+map_container).get(0).map=map;
14
15 // Appeler l'éventuelle fonction de callback et trigger "load"
16 map.on('load',function(e){
17 if (mapcfg["callback"] && typeof(mapcfg["callback"]) === "function") {
18 var callback = mapcfg["callback"];
19 callback(e.target);
20 }
21 jQuery("#"+map_container).trigger('load',e.target);
22 });
23
24 // Déterminer la position initiale de la carte
25 if (!mapcfg['utiliser_bb']){
26 map.setView(new L.LatLng(mapcfg['lat'], mapcfg['lon']), mapcfg['zoom']);
27 }
28 else {
29 map.fitBounds(
30 new L.LatLngBounds(
31 new L.LatLng(mapcfg['sw_lat'], mapcfg['sw_lon']),
32 new L.LatLng(mapcfg['ne_lat'], mapcfg['ne_lon'])
33 )
34 );
35 }
36
37 var get_layer=function(name){
38 var layer;
39 if (typeof mapcfg['layers'][name]!=="undefined")
40 eval("layer=new "+ mapcfg['layers'][name]["layer"]+";");
41 return layer;
42 }
43
44 // Fond de carte par défaut (layer)
45 var default_layer = get_layer(mapcfg['default_layer']);
46 map.addLayer(default_layer);
47
48 if (mapcfg['control_type'] && !mapcfg['no_control'] && mapcfg['affiche_layers'].length>1){
49 var layers_control = new L.Control.Layers();
50 layers_control.addBaseLayer(default_layer,mapcfg['layers'][mapcfg['default_layer']]["nom"]);
51 for(var l in mapcfg['affiche_layers']){
52 if (mapcfg['affiche_layers'][l]!==mapcfg['default_layer']){
53 var layer = get_layer(mapcfg['affiche_layers'][l]);
54 if (typeof layer!=="undefined")
55 layers_control.addBaseLayer(layer,mapcfg['layers'][mapcfg['affiche_layers'][l]]["nom"]);
56 }
57 }
58 map.addControl(layers_control);
59 // ajouter l'objet du controle de layers à la carte pour permettre d'y accéder depuis le callback
60 map.layersControl = layers_control;
61 // classe noajax sur le layer_control pour éviter l'ajout de hidden par SPIP
62 jQuery(layers_control._form).addClass('noajax');
63 }
64
65
66 map.attributionControl.setPrefix('');
67
68 // Ajout des contrôles de la carte
69 if (!mapcfg['no_control']){
70 if (mapcfg['scale'])
71 map.addControl(new L.Control.Scale());
72 if (mapcfg['fullscreen'])
73 map.addControl(new L.Control.FullScreen());
74 if (mapcfg['overview']){
75 var minimap_layer = get_layer(mapcfg['default_layer']);
76 var miniMap = new L.Control.MiniMap(minimap_layer,{width: 100,height: 100, toggleDisplay: true}).addTo(map);
77 }
78 }
79
80 // API setGeoJsonFeatureIcon : Pour Ajouter l'icone d'un point (feature = item d'un GeoJson)
81 map.setGeoJsonFeatureIcon = function (feature, layer) {
82 // Déclarer l'icone du points, si défini
83 if (feature.properties && feature.properties.icon){
84 icon_options = {
85 'iconUrl': feature.properties.icon,
86 'iconSize': new L.Point( feature.properties.icon_size[0], feature.properties.icon_size[1] ),
87 'iconAnchor': new L.Point( feature.properties.icon_anchor[0], feature.properties.icon_anchor[1] ),
88 'popupAnchor': new L.Point( feature.properties.popup_anchor[0], feature.properties.popup_anchor[1] )
89 };
90 if (feature.properties.shadow)
91 icon_options.shadowUrl = feature.properties.shadow;
92 if (feature.properties.shadow_size)
93 icon_options.shadowSize = new L.Point( feature.properties.shadow_size[0], feature.properties.shadow_size[1] );
94 layer.setIcon(new L.Icon(icon_options));
95 }
96 }
97
98 // API setGeoJsonFeaturePopup : Pour Ajouter le texte de popup d'un point (feature = item d'un GeoJson)
99 map.setGeoJsonFeaturePopup = function (feature, layer) {
100 // Déclarer le contenu de la popup s'il y en a
101 if (feature.properties && (feature.properties.title || feature.properties.description)){
102 var popupContent = '';
103 var popupOptions = '';
104 if (feature.properties.title)
105 popupContent = '<strong class="title">' + feature.properties.title + '</strong>';
106 if (feature.properties.description)
107 popupContent = popupContent + feature.properties.description;
108 if (feature.properties.popup_options)
109 popupOptions = feature.properties.popup_options;
110 layer.bindPopup(popupContent,popupOptions);
111 }
112 }
113
114 /*
115 Il y a pour le moment 2 façons d'analyser le GeoJson calculé
116 en fonction de si on veut faire du clustering (regrouper les points proches)
117 ou non. Il y a certainement moyen de regrouper en un seul élément
118 la plupart du code, en se passant du js L.geoJson même hors clustering.
119 À réfléchir.
120 */
121 // API parseGeoJson
122 if (!mapcfg['cluster']){
123 // Analyse des points et déclaration (sans regroupement des points en cluster)
124 map.parseGeoJson = function(data) {
125 if (data.features.length > 0) {
126 var geojson = new L.geoJson('', {
127 style: mapcfg['path_styles'],
128 onEachFeature: function (feature, layer) {
129 // Déclarer l'icone du point
130 map.setGeoJsonFeatureIcon(feature, layer);
131 // Déclarer le contenu de la popup s'il y en a
132 map.setGeoJsonFeaturePopup(feature, layer);
133 }
134 }).addTo(map);
135 geojson.addData(data);
136 if (mapcfg['autocenterandzoom'])
137 map.fitBounds(geojson.getBounds());
138 if (mapcfg['open_id'].length)
139 gis_focus_marker(mapcfg['open_id'],map_container.substring(3));
140
141 if (typeof map.geojsons=="undefined") map.geojsons = [];
142 map.geojsons.push(geojson);
143 }
144 }
145 }
146 else {
147 // Analyse des points et déclaration (en regroupant les points en cluster)
148 map.parseGeoJson = function(data) {
149 var options = {
150 showCoverageOnHover:false
151 };
152 if (mapcfg["clusterMaxZoom"])
153 options.disableClusteringAtZoom = parseInt(mapcfg["clusterMaxZoom"]);
154 if (mapcfg["clusterShowCoverageOnHover"])
155 options.showCoverageOnHover = Boolean(mapcfg["clusterShowCoverageOnHover"]);
156
157 map.markers = new L.MarkerClusterGroup(options);
158
159 /* Pour chaque points présents, on crée un marqueur */
160 $.each(data.features, function(i, feature) {
161 if (feature.geometry.coordinates[0]) {
162 var latlng = new L.LatLng(feature.geometry.coordinates[1], feature.geometry.coordinates[0]);
163 var marker = new L.Marker(latlng);
164
165 // Déclarer l'icone du point
166 map.setGeoJsonFeatureIcon(feature, marker);
167 // Déclarer le contenu de la popup s'il y en a
168 map.setGeoJsonFeaturePopup(feature, marker);
169
170 marker.id = feature.id;
171 map.markers.addLayer(marker);
172 }
173 });
174
175 map.addLayer(map.markers);
176
177 if (mapcfg['autocenterandzoom'])
178 map.fitBounds(map.markers.getBounds());
179 }
180 }
181
182 // API Compat Gis3 : addJSON et removeAllMarkers
183 map.addJSON = map.parseGeoJson
184 map.removeAllMarkers = function(){
185 if (typeof map.geojsons=="undefined") map.geojsons = [];
186 for(i in map.geojsons){
187 map.geojsons[i].clearLayers();
188 map.removeLayer(map.geojsons[i]);
189 }
190 map.geojsons = [];
191 }
192
193 if (mapcfg['affiche_points']
194 && typeof(mapcfg['json_points'])!=="undefined"
195 && mapcfg['json_points']['url'].length){
196 // Récupération des points à mettre sur la carte, via json externe
197 var args = {};
198 jQuery.extend(true, args, mapcfg['json_points']['env']);
199 if (typeof mapcfg['json_points']['objets']!=="undefined"){
200 args["objets"] = mapcfg['json_points']['objets'];
201 if (args["objets"]=="point_libre"){
202 args["lat"]=mapcfg['lat'];
203 args["lon"]=mapcfg['lon'];
204 if (typeof mapcfg['json_points']['titre']!=="undefined")
205 args["titre"]= mapcfg['json_points']['titre'];
206 if (typeof mapcfg['json_points']['description']!=="undefined")
207 args["description"]=mapcfg['json_points']['description'];
208 if (typeof mapcfg['json_points']['icone']!=="undefined")
209 args["icone"]=mapcfg['json_points']['icone'];
210 }
211 }
212 if (typeof mapcfg['json_points']['limit']!=="undefined")
213 args["limit"] = mapcfg['json_points']['limit'];
214 jQuery.getJSON(mapcfg['json_points']['url'],args,
215 function(data) {
216 if (data){
217 // Charger le json (data) et déclarer les points
218 map.parseGeoJson(data);
219 jQuery("#"+map_container).trigger('ready',map);
220 }
221 }
222 );
223 }
224
225 if (mapcfg['kml'] && mapcfg['kml'].length){
226 map.kml = {};
227 for(var i in mapcfg['kml']){
228 map.kml[i] = new L.KML(mapcfg['kml'][i], {async: true});
229 if (mapcfg['centrer_fichier']) {
230 map.kml[i].on("loaded", function(e) { map.fitBounds(e.target.getBounds()); });
231 }
232 map.addLayer(map.kml[i]);
233 }
234 }
235 if (mapcfg['gpx'] && mapcfg['gpx'].length){
236 map.gpx = {};
237 for(var i in mapcfg['gpx']){
238 map.gpx[i] = new L.GPX(mapcfg['gpx'][i], {async: true});
239 if (mapcfg['centrer_fichier']) {
240 map.gpx[i].on("loaded", function(e) { map.fitBounds(e.target.getBounds()); });
241 }
242 map.addLayer(map.gpx[i]);
243 }
244 }
245
246 if (mapcfg['localize_visitor'])
247 map.locate({setView: true, maxZoom: mapcfg['zoom']});
248
249 // si pas de points trigger ici
250 if (!mapcfg['affiche_points'] || !mapcfg['json_points'].length)
251 jQuery("#"+map_container).trigger('ready',map);
252 }