Source: api/CsvLayer.js

Retour à la documentation
define(["dojo/_base/declare", "spw/api/DataLayer", "esri/request", "spw/api/Utils", "dojo/_base/array", "dojo/_base/lang", "esri/tasks/query", "esri/tasks/QueryTask", "dojo/DeferredList"], function(declare, DataLayer, request, Utils, array, lang, Query, QueryTask, DeferredList) {

    /**
			 * @class spw.api.CsvLayer
			 * @classdesc Layer construit sur base d'un fichier CSV (précisé par
			 *            une URL ou par son contenu)
			 * @extends {spw.api.DataLayer}
			 */
    return declare("spw.api.CsvLayer", [DataLayer], /** @lends spw.api.CsvLayer.prototype */
    {

        // START : options
        _options: null,

        // url des données
        url: null,
        // contenu du fichie csv
        csvString: null,

        xField: 'x',
        yField: 'y',
        longField: 'longitude',
        latField: 'latitude',

        customField: 'capakey',
        serviceField: "CAPAKEY",
        serviceUrl: "//geoservices.wallonie.be/arcgis/rest/services/PLAN_REGLEMENT/CADMAP_PARCELLES/MapServer/0",

        showTemplate: false,
        // END : options

        /**
						 * Récupère les données et les transforme en features
						 * 
						 * @memberOf spw.api.DataLayer
						 */
        fetchData: function(map, surface) {
            if (this.url) {
                request({
                    url: this.url,
                    handleAs: "text"
                }).then(lang.hitch(this, function(text) {
                    this.csvString = text;
                    this.processCsvString();
                }), lang.hitch(this, function(err) {
                    this.emit('error', lang.mixin(err, {
                        type: 'loadError'
                    }));
                }));
            } else if (this.csvString) {
                this.processCsvString();
            }
        },

        processCsvString: function() {
            var csvJson = Utils.csvToJson(this.csvString);
            if (this.showTemplate && csvJson.length > 0) {
                this.infoTemplate = {
                    title: "Attributs"
                };
                var content = "";
                for (var k in csvJson[0]) {
                	var lk = k.toLowerCase();
                    if (lk !== this.yField && lk !== this.xField && lk !== this.latField && lk !== this.longField) {
                        content += k + ": " + "${" + k + "}<br/>";
                    }
                }
                this.infoTemplate.content = content;
            }

            var lowerKeys = {}; for(var k in csvJson[0]) lowerKeys[k.toLowerCase()] = csvJson[0][k];
            if (csvJson && csvJson.length > 0 && this.customField in lowerKeys && lowerKeys[this.customField]) {
                var values = array.map(csvJson, lang.hitch(this, function(csv) {
                    var lowerCsv = {}; for(var k in csv) lowerCsv[k.toLowerCase()] = csv[k];
                    return lowerCsv[this.customField];
                }))
                  , valuesArr = [];
                while (values.length > 0) {
                    valuesArr.push(values.splice(0, 999));
                }

                var defs = [];
                array.forEach(valuesArr, lang.hitch(this, function(arr) {
                    var query = new Query();
                    query.returnGeometry = true;
                    query.outFields = [this.serviceField];
                    query.outSpatialReference = this._map.spatialReference;
                    query.where = this.serviceField + " IN ('" + arr.join("','") + "')";

                    var queryTask = new QueryTask(this.serviceUrl);
                    defs.push(queryTask.execute(query));
                }));
                var dl = new DeferredList(defs);
                dl.then(lang.hitch(this, function(res) {
                    this.format = 'NATIVE';
                    this.features = [];
                    array.forEach(res, lang.hitch(this, function(r) {
                        if (r[0] && r[1].features && r[1].features.length > 0) {
                            this.graphicType = r[1].features[0].geometry.type;
                            array.forEach(r[1].features, lang.hitch(this, function(f) {
                                f.properties = array.filter(csvJson, lang.hitch(this, function(j) {
                                    var lowerCsv = {}; for(var k in j) lowerCsv[k.toLowerCase()] = j[k];

                                    return lowerCsv[this.customField] == f.attributes[this.serviceField];
                                }))[0];
                                this.features.push(f);
                            }));
                        }
                    }));
                    if(!this.features || this.features.length == 0) {
                    	//TODO : toast or service error : alert("aucune donnée trouvée");
                    }
                    this.processFeatures();
                }));
            } else {
                this.features = this._createGeoJsonFeatures(csvJson);
                this.processFeatures();
            }
        },

        _createGeoJsonFeatures: function(csvJson) {
            var features = [];
            array.forEach(csvJson, lang.hitch(this, function(j) {
                var lowerCsv = {}; for(var k in j) lowerCsv[k.toLowerCase()] = j[k];

                var y = lowerCsv[this.yField]
                  , x = lowerCsv[this.xField];

                var lon = lowerCsv[this.longField]
                  , lat = lowerCsv[this.latField];

                if ((x == null || y == null || x == '' || y == '') && (lon == null || lat == null || lon == '' || lat == '')) {
                    this._mapService.set('valuesIgnored', true);
                    return;
                }

                if (x != null && y != null) {
                    x = x.replace(',', '.');
                    y = y.replace(',', '.');
                }

                if (lat != null && lon != null) {
                    lat = lat.replace(',', '.');
                    lon = lon.replace(',', '.');
                }

                if (!isNaN(x) && !isNaN(y)) {
                    delete j[this.yField];
                    delete j[this.xField];

                    var f = {
                        geometry: {
                            type: "Point",
                            coordinates: [(isNaN(x) ? 0 : parseFloat(x)), (isNaN(y) ? 0 : parseFloat(y))]
                        },
                        properties: j,
                        srid: this.srid
                    };
                    features.push(f);
                } else if (!isNaN(lat) && !isNaN(lon)) {
                    delete j[this.latField];
                    delete j[this.longField];

                    var f = {
                        geometry: {
                            type: 'Point',
                            coordinates: [lon, lat]
                        },
                        properties: j,
                        srid: 4326
                    };
                    features.push(f);
                } else {
                    this._mapService.set('valuesIgnored', true);
                }
            }));
            return features;
        }

    });
});