Source: widgets/SpwStartupQueryByUrlValue.js

Retour à la documentation
/**
 * @class spw.widgets.SpwStartupQueryByUrlValue
 */
define([
    "dojo/_base/declare", "spw/api/SpwBaseWidget",
    "dojo/on", "dojo/_base/lang","spw/api/Utils","esri/InfoTemplate",
    "esri/tasks/query", "esri/tasks/QueryTask", "esri/request", "dojo/_base/array",
    "dojo/dom-construct", "dojo/aspect", "dojo/dom-class"
], function(declare, SpwBaseWidget, on, lang, Utils, InfoTemplate,
            Query, QueryTask, request, array,
            domConstruct, aspect, domClass) {

    return declare("spw.widgets.SpwStartupQueryByUrlValue", [SpwBaseWidget], /** @lends spw.widgets.SpwStartupQueryByUrlValue.prototype */{

        /**
         * @private
         * @type String
         */
        urlFieldSeparator:null,
        /**
         * Faut-il ouvrir le résultat de la requête lorsque celle-ci est effectuée?
         * @private
         * @type Boolean
         */
        autoOpenTemplate: true,
        /**
         * @private
         * @type String
         */
        featureLayerDefinition:"*",
        /**
         * La configuration est-elle valide?
         * @private
         * @type Boolean
         */
        configurationValide: true,
        /**
         * Faut-il enlever la géométrie lors de la fermeture de l'infobulle lui étant attachée?
         * @private
         * @type Boolean
         */
        removeOnClose: true,

        "queryServiceUrl": "http://geoservices.wallonie.be/arcgis/rest/services/PLAN_REGLEMENT/CADMAP_PARCELLES/MapServer/0",
        "defaultLayerId": null,
        "serviceField": "CAPAKEY",
        "urlField": "CAPAKEY",
        "infoTemplate": {
            "title": "Cadastre",
            "content": "<table><tr><td>Nom commune: </td><td>${NOM_COMMUNE}</td></tr><tr><td>Code INS: </td><td>${COMMUNE}</td></tr><tr><td>Capakey: </td><td>${CAPAKEY}</td></tr><tr><td>Nom division: </td><td>${DIV_NOM}</td></tr><tr><td>Code division: </td><td>${CODE_DIV}</td></tr><tr><td>Section: </td><td>${SECT}</td></tr><tr><td>Radical: </td><td>${RADICAL}</td></tr><tr><td>Bis: </td><td>${BIS}</td></tr><tr><td>Exposant: </td><td>${EXPOSANT}</td></tr><tr><td>Puissance: </td><td>${PUISSANCE}</td></tr><tr><td>Version: </td><td>${VER}</td></tr></table>"
        },
        "infoWindowSize": {
            "width": 400,
            "height": 200
        },

        postCreate: function() {

            if(this.queryServiceUrl == null || this.serviceField == null) {
                console.error("L'outil de query au démarrage ne fonctionne pas car il manque des paramètres obligatoires.");
                this.configurationValide = false;
            }

            if(this.configurationValide){
                var paramValue = null;
                var re = new RegExp("#("+this.urlField+")(\|\|[^=]+)?=");
                var matches = re.exec(window.location.hash);
                if(!matches) return;
                var q = matches[1]+(matches[2] ? matches[2] : "");
                paramValue = Utils.gua(q);
                if(paramValue == null || paramValue=="")
                    paramValue = Utils.gup(this.urlField);

                if(paramValue != null && paramValue != ""){
                    var query = new Query();

                    query.returnGeometry = true;
                    query.outFields = ["*"];
                    query.outSpatialReference = this.spwViewer.get('spatialReference');

                    var url = this.queryServiceUrl;

                    if (this.defaultLayerId != null || matches[2]) {
                        var layerId = this.defaultLayerId;

                        if (matches[2]) {
                            paramValue = paramValue;
                            layerId = matches[2].substring(2);
                        }

                        url = url + '/' + layerId;
                    }

                    request({
                        url: url,
                        content: { f:'pjson' },
                        handleAs: "json",
                        timeout: 10000
                    }).then(lang.hitch(this, function(response){
                        var i = 0, tab = new Array(), txt = "";
                        if (this.urlFieldSeparator==null){
                            if(this.getFieldItemType(this.serviceField, response) == 'esriFieldTypeString'){
                                txt = this.serviceField+"='"+paramValue+"'";
                            } else {
                                txt = this.serviceField+"="+paramValue;
                            }
                        }
//                          else
//                          {
//                              while(typeof urlFieldParams!="undefined" && i<paramValue.length){
//                                  var j = paramValue.indexOf(this.urlFieldSeparator,i);
//                                  if (j ==-1){
//                                      j = paramValue.length;
//                                  }
//
//                                  var urlFieldParam = paramValue.substring(i,j);
//                                  tab.push(urlFieldParam);
//                                  i=j;
//                                  i++;
//                              }
//                              if (tab.length!=0){
//                                  i=0;
//                                  while(i<tab.length){
//                                      txt+="("+this.serviceField+"='"+tab[i]+"')";
//                                      i++;
//                                      if (i<tab.length){
//                                          txt+=" OR ";
//                                      }
//                                  }
//                              }
//                          }
                        query.where = txt;
                        var queryTask = new QueryTask(url);
                        queryTask.execute(query, lang.hitch(this,function(features) {
                            var spwMap = this.spwViewer.get('spwMap');
                            if (spwMap.get('loaded')) {
                                this.displayResultAndZoom(features);
                            } else {
                                spwMap.on(spwMap.events.MapLoaded, lang.hitch(this, function(){
                                    this.displayResultAndZoom(features);
                                }))
                            }
                        }));
                    }));
                }
            }
        },

        getFieldItemType: function(queryField, layerInfo){
            var type = '';
            if(layerInfo && layerInfo.fields && layerInfo.fields.length > 0){
                array.some(layerInfo.fields, function(field){
                    if(field.name == queryField){
                        type = field.type;
                        return true;
                    }
                    return false;
                });
            }
            return type;
        },

        displayResultAndZoom : function(featureSet){
			setTimeout(lang.hitch(this, function(){

				require(['dojo/_base/array'], function(array){
					array.forEach(featureSet.features, function(f){
						if(f.geometry.type === 'multipoint' && f.geometry.points.length === 1) {
							f.geometry = new esri.geometry.Point(f.geometry.points[0][0],f.geometry.points[0][1], new esri.SpatialReference(31370));
						}
					});
				});
				if(featureSet.features.length <= 0) return;

				if(this.removeOnClose){
					on(this.spwViewer.get('spwMap').get('esriMap').infoWindow, "hide", lang.hitch(this,function(){
						this.spwViewer.get('spwMap').removeFeatures(featureSet.features);
					}));
				}

				for(var i=0; i<featureSet.features.length; i++){
					if (featureSet.features[i] && featureSet.features[i].geometry) {
						featureSet.features[i].geometry.setSpatialReference(this.spwViewer.get('spatialReference'));
					}

				}

				if(this.infoTemplate != null && this.infoTemplate != ""){
					var infoTemplate = new InfoTemplate(this.infoTemplate);
					for(var i=0; i<featureSet.features.length; i++){
						featureSet.features[i].setInfoTemplate(infoTemplate);
					}
					if(this.infoWindowSize != null){
						this.spwViewer.get('spwMap').resizeInfoWindow(this.infoWindowSize.width,this.infoWindowSize.height);
					}
				}

				this.spwViewer.get('spwMap').showFeatures(featureSet.features);

				var infoWindow = this.spwViewer.get('spwMap').get('esriMap').infoWindow;

				var addDeleteButton = lang.hitch(this, function(featureOrEvent) {
					var curr = infoWindow.getSelectedFeature();

					if (infoWindow._deleteButton) {
						domConstruct.destroy(infoWindow._deleteButton);
					}

					if (curr == null && featureSet.features.indexOf(featureOrEvent) < 0) {
						return;
					}
					else if (curr == null) {
						curr = featureOrEvent;
					}

					if (featureSet.features.indexOf(curr) > -1) {
						var link = infoWindow._deleteButton = domConstruct.create('a', {
							'class': 'action zoomTo',
							'style': 'float: right;',
							innerHTML: 'Supprimer',
							href: 'javascript:void(0);'
						}, infoWindow._actionList);

						domClass.remove(infoWindow._actionList, 'hidden');

						on(link, 'click', lang.hitch(this, function() {
							this.spwViewer.get('spwMap').removeFeature(curr);

							if (infoWindow.features && infoWindow.features.length > 1) {
								infoWindow.selectNext();
							}
							else {
								infoWindow.hide();
							}
						}));
					}
				});

				on(infoWindow, 'show', addDeleteButton);
				aspect.after(infoWindow, 'onSelectionChange', addDeleteButton);

				infoWindow.setFeatures(featureSet.features);

				if(this.autoOpenTemplate != null && this.autoOpenTemplate && featureSet.features[0]){
						
					var spwMap = this.spwViewer.get('spwMap');
					var handler = spwMap.on(spwMap.events.MapUpdateEnd, lang.hitch(this, function(){
						handler.remove();
						//setTimeout(lang.hitch(this, function(){
	
						var feature = featureSet.features[0];
						if(typeof feature.geometry.getPoint != 'undefined'){
							this.spwViewer.get('spwMap').showInfoWindowAt(infoTemplate.title, Utils.mergeTemplateWithFeature(infoTemplate.content, feature),feature.geometry.getPoint(0,0));
						} if(featureSet.geometryType == "esriGeometryPoint" || (feature.geometry.type == 'point' && featureSet.features.length == 1)){
							this.spwViewer.get('spwMap').showInfoWindowAt(infoTemplate.title, Utils.mergeTemplateWithFeature(infoTemplate.content, feature),feature.geometry);
						} else {
							this.spwViewer.get('spwMap').showInfoWindowAt(infoTemplate.title, Utils.mergeTemplateWithFeature(infoTemplate.content, feature),feature.geometry.getExtent().getCenter());
						}
						addDeleteButton(feature);
						//}), 2000);
					}));
			   
					this.spwViewer.get('spwMap').zoomToFeatures(featureSet.features);
				}
			}), 2000);
        }
    });
});