Diagnóstico integrado 2020
/** @global
* Flag variable to control drill functionality.
* Such feature is in infoDrill.js file
*/
var isDrillActive = false;
/**
* Transform json data into CSV string
* @param {Object} jsonData - The JSON data, with key-value pairs
* @return {string} The CSV representation.
*/
function convertToCSV(jsonData) {
var csvData = [];
csvData.push('Atributo,Valor');
for (var key in jsonData.properties) {
var value = jsonData.properties[key];
if (value === null) {
value = '';
} else {
value = value.toString().replace(/"/g, '""');
}
csvData.push('"' + key + '","' + value + '"');
}
return csvData.join('\n');
}
L.TileLayer.BetterWMST = L.TimeDimension.Layer.WMS.extend({
defaultWmsParams: {
service: 'WMS',
request: 'GetMap',
// @option layers: String = ''
// **(required)** Comma-separated list of WMS layers to show.
layers: '',
// @option styles: String = ''
// Comma-separated list of WMS styles.
styles: '',
// @option format: String = 'image/jpeg'
// WMS image format (use `'image/png'` for layers with transparency).
format: 'image/jpeg',
// @option transparent: Boolean = false
// If `true`, the WMS service will return images with transparency.
transparent: false,
// @option version: String = '1.1.1'
// Version of the WMS service to use
version: '1.1.1'
},
options: {
// @option crs: CRS = null
// Coordinate Reference System to use for the WMS requests, defaults to
// map CRS. Don't change this if you're not sure what it means.
crs: null,
// @option uppercase: Boolean = false
// If `true`, WMS request parameter keys will be uppercase.
uppercase: false,
detectRetina: false,
control: null
},
initialize: function(layer, options) {
L.TimeDimension.Layer.WMS.prototype.initialize.call(this, layer, options);
this._url = options.url;
const wmsParams = L.Util.extend({}, this.defaultWmsParams);
// all keys that are not TileLayer options go to WMS params
for (const i in options) {
if (!(i in this.options)) {
wmsParams[i] = options[i];
}
}
options = L.Util.setOptions(this, options);
const realRetina = 1;
const tileSize = this.getTileSize();
wmsParams.width = tileSize.x * realRetina;
wmsParams.height = tileSize.y * realRetina;
wmsParams.layers = options.layers
this.wmsTime = []
this.wmsParams = wmsParams;
this.timeLayerControl = L.control.timeDimension(this.options.mapt,{
position: "topright",
autoPlay: false,
timeSlider: false,
loopButton: true,
playerOptions: {
transitionTime: 125,
loop: true,
}
});
},
getTileSize: function() {
const s = 256;
return s instanceof L.Point ? s : new L.Point(s, s);
},
onAdd: function (map) {
console.log("onAdd log", this)
L.TimeDimension.Layer.WMS.prototype.onAdd.call(this, map);
map.on('click', this.getFeatureInfo, this);
// map.addControl(this.timeLayerControl)
},
onRemove: function (map) {
// Triggered when the layer is removed from a map.
// Unregister a click listener, then do all the upstream WMS things
L.TimeDimension.Layer.WMS.prototype.onRemove.call(this, map);
map.off('click', this.getFeatureInfo, this);
// map.removeControl(this.timeLayerControl)
this.timeLayerControl = null
},
_showLayer: function(layer, time) {
if (this._currentLayer && this._currentLayer !== layer) {
this._currentLayer.hide();
}
layer.show();
if (this._currentLayer && this._currentLayer === layer) {
return;
}
this._currentLayer = layer;
this._currentTime = time;
console.log('Show layer ' + layer.wmsParams.layers + ' with time: ' + new Date(time).toISOString());
},
_update: function(){
L.TimeDimension.Layer.WMS.prototype._update.call(this);
},
getFeatureInfo: function (evt) {
// Make an AJAX request to the server and hope for the best
if (isDrillActive) {
return null
}
var url = this.getFeatureInfoUrl(evt.latlng),
showResults = L.Util.bind(this.showGetFeatureInfo, this);
var layername = this.wmsParams.layers;
showResults(evt.latlng, layername, url);
},
getFeatureInfoUrl: function (latlng) {
// Construct a GetFeatureInfo request URL given a point
console.log("url",this.wmsParams.format)
var point = this._map.latLngToContainerPoint(latlng, this._map.getZoom()),
size = this._map.getSize(),
params = {
request: 'GetFeatureInfo',
service: 'WMS',
srs: 'EPSG:4326',
styles: this.wmsParams.styles,
transparent: this.wmsParams.transparent,
version: this.wmsParams.version,
format: this.wmsParams.format,
bbox: this._map.getBounds().toBBoxString(),
height: size.y,
width: size.x,
layers: this.wmsParams.layers,
query_layers: this.wmsParams.layers,
info_format: 'application/json',
time : 'P1000Y/PRESENT'
};
params[params.version === '1.3.0' ? 'i' : 'x'] = Math.round(point.x);
params[params.version === '1.3.0' ? 'j' : 'y'] = Math.round(point.y);
// Possible FIXME: Let backend to determine origin
url = this._url + L.Util.getParamString(params, this._url, true);
console.log("Formed url: "+url)
return url
},
showGetFeatureInfo: function (latlng, layername, url) {
var pcontent = "";
var e = this;
$.ajax({
url: '/interactive/get_featureinfo',
type: 'POST',
data: {'layername':layername,
'url': url,
csrfmiddlewaretoken: 'L0me39nnLzDgTWyERyRYeyoLStHO0HJz'
},
dataType: 'json',
success: function(data) {
console.warn(data);
var jdata = data.properties;
var desc = data.attr_desc;
pcontent += '
Atributo Valor '
if(!jQuery.isEmptyObject(desc)){
// if (census.getConstants()) {
// $.each(jdata, function(key, value){
// if(value==null){
// value='';
// }
// if(!isNaN(value)){
// if(value.toString().indexOf('.') != -1){
// var arr = value.toString().split('.');
// var trunc = arr[1].substring(0, 2);
// pcontent += ''+desc[key]+' '+arr[0]+'.'+trunc+' ';
// } else{
// pcontent += ''+desc[key]+' '+value+' ';
// }
// } else {
// pcontent += ''+desc[key]+' '+value+' ';
// }
// });
// var container = $('
');
// container.on('click', 'div.click-census-analysis', function() {
// if (typeof($(".layer-selected").attr('id')) != "undefined") {
// var swt_id = $(".layer-selected").attr('id').slice(1);
// var lay_id = $("#"+swt_id).attr('data-regid');
// if (typeof(lay_id) != "undefined") {
// census.getResultsCensus(jdata,lay_id);
// }
// }
// });
// pcontent += 'Analisis para el objeto seleccionado
';
// pcontent += '
';
// container.html(pcontent);
// L.popup()
// .setLatLng(latlng)
// .setContent(container[0], customOptions)
// .openOn(e._map);
// }else{
$.each(jdata, function(key, value){
if(value==null){
value='';
}
if(!isNaN(value)){
if(value.toString().indexOf('.') != -1){
var arr = value.toString().split('.');
var trunc = arr[1].substring(0, 2);
pcontent += '
'+desc[key]+' '+arr[0]+'.'+trunc+' ';
} else{
pcontent += ''+desc[key]+' '+value+' ';
}
} else {
pcontent += ''+desc[key]+' '+value+' ';
}
});
pcontent += ''
// Add the download button to the popup content
var csvData = convertToCSV(data);
var downloadButton = 'Download CSV ';
pcontent += downloadButton;
L.popup()
.setLatLng(latlng)
.setContent(pcontent)
.openOn(e._map);
// }
}
else{
$.each(jdata, function(key, value){
//pcontent += ''+key+' = '+value+'
';
pcontent += ''+key+' '+value+' ';
});
pcontent += ''
L.popup()
.setLatLng(latlng)
.setContent(pcontent)
.openOn(e._map);
}
},
error: function() {
console.log('There is an error in the response');
}
});
}
});
L.tileLayer.betterWmsTime = function (url, options) {
return new L.TileLayer.BetterWMST(url, options);
};
// BETTERWMS CON MEJORAS DE BUSQUEDA
// function addLayerSearch(currentHref, typename){
// var url = currentHref.replace("wms","wfs");
// var params = {
// 'service': 'wfs',
// 'request': 'GetFeature',
// 'version': '2.0.0',
// 'typeNames': typename,
// 'format': 'application/json',
// 'info_format' : 'application/json',
// 'outputFormat': 'application/json'
// }
// url = url + L.Util.getParamString(params, url, params.uppercase);
// $.ajax({
// url: url,
// type: 'GET',
// success: function(data){
// searchLayer = L.geoJSON(data,{pointToLayer: function(){}}).addTo(map)
// searchControl = new L.Control.Search({
// layer: searchLayer,
// marker: true,
// propertyName:'radio',
// moveToLocation: function(latlng, title, map) {
// //map.fitBounds( latlng.layer.getBounds() );
// var zoom = map.getBoundsZoom(latlng.layer.getBounds());
// map.setView(latlng, zoom); // access the zoom
// }
// })
// }
// })
// }
L.TileLayer.BetterWMS = L.TileLayer.WMS.extend({
initialize(url, options) {
L.TileLayer.WMS.prototype.initialize.call(this,url, options);
this.wmsParams = L.Util.extend({
time : 'P1000Y/PRESENT'
}, this.wmsParams);
this.searchLayer = null;
this.searchData = null
this.searchControl = null;
this.mapt = this.options.mapt
this.layerGroupWms = new L.LayerGroup();
},
_getGeojsonLayer: function(){
var e = this
var url = this._url.replace("wms","wfs");
let protocol = window.location.protocol;
if (protocol.includes("https") && !url.includes("https")) {
url = url.replace("http", "https");
}
var params = {
'service': 'wfs',
'request': 'GetFeature',
'version': '2.0.0',
'typeNames': this.wmsParams.layers,
'format': 'application/json',
'info_format' : 'application/json',
'outputFormat': 'application/json'
}
url = url + L.Util.getParamString(params, url, params.uppercase);
console.log("geojson wfs url", url);
$.ajax({
url: url,
type: 'GET',
success: function(data){
e.searchData = data
console.log("success geojson data", data);
},
complete: function(){
e.searchLayer = L.geoJSON(e.searchData,{
pointToLayer: function(geoJsonPoint, latlng) {
return L.marker(latlng,{
"opacity": 0
});
}
})
console.log("searchLayer", e.searchLayer)
e.layerGroupWms.addLayer(e.searchLayer)
var layername = e.wmsParams.layers.replace("geonode:","");
e.searchControl = new L.Control.Search({
marker: false,
layer: e.layerGroupWms,
textPlaceholder: layername,
autoType: false,
position: 'topright',
propertyName: e.options.attributeSearch,
minLength: 0,
moveToLocation: function(latlng, title, map) {
console.log(latlng,title,map)
map.setView(latlng, 16); // access the zoom
},
filterData: function(text, records){
const frecords = {};
text = text.replace(new RegExp('[.*+?^${}()|[\]\\]','g'), '')
// sanitize remove all special characters
if (text === '' || !text) {
console.log("No text", records);
return records;
}
const regSearch = new RegExp(text, 'i');
for (const key in records) {
if (regSearch.test(key)) {
frecords[key] = records[key];
}
}
console.log(text,frecords);
return frecords;
}
}).addTo(e.mapt)
// Change the id of the created input (searchtext{lenght of placeholder})
$(`#searchtext${layername.length}`).attr("id", `searchtext-${layername}`);
},
error: function(error) {
console.error("Failure on search (geojson)", error);
}
})
},
_update: function(){
L.TileLayer.WMS.prototype._update.call(this);
// map.addControl(this.controlSearch)
},
onAdd: function (map) {
// Triggered when the layer is added to a map.
// Register a click listener, then do all the upstream WMS things
L.TileLayer.WMS.prototype.onAdd.call(this, map);
map.on('click', this.getFeatureInfo, this);
// this.searchControl.addTo(map)
if( this.options.attributeSearch != "" && this.options.attributeSearch.length >= 1){
this._getGeojsonLayer()
this.layerGroupWms.addTo(map);
}
},
onRemove: function (map) {
// Triggered when the layer is removed from a map.
// Unregister a click listener, then do all the upstream WMS things
L.TileLayer.WMS.prototype.onRemove.call(this, map);
map.off('click', this.getFeatureInfo, this);
if(map.hasLayer(this.layerGroupWms)){
map.removeLayer(this.layerGroupWms)
map.removeControl(this.searchControl)
}
},
getFeatureInfo: function (evt) {
console.log(evt)
// Make an AJAX request to the server and hope for the best
if (isDrillActive) {
return null
}
var url = this.getFeatureInfoUrl(evt.latlng),
showResults = L.Util.bind(this.showGetFeatureInfo, this);
var layername = this.wmsParams.layers;
showResults(evt.latlng, layername, url);
},
getFeatureInfoUrl: function (latlng) {
// Construct a GetFeatureInfo request URL given a point
console.log("url",this.wmsParams.format)
var point = this._map.latLngToContainerPoint(latlng, this._map.getZoom()),
size = this._map.getSize(),
params = {
request: 'GetFeatureInfo',
service: 'WMS',
srs: 'EPSG:4326',
styles: this.wmsParams.styles,
transparent: this.wmsParams.transparent,
version: this.wmsParams.version,
format: this.wmsParams.format,
bbox: this._map.getBounds().toBBoxString(),
height: size.y,
width: size.x,
layers: this.wmsParams.layers,
query_layers: this.wmsParams.layers,
info_format: 'application/json',
time : 'P1000Y/PRESENT'
};
params[params.version === '1.3.0' ? 'i' : 'x'] = Math.round(point.x);
params[params.version === '1.3.0' ? 'j' : 'y'] = Math.round(point.y);
url = this._url + L.Util.getParamString(params, this._url, true);
// Possible FIXME: Let backend to determine origin
console.log("Formed url: "+url)
return url
},
showGetFeatureInfo: function (latlng, layername, url) {
var pcontent = "";
var e = this;
$.ajax({
url: '/interactive/get_featureinfo',
type: 'POST',
data: {'layername':layername,
'url': url,
csrfmiddlewaretoken: 'L0me39nnLzDgTWyERyRYeyoLStHO0HJz'
},
dataType: 'json',
success: function(data) {
console.log(data);
var jdata = data.properties;
var desc = data.attr_desc;
pcontent += 'Atributo Valor '
if(!jQuery.isEmptyObject(desc)){
// if (census.getConstants()) {
// $.each(jdata, function(key, value){
// if(value==null){
// value='';
// }
// if(!isNaN(value)){
// if(value.toString().indexOf('.') != -1){
// var arr = value.toString().split('.');
// var trunc = arr[1].substring(0, 2);
// pcontent += ''+desc[key]+' '+arr[0]+'.'+trunc+' ';
// } else{
// pcontent += ''+desc[key]+' '+value+' ';
// }
// } else {
// pcontent += ''+desc[key]+' '+value+' ';
// }
// });
// var container = $('
');
// container.on('click', 'div.click-census-analysis', function() {
// if (typeof($(".layer-selected").attr('id')) != "undefined") {
// var swt_id = $(".layer-selected").attr('id').slice(1);
// var lay_id = $("#"+swt_id).attr('data-regid');
// if (typeof(lay_id) != "undefined") {
// census.getResultsCensus(jdata,lay_id);
// }
// }
// });
// pcontent += 'Analisis para el objeto seleccionado
';
// pcontent += '
';
// container.html(pcontent);
// L.popup()
// .setLatLng(latlng)
// .setContent(container[0], customOptions)
// .openOn(e._map);
// }else{
$.each(jdata, function(key, value){
if(value==null){
value='';
}
if(!isNaN(value)){
if(value.toString().indexOf('.') != -1){
var arr = value.toString().split('.');
var trunc = arr[1].substring(0, 2);
pcontent += ''+desc[key]+' '+arr[0]+'.'+trunc+' ';
} else{
pcontent += ''+desc[key]+' '+value+' ';
}
} else {
pcontent += ''+desc[key]+' '+value+' ';
}
});
pcontent += ''
// Add the download button to the popup content
var csvData = convertToCSV(data);
var downloadButton = 'Download CSV ';
pcontent += downloadButton;
L.popup()
.setLatLng(latlng)
.setContent(pcontent)
.openOn(e._map);
// }
}
else{
$.each(jdata, function(key, value){
//pcontent += ''+key+' = '+value+'
';
pcontent += ''+key+' '+value+' ';
});
pcontent += ''
L.popup()
.setLatLng(latlng)
.setContent(pcontent)
.openOn(e._map);
}
},
error: function() {
console.log('There is an error in the response');
}
});
}
});
L.tileLayer.betterWms = function (url, options) {
return new L.TileLayer.BetterWMS(url, options);
};
/*
Esta clase es el js para los Chats de los mapas
*/