Commit b6b23002 authored by Rodrigo Tapia-McClung's avatar Rodrigo Tapia-McClung

Big code and style clean up

parent 7456fdbd
...@@ -5,32 +5,14 @@ ...@@ -5,32 +5,14 @@
* August 2019 - June 2020 * August 2019 - June 2020
*/ */
/* global baseFileSize, formatBytes, Promise, omnivore, JSZip, map, layerControl, intervals, updateCharts, odClick, am4core*/ /* global Promise, omnivore, JSZip, map, layerControl, intervals, odClick, am4core*/
/* exported, odData, makeBaseMap, baseLayerPromises, drawnItems */ /* exported, odData, makeBaseMap, baseLayerPromises */
/* Lines related to displaying loading bar are commented */ let baseLayerPromises = [],
od, flowMapsArray = [],
let baseLayerPromises = [];
/* baseSize = 0,
baseDisplaySize,
baseLoadedSize = 0,
baseLoadedDisplaySize,
baseLayerCounter = 0,
currentBaseLayer = 1;*/
//let drawnItems;
let od, flowMapsArray = [],
odData = {}; odData = {};
/*Object.keys(baseFileSize).forEach((name) => { const compare = (el1, el2, index) => {
if (name.split(".")[1] == "zip") {
baseSize += parseFloat(baseFileSize[name].size); // file size to load for zipped base layers
baseDisplaySize = formatBytes(baseSize, 2); // size in pretty units
baseLayerCounter++;
}
});*/
function compare(el1, el2, index) {
return el1[index] == el2[index] ? 0 : (el1[index] < el2[index] ? -1 : 1); return el1[index] == el2[index] ? 0 : (el1[index] < el2[index] ? -1 : 1);
} }
...@@ -55,17 +37,6 @@ const zip2Lyr = (zipFile, layerName, layerTemplate) => { ...@@ -55,17 +37,6 @@ const zip2Lyr = (zipFile, layerName, layerTemplate) => {
.then(([file, type]) => { .then(([file, type]) => {
file.async("string").then( file.async("string").then(
function success(text) { // 5) display the result function success(text) { // 5) display the result
/*let baseFile = zipFile.split("/")[3];
¬baseLoadedSize += parseFloat(baseFileSize[baseFile].size); // cumulative loaded size
baseLoadedDisplaySize = formatBytes(baseLoadedSize); // in pretty units
let baseBarWidth = (baseLoadedSize/baseSize*100);*/
/*currentBaseLayer++;
let baseFiles = currentBaseLayer <= baseLayerCounter ? currentBaseLayer : baseLayerCounter;
$("#basemap-fileLoad").html("Cargando capa " + baseFiles + " de " + baseLayerCounter + "<br>" +
"<span class=\"progress\"><span id=\"baseBar\" class=\"progress-bar progress-bar-striped progress-bar-animated\" role=\"progressbar\" style=\"width: " + baseBarWidth + "%;\" aria-valuenow=\"" + baseBarWidth + "\" aria-valuemin=\"0\" aria-valuemax=\"100\"></span>" +
"<span class=\"justify-content-center d-flex position-absolute w-100\">" + baseLoadedDisplaySize + "/" + baseDisplaySize + "</span></span>");
*/
if (type == "json") { if (type == "json") {
layerTemplate.addData(JSON.parse(text)); layerTemplate.addData(JSON.parse(text));
} else if (type == "topojson") { } else if (type == "topojson") {
...@@ -89,47 +60,12 @@ const createPane = (layerPane, zIndex) => { ...@@ -89,47 +60,12 @@ const createPane = (layerPane, zIndex) => {
map.getPane(layerPane).style["mix-blend-mode"] = "normal"; map.getPane(layerPane).style["mix-blend-mode"] = "normal";
} }
// const getSchoolColor = s => {
// return s == "Básico" ? "#409400" :
// s == "Medio superior" ? "#df6400" :
// "#c0d1e5";
// }
// const getCommerceColor = s => {
// return s == "Comercio al por menor en supermercados" ? "#9e4244" :
// s == "Comercio al por menor en tiendas departamentales" ? "#fc464e" :
// "#c0d1e5";
// }
const getCentrosColor = s => { const getCentrosColor = s => {
return s == "Primario" ? "#ff5500" : return s == "Primario" ? "#ff5500" :
s == "Secundario" ? "#8e1973" : s == "Secundario" ? "#8e1973" :
"#d1ff73"; "#d1ff73";
} }
// const getCultivoBorder = s => {
// return s == "" ? "#e60000" : // :
// s == "Frijol" ? "#a80084" :
// "#aaff00"; //;
// }
// const getPoblacionColor = s => {
// return s > 6000 ? "#6b0601" :
// s > 4000 ? "#9e4410" :
// s > 2500 ? "#d68522" :
// s > 1000 ? "#f7ba3e" :
// s > 0 ? "#fcdd5d" :
// "#ffffff";
// }
// const getDensidadColor = s => {
// return s > 16000 ? "#633096" :
// s > 11500 ? "#8c6fbd" :
// s > 7000 ? "#a6a2eb" :
// s > 2400 ? "#d2d3fa" :
// s > 0 ? "#f1f0fc" :
// "#ffffff";
// }
const getHaciaColor = s => { const getHaciaColor = s => {
return s > 32000 ? "#00451c" : return s > 32000 ? "#00451c" :
s > 6000 ? "#218542" : s > 6000 ? "#218542" :
...@@ -159,40 +95,9 @@ const getDesdePOICColor = s => { ...@@ -159,40 +95,9 @@ const getDesdePOICColor = s => {
"#ffebbf"; "#ffebbf";
} }
const getEntreColor = s => {
return s > 3500 ? "#a80000" :
s > 2000 ? "#e64c00" :
s > 1000 ? "#ffaa00" :
"#70a800";
}
const getCuencasColor = s => {
return s == "Bajo Grijalva o Grijalva-Villahermosa" ? "rgba(255,255,190,0.3)" :
s == "Medio Grijalva o Grijalva-Tuxtla Gutiérrez" ? "rgba(255,170,0,0.3)" :
"rgba(168,56,0,0.3)";
}
let munis_contexto, lim_zms, zms, conurbaciones, agebs2005, agebs2010, agebs2015, auto2010, auto2014, auto2018, tecnologia2010, tecnologia2014, tecnologia2018, centros, hacia, desde, centrosPOIC, haciaPOIC, desdePOIC; let munis_contexto, lim_zms, zms, conurbaciones, agebs2005, agebs2010, agebs2015, auto2010, auto2014, auto2018, tecnologia2010, tecnologia2014, tecnologia2018, centros, hacia, desde, centrosPOIC, haciaPOIC, desdePOIC;
//supermercados, bancos, agebsbypop, agebsbydens, agricolaoi, agricolapv, escuelas, hospitales, hoteles, subcuencas, tuxtlaVH;
// *** WMS INEGI *** // *** WMS INEGI ***
// // AEROPUERTOS
// let layer_aeropuertos = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
// layers: "c201",
// format: "image/svg+xml",
// transparent: true,
// //pane: "pane_aeropuertosypistas",
// attribution: "INEGI 2019",
// minZoom: 9
// });
// // VIAS FERREAS
// let layer_vferreas = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
// layers: "c202",
// format: "image/svg+xml",
// transparent: true,
// pane: "pane_vferreas",
// attribution: "INEGI 2019"
// });
//Límite geoestadístico estatal //Límite geoestadístico estatal
let layer_limiteEstatal = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", { let layer_limiteEstatal = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
layers: "c100", //Límite geoestadístico estatal layers: "c100", //Límite geoestadístico estatal
...@@ -201,15 +106,6 @@ let layer_limiteEstatal = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunn ...@@ -201,15 +106,6 @@ let layer_limiteEstatal = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunn
pane: "pane_estatal", pane: "pane_estatal",
attribution: "INEGI 2019" attribution: "INEGI 2019"
}); });
// // NOMBRES DE CUERPOS DE AGUA
// let layer_nombresWB = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
// layers: "t311",
// format: "image/svg+xml",
// transparent: true,
// attribution: "INEGI 2019",
// minZoom: 9,
// pane: "pane_wbnames"
// });
//RED NACIONAL DE CAMINOS //RED NACIONAL DE CAMINOS
let layer_RedNacionalCaminos = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", { let layer_RedNacionalCaminos = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
layers: "RNC", //Red nacional de caminos layers: "RNC", //Red nacional de caminos
...@@ -218,16 +114,7 @@ let layer_RedNacionalCaminos = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB ...@@ -218,16 +114,7 @@ let layer_RedNacionalCaminos = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB
pane: "pane_carreteras", pane: "pane_carreteras",
attribution: "INEGI 2019" attribution: "INEGI 2019"
}); });
//MANZANAS
// let layer_manzanaswms = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
// layers: "c104",
// format: "image/svg+xml",
// transparent: true,
// pane: "pane_manzanas",
// attribution: "INEGI 2019",
// minZoom: 13,
// maxZoom: 18
// });
//LOCALIDAD URBANA //LOCALIDAD URBANA
let layer_locUrban = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", { let layer_locUrban = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel/wms/wms61?", {
layers: "c102", layers: "c102",
...@@ -250,13 +137,7 @@ let layer_limiteMunicipal = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tu ...@@ -250,13 +137,7 @@ let layer_limiteMunicipal = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tu
let layer_auto2010 = new L.geoJson(null, { let layer_auto2010 = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_auto2010", pane: "pane_auto2010",
// minZoom: 9, pointToLayer: (feature, latlng) => {
//onEachFeature: pop_escuelas,
pointToLayer: function(feature, latlng) {
// let context = {
// feature: feature,
// variables: {}
// };
let autoMarker = L.BeautifyIcon.icon({ let autoMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -267,8 +148,7 @@ let layer_auto2010 = new L.geoJson(null, { ...@@ -267,8 +148,7 @@ let layer_auto2010 = new L.geoJson(null, {
html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(0,121,159,0.3);font-size: 8px;\"></i></span>", html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(0,121,159,0.3);font-size: 8px;\"></i></span>",
borderWidth: 0, borderWidth: 0,
borderColor: "transparent", borderColor: "transparent",
backgroundColor: "transparent" //, backgroundColor: "transparent"
// textColor: "#C0C0C0"
}); });
return new L.Marker(latlng, { return new L.Marker(latlng, {
icon: autoMarker icon: autoMarker
...@@ -279,13 +159,7 @@ let layer_auto2010 = new L.geoJson(null, { ...@@ -279,13 +159,7 @@ let layer_auto2010 = new L.geoJson(null, {
let layer_auto2014 = new L.geoJson(null, { let layer_auto2014 = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_auto2014", pane: "pane_auto2014",
// minZoom: 9, pointToLayer: (feature, latlng) => {
//onEachFeature: pop_escuelas,
pointToLayer: function(feature, latlng) {
// let context = {
// feature: feature,
// variables: {}
// };
let autoMarker = L.BeautifyIcon.icon({ let autoMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -296,8 +170,7 @@ let layer_auto2014 = new L.geoJson(null, { ...@@ -296,8 +170,7 @@ let layer_auto2014 = new L.geoJson(null, {
html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(60,75,175,0.3);font-size: 8px;\"></i></span>", html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(60,75,175,0.3);font-size: 8px;\"></i></span>",
borderWidth: 0, borderWidth: 0,
borderColor: "transparent", borderColor: "transparent",
backgroundColor: "transparent" //, backgroundColor: "transparent"
// textColor: "#C0C0C0"
}); });
return new L.Marker(latlng, { return new L.Marker(latlng, {
icon: autoMarker icon: autoMarker
...@@ -308,25 +181,18 @@ let layer_auto2014 = new L.geoJson(null, { ...@@ -308,25 +181,18 @@ let layer_auto2014 = new L.geoJson(null, {
let layer_auto2018 = new L.geoJson(null, { let layer_auto2018 = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_auto2018", pane: "pane_auto2018",
// minZoom: 9, pointToLayer: (feature, latlng) => {
//onEachFeature: pop_escuelas,
pointToLayer: function(feature, latlng) {
// let context = {
// feature: feature,
// variables: {}
// };
let autoMarker = L.BeautifyIcon.icon({ let autoMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
iconAnchor: [7, 10], iconAnchor: [7, 10],
iconShape: "", //"circle", iconShape: "",
popupAnchor: [0, 0], popupAnchor: [0, 0],
innerIconStyle: "font-size: 15px;", innerIconStyle: "font-size: 15px;",
html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(35,53,249,0.3);font-size: 8px;\"></i></span>", html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(35,53,249,0.3);font-size: 8px;\"></i></span>",
borderWidth: 0, borderWidth: 0,
borderColor: "transparent", borderColor: "transparent",
backgroundColor: "transparent" //, backgroundColor: "transparent"
// textColor: "#C0C0C0"
}); });
return new L.Marker(latlng, { return new L.Marker(latlng, {
icon: autoMarker icon: autoMarker
...@@ -337,25 +203,18 @@ let layer_auto2018 = new L.geoJson(null, { ...@@ -337,25 +203,18 @@ let layer_auto2018 = new L.geoJson(null, {
let layer_tecnologia2010 = new L.geoJson(null, { let layer_tecnologia2010 = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_tecnologia2010", pane: "pane_tecnologia2010",
// minZoom: 9, pointToLayer: (feature, latlng) => {
//onEachFeature: pop_escuelas,
pointToLayer: function(feature, latlng) {
// let context = {
// feature: feature,
// variables: {}
// };
let autoMarker = L.BeautifyIcon.icon({ let autoMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
iconAnchor: [7, 10], iconAnchor: [7, 10],
iconShape: "", //"circle", iconShape: "",
popupAnchor: [0, 0], popupAnchor: [0, 0],
innerIconStyle: "font-size: 12px;", innerIconStyle: "font-size: 12px;",
html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(88,24,69,0.3);font-size: 8px;\"></i></span>", html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(88,24,69,0.3);font-size: 8px;\"></i></span>",
borderWidth: 0, borderWidth: 0,
borderColor: "transparent", borderColor: "transparent",
backgroundColor: "transparent" //, backgroundColor: "transparent"
// textColor: "#C0C0C0"
}); });
return new L.Marker(latlng, { return new L.Marker(latlng, {
icon: autoMarker icon: autoMarker
...@@ -366,25 +225,18 @@ let layer_tecnologia2010 = new L.geoJson(null, { ...@@ -366,25 +225,18 @@ let layer_tecnologia2010 = new L.geoJson(null, {
let layer_tecnologia2014 = new L.geoJson(null, { let layer_tecnologia2014 = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_tecnologia2014", pane: "pane_tecnologia2014",
// minZoom: 9, pointToLayer: (feature, latlng) => {
//onEachFeature: pop_escuelas,
pointToLayer: function(feature, latlng) {
// let context = {
// feature: feature,
// variables: {}
// };
let autoMarker = L.BeautifyIcon.icon({ let autoMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
iconAnchor: [7, 10], iconAnchor: [7, 10],
iconShape: "", //"circle", iconShape: "",
popupAnchor: [0, 0], popupAnchor: [0, 0],
innerIconStyle: "font-size: 8px;", innerIconStyle: "font-size: 8px;",
html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(144,12,63,0.3);font-size: 8px;\"></i></span>", html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(144,12,63,0.3);font-size: 8px;\"></i></span>",
borderWidth: 0, borderWidth: 0,
borderColor: "transparent", borderColor: "transparent",
backgroundColor: "transparent" //, backgroundColor: "transparent"
// textColor: "#C0C0C0"
}); });
return new L.Marker(latlng, { return new L.Marker(latlng, {
icon: autoMarker icon: autoMarker
...@@ -395,182 +247,30 @@ let layer_tecnologia2014 = new L.geoJson(null, { ...@@ -395,182 +247,30 @@ let layer_tecnologia2014 = new L.geoJson(null, {
let layer_tecnologia2018 = new L.geoJson(null, { let layer_tecnologia2018 = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_tecnologia2018", pane: "pane_tecnologia2018",
// minZoom: 9, pointToLayer: (feature, latlng) => {
//onEachFeature: pop_escuelas,
pointToLayer: function(feature, latlng) {
// let context = {
// feature: feature,
// variables: {}
// };
let autoMarker = L.BeautifyIcon.icon({ let autoMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
iconAnchor: [7, 10], iconAnchor: [7, 10],
iconShape: "", //"circle", iconShape: "",
popupAnchor: [0, 0], popupAnchor: [0, 0],
innerIconStyle: "font-size: 8px;", innerIconStyle: "font-size: 8px;",
html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(199,0,57,0.3);font-size: 8px;\"></i></span>", html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:rgba(199,0,57,0.3);font-size: 8px;\"></i></span>",
borderWidth: 0, borderWidth: 0,
borderColor: "transparent", borderColor: "transparent",
backgroundColor: "transparent" //, backgroundColor: "transparent"
// textColor: "#C0C0C0"
}); });
return new L.Marker(latlng, { return new L.Marker(latlng, {
icon: autoMarker icon: autoMarker
}); });
} }
}); });
// let aeropuertosypistasaereas = new L.layerGroup([layer_aeropuertos, layer_pistasaereas], {
// pane: "pane_aeropuertosypistas",
// minZoom: 9
// });
// let layer_supermercados = new L.geoJson(null, {
// attribution: "",
// pane: "pane_supermercados",
// //onEachFeature: pop_escuelas,
// pointToLayer: function(feature, latlng) {
// // let context = {
// // feature: feature,
// // variables: {}
// // };
// let shoppingMarker = L.BeautifyIcon.icon({
// icon: "shopping-cart",
// iconSize: [0, 0],
// iconAnchor: [7, 10],
// iconShape: "circle",
// popupAnchor: [0, 0],
// innerIconStyle: "font-size: 15px;",
// // html: "<span class=\"fa-stack\"><i class=\"fas fa-shopping-cart fa-stack-1x\" style=\"color:#808080;\"></i></span>",
// borderWidth: 0,
// borderColor: "transparent",
// backgroundColor: "transparent",
// textColor: getCommerceColor(feature.properties["nombre_act"]) //textColor: "#C0C0C0"
// });
// return new L.Marker(latlng, {
// icon: shoppingMarker
// });
// }
// });
// let layer_bancos = new L.geoJson(null, {
// attribution: "",
// pane: "pane_bancos",
// //onEachFeature: pop_escuelas,
// pointToLayer: function(feature, latlng) {
// // let context = {
// // feature: feature,
// // variables: {}
// // };
// let bancosMarker = L.BeautifyIcon.icon({
// icon: "desechos",
// iconSize: [0, 0],
// iconAnchor: [7, 10],
// iconShape: "", //"circle",
// popupAnchor: [0, 0],
// innerIconStyle: "font-size: 12px;",
// html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:#c0ca33;\"></i><i class =\"fas fa-dollar fa-stack-1x fa-inverse\"></i></span>",
// borderWidth: 0,
// borderColor: "transparent",
// backgroundColor: "transparent",
// textColor: "#C0C0C0"
// });
// return new L.Marker(latlng, {
// icon: bancosMarker
// });
// }
// });
// let layer_escuelas = new L.geoJson(null, {
// attribution: "",
// pane: "pane_escuelas",
// //onEachFeature: pop_escuelas,
// pointToLayer: function(feature, latlng) {
// // let context = {
// // feature: feature,
// // variables: {}
// // };
// let escuelaMarker = L.BeautifyIcon.icon({
// icon: "escuela",
// iconSize: [0, 0],
// iconAnchor: [7, 10],
// iconShape: "circle",
// popupAnchor: [0, 0],
// innerIconStyle: "font-size: 15px;",
// borderWidth: 0,
// borderColor: "transparent",
// backgroundColor: "transparent",
// textColor: getSchoolColor(feature.properties["Nivel"])
// });
// return new L.Marker(latlng, {
// icon: escuelaMarker
// });
// }
// });
// let layer_hospitales = new L.geoJson(null, {
// attribution: "",
// pane: "pane_hospitales",
// //onEachFeature: pop_hospitales,
// pointToLayer: function(feature, latlng) {
// // let context = {
// // feature: feature,
// // variables: {}
// // };
// let hospitalMarker = L.BeautifyIcon.icon({
// icon: "desechos",
// iconSize: [0, 0],
// iconAnchor: [7, 10],
// iconShape: "circle",
// popupAnchor: [0, 0],
// innerIconStyle: "font-size: 13px;",
// html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:#ff0000;\"></i><i class =\"fas fa-plus-circle fa-stack-1x fa-inverse\"></i></span>",
// borderWidth: 0,
// borderColor: "transparent",
// backgroundColor: "transparent",
// textColor: "#C0C0C0"
// });
// return new L.Marker(latlng, {
// icon: hospitalMarker
// });
// }
// });
// let layer_hoteles = new L.geoJson(null, {
// attribution: "",
// pane: "pane_hoteles",
// //onEachFeature: pop_hoteles,
// pointToLayer: function(feature, latlng) {
// // let context = {
// // feature: feature,
// // variables: {}
// // };
// let hotelMarker = L.BeautifyIcon.icon({
// icon: "bed",
// iconSize: [0, 0],
// iconAnchor: [7, 10],
// iconShape: "circle",
// popupAnchor: [0, 0],
// innerIconStyle: "font-size: 12px;",
// borderWidth: 0,
// borderColor: "transparent",
// backgroundColor: "transparent",
// textColor: "#808080"
// });
// return new L.Marker(latlng, {
// icon: hotelMarker
// });
// }
// });
const style_munis_contexto = () => { const style_munis_contexto = () => {
return { return {
pane: "pane_munis_contexto", pane: "pane_munis_contexto",
opacity: 1, opacity: 1,
color: "rgba(110,110,110,0.4)", color: "rgba(110,110,110,0.4)",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 1.0, weight: 1.0,
...@@ -582,7 +282,6 @@ const style_munis_contexto = () => { ...@@ -582,7 +282,6 @@ const style_munis_contexto = () => {
let layer_munis_contexto = new L.geoJson(null, { let layer_munis_contexto = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_munis_contexto", pane: "pane_munis_contexto",
//onEachFeature: pop_cuencas,
style: style_munis_contexto style: style_munis_contexto
}); });
...@@ -602,7 +301,6 @@ const style_limZMs = () => { ...@@ -602,7 +301,6 @@ const style_limZMs = () => {
let layer_limZMs = new L.geoJson(null, { let layer_limZMs = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_limZMs", pane: "pane_limZMs",
//onEachFeature: pop_limZMs,
style: style_limZMs style: style_limZMs
}); });
...@@ -623,7 +321,6 @@ const style_ZMs = () => { ...@@ -623,7 +321,6 @@ const style_ZMs = () => {
let layer_ZMs = new L.geoJson(null, { let layer_ZMs = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_ZMs", pane: "pane_ZMs",
//onEachFeature: pop_ZMs,
style: style_ZMs style: style_ZMs
}); });
...@@ -644,16 +341,13 @@ const style_conurbaciones_rurbana = () => { ...@@ -644,16 +341,13 @@ const style_conurbaciones_rurbana = () => {
let layer_conurbaciones_rurbana = new L.geoJson(null, { let layer_conurbaciones_rurbana = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_conurbaciones", pane: "pane_conurbaciones",
//onEachFeature: pop_ZMs,
style: style_conurbaciones_rurbana style: style_conurbaciones_rurbana
}); });
const style_agebs2005 = () => { const style_agebs2005 = () => {
return { return {
// pane: "pane_agebs2005",
opacity: .9, opacity: .9,
color: "#d6c996", color: "#d6c996",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 0.5, //1.0, weight: 0.5, //1.0,
...@@ -665,18 +359,14 @@ const style_agebs2005 = () => { ...@@ -665,18 +359,14 @@ const style_agebs2005 = () => {
let layer_agebs2005 = new L.geoJson(null, { let layer_agebs2005 = new L.geoJson(null, {
attribution: "", attribution: "",
// pane: "pane_agebs2005",
//onEachFeature: pop_ANPs,
style: style_agebs2005, style: style_agebs2005,
interactive: false interactive: false
}); });
const style_agebs2010 = () => { const style_agebs2010 = () => {
return { return {
// pane: "pane_agebs2010",
opacity: 1, opacity: 1,
color: "#ffaa00", color: "#ffaa00",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 0.5, //1.0, weight: 0.5, //1.0,
...@@ -688,18 +378,14 @@ const style_agebs2010 = () => { ...@@ -688,18 +378,14 @@ const style_agebs2010 = () => {
let layer_agebs2010 = new L.geoJson(null, { let layer_agebs2010 = new L.geoJson(null, {
attribution: "", attribution: "",
// pane: "pane_agebs2010",
//onEachFeature: pop_ANPs,
style: style_agebs2010, style: style_agebs2010,
interactive: false interactive: false
}); });
const style_agebs2015 = () => { const style_agebs2015 = () => {
return { return {
// pane: "pane_agebs2015",
opacity: 1, opacity: 1,
color: "#730000", color: "#730000",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 1.0, weight: 1.0,
...@@ -711,15 +397,12 @@ const style_agebs2015 = () => { ...@@ -711,15 +397,12 @@ const style_agebs2015 = () => {
let layer_agebs2015 = new L.geoJson(null, { let layer_agebs2015 = new L.geoJson(null, {
attribution: "", attribution: "",
// pane: "pane_agebs2015",
//onEachFeature: pop_ANPs,
style: style_agebs2015, style: style_agebs2015,
interactive: false interactive: false
}); });
let crecimiento_urbano = new L.layerGroup([layer_agebs2005, layer_agebs2010, layer_agebs2015], { let crecimiento_urbano = new L.layerGroup([layer_agebs2005, layer_agebs2010, layer_agebs2015], {
pane: "pane_agebs", pane: "pane_agebs"
// minZoom: 9
}); });
const style_centros = feature => { const style_centros = feature => {
...@@ -727,7 +410,6 @@ const style_centros = feature => { ...@@ -727,7 +410,6 @@ const style_centros = feature => {
pane: "pane_centros", pane: "pane_centros",
opacity: 1, opacity: 1,
color: "rgba(110,100,110,0.7)", color: "rgba(110,100,110,0.7)",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 0.5, //1.0, weight: 0.5, //1.0,
...@@ -741,7 +423,6 @@ const style_centros = feature => { ...@@ -741,7 +423,6 @@ const style_centros = feature => {
let layer_centros = new L.geoJson(null, { let layer_centros = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_centros", pane: "pane_centros",
//onEachFeature: pop_ANPs,
style: style_centros, style: style_centros,
interactive: false interactive: false
}); });
...@@ -751,7 +432,6 @@ const style_hacia = feature => { ...@@ -751,7 +432,6 @@ const style_hacia = feature => {
pane: "pane_hacia", pane: "pane_hacia",
opacity: 1, opacity: 1,
color: "rgba(110,110,110,0.7)", color: "rgba(110,110,110,0.7)",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 0.5, //1.0, weight: 0.5, //1.0,
...@@ -764,7 +444,6 @@ const style_hacia = feature => { ...@@ -764,7 +444,6 @@ const style_hacia = feature => {
let layer_hacia = new L.geoJson(null, { let layer_hacia = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_hacia", pane: "pane_hacia",
//onEachFeature: pop_ANPs,
style: style_hacia style: style_hacia
}); });
...@@ -773,7 +452,6 @@ const style_desde = feature => { ...@@ -773,7 +452,6 @@ const style_desde = feature => {
pane: "pane_desde", pane: "pane_desde",
opacity: 1, opacity: 1,
color: "rgba(110,110,110,0.7)", color: "rgba(110,110,110,0.7)",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 0.5, //1.0, weight: 0.5, //1.0,
...@@ -786,7 +464,6 @@ const style_desde = feature => { ...@@ -786,7 +464,6 @@ const style_desde = feature => {
let layer_desde = new L.geoJson(null, { let layer_desde = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_desde", pane: "pane_desde",
//onEachFeature: pop_ANPs,
style: style_desde style: style_desde
}); });
...@@ -795,21 +472,18 @@ const style_centrosPOIC = feature => { ...@@ -795,21 +472,18 @@ const style_centrosPOIC = feature => {
pane: "pane_centrosPOIC", pane: "pane_centrosPOIC",
opacity: 1, opacity: 1,
color: "rgba(110,100,110,0.7)", color: "rgba(110,100,110,0.7)",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 0.5, //1.0, weight: 0.5, //1.0,
fill: true, fill: true,
fillOpacity: .4, fillOpacity: .4,
fillColor: getCentrosColor(feature.properties["POIC"]), fillColor: getCentrosColor(feature.properties["POIC"])
//fillPattern: "stripes"
} }
} }
let layer_centrosPOIC = new L.geoJson(null, { let layer_centrosPOIC = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_centrosPOIC", pane: "pane_centrosPOIC",
//onEachFeature: pop_ANPs,
style: style_centrosPOIC style: style_centrosPOIC
}); });
...@@ -818,7 +492,6 @@ const style_haciaPOIC = feature => { ...@@ -818,7 +492,6 @@ const style_haciaPOIC = feature => {
pane: "pane_haciaPOIC", pane: "pane_haciaPOIC",
opacity: 1, opacity: 1,
color: "rgba(110,110,110,0.7)", color: "rgba(110,110,110,0.7)",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 0.5, //1.0, weight: 0.5, //1.0,
...@@ -831,7 +504,6 @@ const style_haciaPOIC = feature => { ...@@ -831,7 +504,6 @@ const style_haciaPOIC = feature => {
let layer_haciaPOIC = new L.geoJson(null, { let layer_haciaPOIC = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_haciaPOIC", pane: "pane_haciaPOIC",
//onEachFeature: pop_ANPs,
style: style_haciaPOIC style: style_haciaPOIC
}); });
...@@ -840,7 +512,6 @@ const style_desdePOIC = feature => { ...@@ -840,7 +512,6 @@ const style_desdePOIC = feature => {
pane: "pane_desdePOIC", pane: "pane_desdePOIC",
opacity: 1, opacity: 1,
color: "rgba(110,110,110,0.7)", color: "rgba(110,110,110,0.7)",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 0.5, //1.0, weight: 0.5, //1.0,
...@@ -853,47 +524,10 @@ const style_desdePOIC = feature => { ...@@ -853,47 +524,10 @@ const style_desdePOIC = feature => {
let layer_desdePOIC = new L.geoJson(null, { let layer_desdePOIC = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_desdePOIC", pane: "pane_desdePOIC",
//onEachFeature: pop_ANPs,
style: style_desdePOIC style: style_desdePOIC
}); });
/*const styleDrawnItems = () => { let canvasPointRenderer = L.canvas({ pane: "pane_flujos" });
let currentId = 0;
drawnItems.eachLayer(l => {
l.feature.properties.id = currentId;
l.feature.properties.color = d3.schemeCategory10[currentId];
l.setStyle({
fillColor: d3.schemeCategory10[currentId],
opacity: 0.5,
fillOpacity: 0.2,
color: d3.schemeCategory10[currentId],
weight: 4
});
currentId++;
});
}
const toggleButtons = () => {
let buttons = [];
buttons.push(document.getElementsByClassName("leaflet-draw-draw-polyline")[0]);
buttons.push(document.getElementsByClassName("leaflet-draw-draw-polygon")[0]);
buttons.push(document.getElementsByClassName("leaflet-draw-draw-rectangle")[0]);
buttons.forEach(b => {
// disable buttons if there are 10 drawn items
if (drawnItems.getLayers().length >= 10) {
b.onClick = "preventEventDefault(); return false";
b.classList.add("draw-control-disabled");
// enable buttons if there are less than 10 drawn items
} else if (drawnItems.getLayers().length < 10) {
b.onClick = null;
b.classList.remove("draw-control-disabled");
}
})
}*/
let canvasPointRenderer = L.canvas({ pane: 'pane_flujos' });
const createFlowLayer = (geojson, type, addOnCreate) => { const createFlowLayer = (geojson, type, addOnCreate) => {
return new Promise(resolve => { return new Promise(resolve => {
...@@ -925,14 +559,14 @@ const createFlowLayer = (geojson, type, addOnCreate) => { ...@@ -925,14 +559,14 @@ const createFlowLayer = (geojson, type, addOnCreate) => {
shadowColor: intervals[type].colors[idx], shadowColor: intervals[type].colors[idx],
shadowBlur: 1.5 shadowBlur: 1.5
} }
}) });
}); });
$.getJSON(geojson, data => { $.getJSON(geojson, data => {
// build data array from geojson to be used in amchart // build data array from geojson to be used in amchart
let source = data.features; let source = data.features;
let newData = []; let newData = [];
source.forEach(o => newData.push({ 'xVar': o.properties.muni_origen, 'yVar': o.properties.muni_destino, 'flowCount': o.properties.viajes })); source.forEach(o => newData.push({ "xVar": o.properties.muni_origen, "yVar": o.properties.muni_destino, "flowCount": o.properties.viajes }));
let origins = [], let origins = [],
destinations = []; destinations = [];
...@@ -948,14 +582,14 @@ const createFlowLayer = (geojson, type, addOnCreate) => { ...@@ -948,14 +582,14 @@ const createFlowLayer = (geojson, type, addOnCreate) => {
origins.forEach((o) => { origins.forEach((o) => {
destinations.forEach((d) => { destinations.forEach((d) => {
if (!newData.some(data => data.xVar === o && data.yVar === d)) { if (!newData.some(data => data.xVar === o && data.yVar === d)) {
newData.push({ 'xVar': o, 'yVar': d, 'flowCount': 0 }); newData.push({ "xVar": o, "yVar": d, "flowCount": 0 });
} }
}) });
}); });
// sort array by origins and then by destinations // sort array by origins and then by destinations
newData.sort((el1, el2) => { newData.sort((el1, el2) => {
let compared = compare(el1, el2, "xVar") let compared = compare(el1, el2, "xVar");
return compared == 0 ? compare(el1, el2, "yVar") : compared; return compared == 0 ? compare(el1, el2, "yVar") : compared;
}); });
...@@ -990,14 +624,14 @@ const createFlowLayer = (geojson, type, addOnCreate) => { ...@@ -990,14 +624,14 @@ const createFlowLayer = (geojson, type, addOnCreate) => {
}, },
// dot styles // dot styles
style: function(geoJsonFeature) { style: geoJsonFeature => {
if (geoJsonFeature.properties.isOrigin) { if (geoJsonFeature.properties.isOrigin) {
return { return {
renderer: canvasPointRenderer, renderer: canvasPointRenderer,
radius: 5, radius: 5,
weight: 1, weight: 1,
color: 'rgb(195, 255, 62)', color: "rgb(195, 255, 62)",
fillColor: 'rgba(195, 255, 62, 0.6)', fillColor: "rgba(195, 255, 62, 0.6)",
fillOpacity: 0.6 fillOpacity: 0.6
}; };
} else { } else {
...@@ -1005,8 +639,8 @@ const createFlowLayer = (geojson, type, addOnCreate) => { ...@@ -1005,8 +639,8 @@ const createFlowLayer = (geojson, type, addOnCreate) => {
renderer: canvasPointRenderer, renderer: canvasPointRenderer,
radius: 2.5, radius: 2.5,
weight: 0.25, weight: 0.25,
color: 'rgb(17, 142, 170)', color: "rgb(17, 142, 170)",
fillColor: 'rgb(17, 142, 170)', fillColor: "rgb(17, 142, 170)",
fillOpacity: 0.7 fillOpacity: 0.7
}; };
} }
...@@ -1025,17 +659,17 @@ const createFlowLayer = (geojson, type, addOnCreate) => { ...@@ -1025,17 +659,17 @@ const createFlowLayer = (geojson, type, addOnCreate) => {
let coords = layer.getLatLng(); let coords = layer.getLatLng();
let label = od.features.filter(f => f.properties.lng == coords.lng && f.properties.lat == coords.lat); let label = od.features.filter(f => f.properties.lng == coords.lng && f.properties.lat == coords.lat);
return label[0].properties.nombre; return label[0].properties.nombre;
}) });
// if layer is to be added on creation, add click funcionality and populate chart // if layer is to be added on creation, add click funcionality and populate chart
if (addOnCreate) { if (addOnCreate) {
flowMapLayer.addTo(map).on('click', odClick); flowMapLayer.addTo(map).on("click", odClick);
let odChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "topChart"); let odChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "topChart");
odChart.data = newData; odChart.data = newData;
let chordChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "bottomLeftChart"); let chordChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "bottomLeftChart");
chordChart.data = newData; chordChart.data = newData;
chordChart.data = chordChart.data.filter(function(e) { return e.flowCount > 0 }); chordChart.data = chordChart.data.filter( e => e.flowCount > 0 );
} }
flowMapsArray.push(flowMapLayer); flowMapsArray.push(flowMapLayer);
resolve(flowMapsArray); resolve(flowMapsArray);
...@@ -1056,7 +690,6 @@ const makeBaseMap = () => { ...@@ -1056,7 +690,6 @@ const makeBaseMap = () => {
createPane("pane_manzanas", 408); createPane("pane_manzanas", 408);
createPane("pane_estatal", 409); createPane("pane_estatal", 409);
createPane("pane_carreteras", 410); createPane("pane_carreteras", 410);
// createPane("pane_wbnames", 421);
createPane("pane_auto2010", 411); createPane("pane_auto2010", 411);
createPane("pane_auto2014", 411); createPane("pane_auto2014", 411);
createPane("pane_auto2018", 411); createPane("pane_auto2018", 411);
...@@ -1072,10 +705,6 @@ const makeBaseMap = () => { ...@@ -1072,10 +705,6 @@ const makeBaseMap = () => {
createPane("pane_agebs", 421); createPane("pane_agebs", 421);
createPane("pane_flujos", 422); createPane("pane_flujos", 422);
/*$("#basemap-fileLoad").html("Cargando capa 1 de " + baseLayerCounter + "<br>" +
"<span class=\"progress\"><span id=\"baseBar\" class=\"progress-bar progress-bar-striped progress-bar-animated\" role=\"progressbar\" style=\"width: 0%;\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\"></span>" +
"<span class=\"justify-content-center d-flex position-absolute w-100\">0/" + baseDisplaySize + "</span></span>");*/
zip2Lyr("../centropais/data/munis_contexto.zip", munis_contexto, layer_munis_contexto); zip2Lyr("../centropais/data/munis_contexto.zip", munis_contexto, layer_munis_contexto);
layerControl.addOverlay(layer_munis_contexto, "&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(255,255,212,0.4)\" stroke=\"rgba(110,100,100,0.4)\" stroke-dasharray=\" \"></rect></svg>&nbsp; Municipios para dar contexto a la región"); layerControl.addOverlay(layer_munis_contexto, "&nbsp;<svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(255,255,212,0.4)\" stroke=\"rgba(110,100,100,0.4)\" stroke-dasharray=\" \"></rect></svg>&nbsp; Municipios para dar contexto a la región");
zip2Lyr("../centropais/data/munis_conurbaciones_rurbana.zip", conurbaciones, layer_conurbaciones_rurbana); zip2Lyr("../centropais/data/munis_conurbaciones_rurbana.zip", conurbaciones, layer_conurbaciones_rurbana);
...@@ -1127,7 +756,6 @@ const makeBaseMap = () => { ...@@ -1127,7 +756,6 @@ const makeBaseMap = () => {
resetControl.onAdd = () => { resetControl.onAdd = () => {
let div = L.DomUtil.create("div", "leaflet-bar leaflet-control"); let div = L.DomUtil.create("div", "leaflet-bar leaflet-control");
div.innerHTML = "<button type=\"button\" class=\"btn btn-sm btn-light\" id=\"resetFlows\" title=\"Reiniciar fujos\"><i class=\"fa fa-sync-alt\"></i></button>"; div.innerHTML = "<button type=\"button\" class=\"btn btn-sm btn-light\" id=\"resetFlows\" title=\"Reiniciar fujos\"><i class=\"fa fa-sync-alt\"></i></button>";
//div.innerHTML = "<a class=\"btn btn-sm btn-light\" href=\"#\" role=\"button\" id=\"resetFlows\" title=\"Reiniciar fujos\" aria-label=\"aaa\"><i class=\"fa fa-sync-alt\"></i></a>";
return div; return div;
}; };
...@@ -1150,7 +778,7 @@ const makeBaseMap = () => { ...@@ -1150,7 +778,7 @@ const makeBaseMap = () => {
$("#resetFlows").on("click", () => { $("#resetFlows").on("click", () => {
layers.forEach(layer => { layers.forEach(layer => {
if (map.hasLayer(layer)) { if (map.hasLayer(layer)) {
layer.originAndDestinationGeoJsonPoints.features.forEach(function(feature) { layer.originAndDestinationGeoJsonPoints.features.forEach( feature => {
if (feature.properties.isOrigin === true) { if (feature.properties.isOrigin === true) {
feature.properties._isSelectedForPathDisplay = true; feature.properties._isSelectedForPathDisplay = true;
} else { } else {
...@@ -1165,213 +793,8 @@ const makeBaseMap = () => { ...@@ -1165,213 +793,8 @@ const makeBaseMap = () => {
} }
}); });
// TODO: reset amchart // TODO: reset amchart
//let amchart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "amchartdiv") //let amchart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "amchartdiv");
//amchart.data = odData.ocupadosDesde; //amchart.data = odData.ocupadosDesde;
}); });
//resolve(layers);
});
//});
/* // Localize Leaflet.Draw texts
L.drawLocal = {
draw: {
toolbar: {
actions: {
title: "Cancelar dibujo",
text: "Cancelar"
},
finish: {
title: "Terminar dibujo",
text: "Terminar"
},
undo: {
title: "Eliminar último punto dibujado",
text: "Eliminar último punto"
},
buttons: {
polyline: "Dibujar una polilínea",
polygon: "Dibujar un polígono",
rectangle: "Dibujar un rectángulo",
circle: "Dibujar un círculo",
marker: "Dibujar un marcador",
circlemarker: "Dibujar un marcador circular"
}
},
handlers: {
circle: {
tooltip: {
start: "Haz click y arrastra para dibujar un círculo"
},
radius: "Radio"
},
circlemarker: {
tooltip: {
start: "Haz click en el mapa para ubicar el marcador circular"
}
},
marker: {
tooltip: {
start: "Haz click en el mapa para ubicar el marcador"
}
},
polygon: {
error: "<strong>Error:</strong>",
tooltip: {
start: "Haz click para empezar a dibujar la figura",
cont: "Haz click para continuar dibujando la figura",
end: "Haz click en el primer punto para cerrar la figura"
}
},
polyline: {
error: "<strong>Error:</strong> las líneas no deben cruzarse",
tooltip: {
start: "Haz click para empezar a dibujar la línea",
cont: "Haz click para continuar dibujando la línea",
end: "Haz click en el último punto para terminar la línea"
}
},
rectangle: {
tooltip: {
start: "Haz click y arrastra para dibujar un rectángulo"
}
},
simpleshape: {
tooltip: {
end: "Suelta el ratón para terminar de dibujar"
}
}
}
},
edit: {
toolbar: {
actions: {
save: {
title: "Guardar los cambios",
text: "Guardar"
},
cancel: {
title: "Cancelar la edición, descarta todos los cambios",
text: "Cancelar"
},
clearAll: {
title: "Limpiar todas las capas",
text: "Limpiar todo"
}
},
buttons: {
edit: "Editar capas",
editDisabled: "No hay capas que editar",
remove: "Eliminar capas",
removeDisabled: "No hay capas que eliminar"
}
},
handlers: {
edit: {
tooltip: {
text: "Arrastra el marcador para editar la figura",
subtext: "Haz click en cancelar para deshacer los cambios"
}
},
remove: {
tooltip: {
text: "Haz click en una figura para eliminarla"
}
}
}
}
}
// leaflet draw control
drawnItems = L.featureGroup().addTo(map);
let drawControl = new L.Control.Draw({
draw: {
polygon: {
showArea: true,
//allowIntersection: false, // Restricts shapes to simple polygons
//drawError: {
//color: "#f9a800",
//message: "<strong>you can't draw that!" // Message that will show when intersect
//},
shapeOptions: {
color: "#42ffc3"
}
},
// disable toolbar item by setting it to false
polyline: {
//allowIntersection:false,
shapeOptions: {
color: "#42ffc3"
}
},
rectangle: {
shapeOptions: {
color: "#42ffc3"
}
},
marker: false,
circlemarker: false,
circle: false // Turns off this drawing tool
},
edit: {
featureGroup: drawnItems,
//remove: false
}
});
map.addControl(drawControl);
// set z-index of panes so actions can be done on drawnItems when editing/deleting
map.on(L.Draw.Event.CREATED, event => {
$("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
let layer = event.layer,
feature = layer.feature = layer.feature || {}; // Initialize feature
feature.type = feature.type || "Feature"; // Initialize feature.type
feature.properties = feature.properties || {}; // Initialize feature.properties
drawnItems.addLayer(layer); // whatever you want to do with the created layer
// give each drawn item an id and color from an array
styleDrawnItems();
// disable buttons if there are 10 drawn items
toggleButtons();
// after drawing shape, update chart with data for polygons contained inside it
updateCharts();
}); });
map.on(L.Draw.Event.DELETESTART, () => {
// before deleting shape, bring pane up
$("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "451");
});
map.on(L.Draw.Event.DELETED, () => {
// after deleting a drawn item, refresh the list of ids and colors
styleDrawnItems();
// enable buttons if there are less than 10 drawn items
toggleButtons();
// after deleting shape, send pane down
$("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
// and update chart with data:
// if there are drawnItems, use them. If not, use original data
updateCharts();
});
map.on(L.Draw.Event.EDITSTART, () => {
$("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "451");
// before editing shape, bring pane up
});
map.on(L.Draw.Event.EDITSTOP, () => {
$("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
// before editing shape, bring pane up
});
map.on(L.Draw.Event.EDITED, () => {
// before editing shape, send pane down
$("#mexmap .leaflet-pane.leaflet-overlay-pane").css("z-index", "400");
// after editing shape, update chart with data for polygons contained inside it
updateCharts();
});
*/
} }
\ No newline at end of file
...@@ -8,35 +8,34 @@ ...@@ -8,35 +8,34 @@
/* globals am4core, am4charts, am4themes_animated, intervals */ /* globals am4core, am4charts, am4themes_animated, intervals */
let minValue, maxValue; let minValue, maxValue;
let mainTextColor = getComputedStyle(document.body).getPropertyValue('--main-text-color'); let mainTextColor = getComputedStyle(document.body).getPropertyValue("--main-text-color");
let cellbgColor = getComputedStyle(document.body).getPropertyValue('--main-bg-color'); let cellbgColor = getComputedStyle(document.body).getPropertyValue("--main-bg-color");
// amChart // amChart
am4core.ready(function() { am4core.ready(function() {
// Themes begin // Themes begin
//am4core.useTheme(am4themes_animated); am4core.useTheme(am4themes_animated);
am4core.options.autoSetClassName = true; am4core.options.autoSetClassName = true;
// Themes end // Themes end
var chart = am4core.create("topChart", am4charts.XYChart); let chart = am4core.create("topChart", am4charts.XYChart);
chart.maskBullets = false; chart.maskBullets = false;
var title = chart.titles.create(); let title = chart.titles.create();
//title.text = "Viajes de ocupados desde centros de mercado";
title.fill = am4core.color(mainTextColor); title.fill = am4core.color(mainTextColor);
title.fontSize = 15; title.fontSize = 15;
title.marginBottom = 15; title.marginBottom = 15;
chart.events.on("beforedatavalidated", function(ev) { chart.events.on("beforedatavalidated", (ev) => {
let option = $("#indicatorSelect").val(); let option = $("#indicatorSelect").val();
let optionTitle = $("#indicatorSelect option:selected").text(); let optionTitle = $("#indicatorSelect option:selected").text();
title.text = optionTitle; title.text = optionTitle;
var data = ev.target.data; let data = ev.target.data;
minValue = d3.min(data, function(d) { return d.flowCount || Infinity; }); minValue = d3.min(data, d => { return d.flowCount || Infinity; });
maxValue = d3.max(data, function(d) { return d.flowCount; }); maxValue = d3.max(data, d => { return d.flowCount; });
//heatLegend.minValue = minValue; //heatLegend.minValue = minValue;
//heatLegend.maxValue = maxValue; //heatLegend.maxValue = maxValue;
heatLegend.minValue = 0; heatLegend.minValue = 0;
...@@ -48,32 +47,30 @@ am4core.ready(function() { ...@@ -48,32 +47,30 @@ am4core.ready(function() {
heatLegend.minColor = heatColors[0]; heatLegend.minColor = heatColors[0];
heatLegend.maxColor = heatColors[intervals[option].colors.length - 1]; heatLegend.maxColor = heatColors[intervals[option].colors.length - 1];
//let checkConditions = [minValue, ...intervals[option].values.slice(1)];
let checkConditions = [minValue, ...intervals[option].values]; let checkConditions = [minValue, ...intervals[option].values];
let lastValue = intervals[option].values[intervals[option].values.length - 1] let lastValue = intervals[option].values[intervals[option].values.length - 1]
// Override heatLegend gradient // Override heatLegend gradient
let gradient = new am4core.LinearGradient(); let gradient = new am4core.LinearGradient();
heatColors.forEach(function(color, index) { heatColors.forEach( (color, index) => {
// addColor(color, opacity, offset) use offset to put colors in proper alignment // addColor(color, opacity, offset) use offset to put colors in proper alignment
gradient.addColor(color, undefined, (checkConditions[index] - checkConditions[0]) / lastValue); gradient.addColor(color, undefined, (checkConditions[index] - checkConditions[0]) / lastValue);
}); });
//heatLegend.markers.template.applyOnClones = true;
heatLegend.markers.clear(); heatLegend.markers.clear();
heatLegend.markers.template.adapter.add("fill", function() { heatLegend.markers.template.adapter.add("fill", () => {
return gradient; return gradient;
}); });
// update cell colors // update cell colors
columnTemplate.adapter.add("fill", function(fill, column) { columnTemplate.adapter.add("fill", (fill, column) => {
let workingValue = column.dataItem.values["value"].workingValue; let workingValue = column.dataItem.values["value"].workingValue;
// use min max values calculated from data on beforedatavalidated // use min max values calculated from data on beforedatavalidated
if (am4core.type.isNumber(workingValue)) { if (am4core.type.isNumber(workingValue)) {
checkConditions.forEach((condition, index) => { checkConditions.forEach((condition, index) => {
if (index < checkConditions.length - 1) { if (index < checkConditions.length - 1) {
if (workingValue >= condition && workingValue <= checkConditions[index + 1]) { if (workingValue >= condition && workingValue <= checkConditions[index + 1]) {
//console.log(`${workingValue} entre ${condition} y ${checkConditions[index+1]}`) //console.log(`${workingValue} entre ${condition} y ${checkConditions[index+1]}`);
fill = new am4core.Color( fill = new am4core.Color(
am4core.colors.interpolate( am4core.colors.interpolate(
heatColors[index].rgb, heatColors[index].rgb,
...@@ -81,7 +78,7 @@ am4core.ready(function() { ...@@ -81,7 +78,7 @@ am4core.ready(function() {
workingValue workingValue
) )
); );
//console.log(workingValue, intervals.ocupadosDesde.colors[index]) //console.log(workingValue, intervals.ocupadosDesde.colors[index]);
} else if (workingValue < checkConditions[0]) { } else if (workingValue < checkConditions[0]) {
fill = new am4core.color(cellbgColor); fill = new am4core.color(cellbgColor);
} }
...@@ -92,8 +89,8 @@ am4core.ready(function() { ...@@ -92,8 +89,8 @@ am4core.ready(function() {
}); });
}); });
var xAxis = chart.xAxes.push(new am4charts.CategoryAxis()); let xAxis = chart.xAxes.push(new am4charts.CategoryAxis()),
var yAxis = chart.yAxes.push(new am4charts.CategoryAxis()); yAxis = chart.yAxes.push(new am4charts.CategoryAxis());
xAxis.dataFields.category = "xVar"; xAxis.dataFields.category = "xVar";
yAxis.dataFields.category = "yVar"; yAxis.dataFields.category = "yVar";
...@@ -101,13 +98,6 @@ am4core.ready(function() { ...@@ -101,13 +98,6 @@ am4core.ready(function() {
xAxis.renderer.grid.template.disabled = true; xAxis.renderer.grid.template.disabled = true;
xAxis.renderer.minGridDistance = 10; xAxis.renderer.minGridDistance = 10;
xAxis.renderer.opposite = true; xAxis.renderer.opposite = true;
//xAxis.renderer.labels.template.rotation = -45;
/*xAxis.renderer.labels.template.adapter.add("dy", function(dy, target) {
if (target.dataItem && target.dataItem.index & 2 == 2) {
return dy - 15;
}
return dy;
});*/
xAxis.title.text = "[bold]Origen[/]"; xAxis.title.text = "[bold]Origen[/]";
xAxis.title.fontSize = 15 xAxis.title.fontSize = 15
xAxis.title.paddingBottom = -10; xAxis.title.paddingBottom = -10;
...@@ -116,7 +106,7 @@ am4core.ready(function() { ...@@ -116,7 +106,7 @@ am4core.ready(function() {
// on axis size change, resize labels // on axis size change, resize labels
//FIXME: 80% hack should be better //FIXME: 80% hack should be better
xAxis.events.on("sizechanged", function(ev) { xAxis.events.on("sizechanged", ev => {
let axis = ev.target; let axis = ev.target;
let cellWidth = axis.pixelWidth / (axis.endIndex - axis.startIndex); let cellWidth = axis.pixelWidth / (axis.endIndex - axis.startIndex);
axis.renderer.labels.template.maxWidth = 2 * Math.ceil(cellWidth) * 0.8; axis.renderer.labels.template.maxWidth = 2 * Math.ceil(cellWidth) * 0.8;
...@@ -124,7 +114,7 @@ am4core.ready(function() { ...@@ -124,7 +114,7 @@ am4core.ready(function() {
// on data change change, resize labels // on data change change, resize labels
//FIXME: 80% hack should be better //FIXME: 80% hack should be better
xAxis.events.on("datarangechanged", function(ev) { xAxis.events.on("datarangechanged", ev => {
let axis = ev.target; let axis = ev.target;
let cellWidth = axis.pixelWidth / (axis.endIndex - axis.startIndex); let cellWidth = axis.pixelWidth / (axis.endIndex - axis.startIndex);
axis.renderer.labels.template.maxWidth = 2 * Math.ceil(cellWidth) * 0.8; axis.renderer.labels.template.maxWidth = 2 * Math.ceil(cellWidth) * 0.8;
...@@ -148,7 +138,7 @@ am4core.ready(function() { ...@@ -148,7 +138,7 @@ am4core.ready(function() {
yAxis.title.fill = am4core.color(mainTextColor); yAxis.title.fill = am4core.color(mainTextColor);
yAxis.renderer.labels.template.fill = am4core.color(mainTextColor); yAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
var series = chart.series.push(new am4charts.ColumnSeries()); let series = chart.series.push(new am4charts.ColumnSeries());
series.dataFields.categoryX = "xVar"; series.dataFields.categoryX = "xVar";
series.dataFields.categoryY = "yVar"; series.dataFields.categoryY = "yVar";
series.dataFields.value = "flowCount"; series.dataFields.value = "flowCount";
...@@ -167,22 +157,21 @@ am4core.ready(function() { ...@@ -167,22 +157,21 @@ am4core.ready(function() {
chart.cursor.lineY.fill = am4core.color(mainTextColor); chart.cursor.lineY.fill = am4core.color(mainTextColor);
chart.cursor.lineY.fillOpacity = 0.05; chart.cursor.lineY.fillOpacity = 0.05;
var bgColor = new am4core.InterfaceColorSet().getFor("background"); let bgColor = new am4core.InterfaceColorSet().getFor("background");
var columnTemplate = series.columns.template; let columnTemplate = series.columns.template;
columnTemplate.applyOnClones = true; columnTemplate.applyOnClones = true;
columnTemplate.strokeWidth = 2; columnTemplate.strokeWidth = 2;
columnTemplate.strokeOpacity = 0; columnTemplate.strokeOpacity = 0;
columnTemplate.stroke = bgColor; columnTemplate.stroke = bgColor;
//columnTemplate.tooltipText = "{xVar} -> {yVar}: {value.workingValue.formatNumber('#.')}"; columnTemplate.tooltipHTML = `<div class="amcharttooltip">{xVar} <i class="fas fa-long-arrow-alt-right"></i> {yVar}: {value.workingValue.formatNumber("#,###")}</div>`;
columnTemplate.tooltipHTML = `<div class="amcharttooltip">{xVar} <i class="fas fa-long-arrow-alt-right"></i> {yVar}: {value.workingValue.formatNumber('#,###')}</div>`;
columnTemplate.width = am4core.percent(100); columnTemplate.width = am4core.percent(100);
columnTemplate.height = am4core.percent(100); columnTemplate.height = am4core.percent(100);
columnTemplate.column.cornerRadius(4, 4, 4, 4); columnTemplate.column.cornerRadius(4, 4, 4, 4);
columnTemplate.column.padding(0.5, 0.5, 0.5, 0.5); columnTemplate.column.padding(0.5, 0.5, 0.5, 0.5);
columnTemplate.adapter.add("strokeWidth", function(width, column) { columnTemplate.adapter.add("strokeWidth", (width, column) => {
var workingValue = column.dataItem.values["value"].workingValue; let workingValue = column.dataItem.values["value"].workingValue;
if (am4core.type.isNumber(workingValue)) { if (am4core.type.isNumber(workingValue)) {
width = workingValue != 0 ? 1 : 0; width = workingValue != 0 ? 1 : 0;
} }
...@@ -190,13 +179,10 @@ am4core.ready(function() { ...@@ -190,13 +179,10 @@ am4core.ready(function() {
}); });
// heat legend // heat legend
//var heatLegend = chart.createChild(am4charts.HeatLegend); //let heatLegend = chart.createChild(am4charts.HeatLegend);
var heatLegend = chart.bottomAxesContainer.createChild(am4charts.HeatLegend); let heatLegend = chart.bottomAxesContainer.createChild(am4charts.HeatLegend);
heatLegend.marginTop = 5; heatLegend.marginTop = 5;
//heatLegend.marginBotom = 50;
heatLegend.width = am4core.percent(100); heatLegend.width = am4core.percent(100);
//heatLegend.align = "right";
//heatLegend.markerContainer.height = 10;
heatLegend.markerContainer.minHeight = 20; heatLegend.markerContainer.minHeight = 20;
heatLegend.markers.template.minHeight = 20; heatLegend.markers.template.minHeight = 20;
heatLegend.series = series; heatLegend.series = series;
...@@ -209,20 +195,13 @@ am4core.ready(function() { ...@@ -209,20 +195,13 @@ am4core.ready(function() {
// heatLegend min, max, colors and fill are modified above using adapters // heatLegend min, max, colors and fill are modified above using adapters
// when chart changes size, what happens with heatLegend fill // when chart changes size, what happens with heatLegend fill
heatLegend.markers.template.events.on("sizechanged", function(event) { heatLegend.markers.template.events.on("sizechanged", event => {
event.target.fill = event.target.fill; event.target.fill = event.target.fill;
}); });
// heat legend behavior // heat legend behavior
series.columns.template.events.on("over", function(event) {
handleHover(event.target);
})
series.columns.template.events.on("hit", function(event) { const handleHover = column => {
handleHover(event.target);
})
function handleHover(column) {
if (!isNaN(column.dataItem.value)) { if (!isNaN(column.dataItem.value)) {
column.strokeWidth = 2; column.strokeWidth = 2;
column.strokeOpacity = 0.2; column.strokeOpacity = 0.2;
...@@ -234,84 +213,78 @@ am4core.ready(function() { ...@@ -234,84 +213,78 @@ am4core.ready(function() {
} }
} }
series.columns.template.events.on("out", function(event) { series.columns.template.events.on("over", event => {
handleHover(event.target);
});
series.columns.template.events.on("hit", event => {
handleHover(event.target);
});
series.columns.template.events.on("out", event => {
event.target.strokeWidth = 0; event.target.strokeWidth = 0;
event.target.strokeOpacity = 0; event.target.strokeOpacity = 0;
heatLegend.valueAxis.hideTooltip(); heatLegend.valueAxis.hideTooltip();
}) });
//chart.dataSource.url = "data/odm.json";
//chart.dataSource.url = "data/viajes_ocupados_desde.geojson";
chart.responsive.enabled = true; chart.responsive.enabled = true;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++CC
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end
var cd_chart = am4core.create("bottomLeftChart", am4charts.ChordDiagram); // chord diagram
let cd_chart = am4core.create("bottomLeftChart", am4charts.ChordDiagram);
let cd_title = cd_chart.titles.create();
var cd_title = cd_chart.titles.create();
//cd_title.text = "Viajes de ocupados desde centros de mercado";
cd_title.fill = am4core.color(mainTextColor); cd_title.fill = am4core.color(mainTextColor);
cd_title.fontSize = 13; cd_title.fontSize = 13;
cd_title.align = "left"; cd_title.align = "left";
cd_title.marginBottom = 20; cd_title.marginBottom = 20;
cd_title.paddingLeft = 10; cd_title.paddingLeft = 10;
cd_chart.events.on("beforedatavalidated", function(ev) { cd_chart.events.on("beforedatavalidated", () => {
//let option = $("#indicatorSelect").val();
let optionTitle = $("#indicatorSelect option:selected").text(); let optionTitle = $("#indicatorSelect option:selected").text();
cd_title.text = "[bold]Conectividad origen - destino entre \n" + optionTitle.toLowerCase(); cd_title.text = "[bold]Conectividad origen - destino entre \n" + optionTitle.toLowerCase();
//var data = ev.target.data;
//let data = data.filter(function(e) { return e.flowCount > 0 });
//console.log(data);
}); });
cd_chart.dataFields.fromName = "xVar"; cd_chart.dataFields.fromName = "xVar";
cd_chart.dataFields.toName = "yVar"; cd_chart.dataFields.toName = "yVar";
cd_chart.dataFields.value = "flowCount"; cd_chart.dataFields.value = "flowCount";
//cd_chart.labels.fontSize = 15;
// make nodes draggable // make nodes draggable
var nodeTemplate = cd_chart.nodes.template; let nodeTemplate = cd_chart.nodes.template;
nodeTemplate.readerTitle = "Oculta/muestra para reorganizar la red"; //"Click to show/hide or drag to rearrange"; nodeTemplate.readerTitle = "Oculta/muestra para reorganizar la red"; //"Click to show/hide or drag to rearrange";
nodeTemplate.showSystemTooltip = true; nodeTemplate.showSystemTooltip = true;
var nodeLink = cd_chart.links.template; let nodeLink = cd_chart.links.template;
var bullet = nodeLink.bullets.push(new am4charts.CircleBullet()); let bullet = nodeLink.bullets.push(new am4charts.CircleBullet());
bullet.fillOpacity = 0.8; bullet.fillOpacity = 0.8;
bullet.circle.radius = 3; bullet.circle.radius = 3;
bullet.locationX = 0.5; bullet.locationX = 0.5;
// create animations // create animations
//cd_chart.events.once("over", function()
nodeTemplate.events.on("ready", function() {
for (var i = 0; i < cd_chart.links.length; i++) {
var link = cd_chart.links.getIndex(i);
var bullet = link.bullets.getIndex(0);
animateBullet(bullet); const animateBullet = (bullet) => {
let duration = cd_chart.links.length * Math.random() + 3000;
let animation = bullet.animate([{ property: "locationX", from: 0, to: 1.05 }], duration);
animation.events.on("animationended", event => {
animateBullet(event.target.object);
});
} }
})
nodeTemplate.events.on("ready", () => {
function animateBullet(bullet) { for (let i = 0; i < cd_chart.links.length; i++) {
var duration = cd_chart.links.length * Math.random() + 3000; let link = cd_chart.links.getIndex(i);
var animation = bullet.animate([{ property: "locationX", from: 0, to: 1.05 }], duration) let bullet = link.bullets.getIndex(0);
animation.events.on("animationended", function(event) {
animateBullet(event.target.object) animateBullet(bullet);
})
} }
});
var label = nodeTemplate.label; let label = nodeTemplate.label;
label.relativeRotation = 90; label.relativeRotation = 90;
label.fontSize = 10; label.fontSize = 10;
label.fill = am4core.color(mainTextColor); label.fill = am4core.color(mainTextColor);
//label.wrap = true;
//label.bent = true;
cd_chart.responsive.enabled = true; cd_chart.responsive.enabled = true;
......
...@@ -5,32 +5,19 @@ ...@@ -5,32 +5,19 @@
* August 2019 - June 2020 * August 2019 - June 2020
*/ */
/* globals omnivore, Promise, chroma, makeBaseMap, makeIndicatorGraph, getData, getDataInSelection */ /* globals Promise, makeBaseMap */
/* exported indicators. userFiles, userDates, timeParse, layerControl, updateCharts, intervals */ /* exported indicators. timeParse, layerControl, intervals */
let timeParse, let timeParse,
timeFormat, timeFormat,
timeDimensionControl, timeDimensionControl,
userFiles = [],
monthArray = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
dateArray = [],
dateMin,
dateMax,
minUserDate,
maxUserDate,
userDates,
map, map,
overlay, overlay,
glmap, glmap,
osmLayer, cartoLightLayer, cartoDarkLayer, osmLayer, cartoLightLayer, cartoDarkLayer,
timeLayer, layerControl;
layerControl,
scale;
// define empty objects and indicators // define empty objects and indicators
let maxIndicators = {},
minIndicators = {},
//indicators = ["area", "perimeter", "costa", "df"],
indicators = ["ocupadosDesde", "ocupadosHacia", "ocupadosEntre", "poicDesde", "poicHacia", "poicEntre"], indicators = ["ocupadosDesde", "ocupadosHacia", "ocupadosEntre", "poicDesde", "poicHacia", "poicEntre"],
indicatorsNames = ["Viajes de ocupados desde centros de mercado", "Viajes de ocupados hacia centros de mercado", indicatorsNames = ["Viajes de ocupados desde centros de mercado", "Viajes de ocupados hacia centros de mercado",
"Viajes de ocupados entre zonas", "Viajes de personas en OIC desde centros de mercado", "Viajes de ocupados entre zonas", "Viajes de personas en OIC desde centros de mercado",
...@@ -40,20 +27,11 @@ let maxIndicators = {}, ...@@ -40,20 +27,11 @@ let maxIndicators = {},
"Ocupados entre zonas", "OIC desde centros <br/> de mercado", "Ocupados entre zonas", "OIC desde centros <br/> de mercado",
"OIC hacia centros <br/> de mercado", "OIC entre zonas" "OIC hacia centros <br/> de mercado", "OIC entre zonas"
], ],
//indicatorsUnits = ["m\u00B2", "m", "", ""], indicatorVars = {};
indicatorsxAxisFormat = [".2s", ".2s", ".2f", ".2f"],
indicatorVars = {},
cols = [];
// Add options to combo box, and set their chart variables // Add options to combo box, and set their chart variables
// chart containers must already exist in index.php // chart containers must already exist in index.php
indicators.forEach((indicator, index) => { indicators.forEach((indicator, index) => {
// colnames for queries
cols.push(`min(${indicator}) as min${indicator}`);
cols.push(`max(${indicator}) as max${indicator}`);
// initialize min and max objects to hold values for each indicator and add select options
maxIndicators[indicator] = 0;
minIndicators[indicator] = 1e30;
$("#indicatorSelect").append(`<option value="${indicator}"> ${indicatorsNames[index]}</option>`); $("#indicatorSelect").append(`<option value="${indicator}"> ${indicatorsNames[index]}</option>`);
// chart variables // chart variables
indicatorVars[indicator] = { indicatorVars[indicator] = {
...@@ -108,30 +86,6 @@ let intervals = { ...@@ -108,30 +86,6 @@ let intervals = {
} }
} }
/*
indicatorVars.area.explanation = "Muestra la suma del &aacute;rea contenida en los pol&iacute;gonos dentro de la selecci&oacute;n o en toda la regi&oacute;n de estudio.";
indicatorVars.perimeter.explanation = "Muestra la suma del per&iacute;metro de los pol&iacute;gonos dentro de la selecci&oacute;n o en toda la regi&oacute;n de estudio.";
indicatorVars.costa.explanation = "Relaciona el per&iacute;metro de un cuerpo de agua o longitud de l&iacute;nea de costa con el per&iacute;metro de un c&iacute;rculo de igual \
&aacute;rea (A) que el cuerpo. El valor m&iacute;nimo es 1, el cual corresponde a un c&iacute;rculo perfecto, mientras que el valor m&aacute;ximo no tiene l&iacute;mite. \
En varios estudios se han obtenido valores mayores de 20, como en algunos lagos en Finlandia. Los valores cercanos a 1 son indicativos de formas circulares, mientras que \
los valores mayores de 3 son referencia de cuerpos de agua con contornos de formas alargadas. \
<br/><br/> \
Se calcula como \
<p class=\"equation\">DI = <span class=\"frac\"><sup>P</sup><span>&frasl;</span><sub>2&radic;<span style=\"text-decoration: overline;\">&pi; A</span></sub></span>,</p> \
donde P es el per&iacute;metro y A es el &aacute;rea.";
indicatorVars.df.explanation = "La geometr&iacute;a fractal se usa para hacer referencia a objetos demasiado irregulares y que tienen la propiedad de ser invariantes ante \
cambios de escala. En el caso de la hidrolog&iacute;a, este &iacute;ndice nos refiere la sinuosidad del contorno de un cuerpo de agua. La dimensi&oacute;n presenta valores \
reales no negativos entre 1 y 2. Los valores de este &iacute;ndice aumentan conforme el contorno del cuerpo de agua es más sinuoso. El an&aacute;lisis fractal se ha utilizado \
con &eacute;xito para medir y caracterizar rasgos lineales irregulares como las costas. \
<br/></br> \
Se calcula como \
<p class=\"equation\">DF = <span class=\"frac\"><sup>2 ln(P/4)</sup><span>&frasl;</span><sub>ln(A)</sub></span>,</p> \
donde P es el per&iacute;metro y A es el &aacute;rea.";
*/
let currentTiles = {},
allTiles = {};
d3.json("https://unpkg.com/d3-time-format@2.1.1/locale/es-MX.json").then(locale => { d3.json("https://unpkg.com/d3-time-format@2.1.1/locale/es-MX.json").then(locale => {
d3.timeFormatDefaultLocale(locale); d3.timeFormatDefaultLocale(locale);
...@@ -139,27 +93,16 @@ d3.json("https://unpkg.com/d3-time-format@2.1.1/locale/es-MX.json").then(locale ...@@ -139,27 +93,16 @@ d3.json("https://unpkg.com/d3-time-format@2.1.1/locale/es-MX.json").then(locale
timeParse = d3.timeParse("%B_%Y"); timeParse = d3.timeParse("%B_%Y");
timeFormat = d3.timeFormat("%B_%Y"); timeFormat = d3.timeFormat("%B_%Y");
//setupTimeDimensionControl();
// FIX: Need to remove setup and populate dates and only setup and populate map
/*setupDates()
.then(dates => populateDates(dates))
.then(userData => setupMap(userData))
.then(map => populateMap(map));*/
//$("#showMap").on("click", () => {
// hide initial screen and show map
// TODO: don't need outer call to d3.json, do I? Move this to the bottom after functions definitions // TODO: don't need outer call to d3.json, do I? Move this to the bottom after functions definitions
//TODO: remove unused functions // TODO: remove unused functions
$("#startHeader").remove(); $("#startHeader").remove();
$("#initial-backdrop").remove(); $("#initial-backdrop").remove();
$("#regionSelect").remove(); $("#regionSelect").remove();
$("#mainContainer")[0].style.setProperty("display", "flex", "important") $("#mainContainer")[0].style.setProperty("display", "flex", "important");
$("#mexmap").show(); $("#mexmap").show();
setupMap() setupMap()
.then(map => populateMap(map)); .then(map => populateMap(map));
//});
}); });
const sortInitialDateAscending = (a, b) => { const sortInitialDateAscending = (a, b) => {
...@@ -167,128 +110,6 @@ const sortInitialDateAscending = (a, b) => { ...@@ -167,128 +110,6 @@ const sortInitialDateAscending = (a, b) => {
return a - b; return a - b;
} }
const baseUrl = new URL(window.location.href).origin; // returns "http://localhost:8090"
// use `${baseUrl}/something`
// query available dates on DB
const setupDates = () => {
return new Promise(resolve => {
let layersQuery = `${baseUrl}/list_layers`;
d3.json(layersQuery).then(layers => {
layers.forEach(layer => {
dateArray.push(timeParse(layer.f_table_name)); // convert filenames to dates
})
dateArray = dateArray.sort(sortInitialDateAscending); // order dates
dateMin = d3.min(dateArray);
dateMax = d3.max(dateArray);
//userFiles = dateArray.map( month => timeFormat(month)); // order table names by date
const dates = { min: dateMin, max: dateMax, dates: dateArray };
resolve(dates);
});
});
}
const populateDates = (dates) => { // fill out date pickers with available dates
return new Promise(resolve => {
$.datepicker.regional["es"] = {
closeText: "Cerrar",
prevText: "&#x3c;Ant",
nextText: "Sig&#x3e;",
currentText: "Hoy",
monthNames: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
"Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"
],
monthNamesShort: ["Ene", "Feb", "Mar", "Abr", "May", "Jun",
"Jul", "Ago", "Sep", "Oct", "Nov", "Dic"
],
dayNames: ["Domingo", "Lunes", "Martes", "Mi&eacute;rcoles", "Jueves", "Viernes", "S&aacute;bado"],
dayNamesShort: ["Dom", "Lun", "Mar", "Mi&eacute;", "Juv", "Vie", "S&aacute;b"],
dayNamesMin: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "S&aacute;"],
weekHeader: "Sm",
dateFormat: "yy/mm/dd",
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ""
}
$.datepicker.setDefaults($.datepicker.regional["es"]);
// month pickers
$("#date-initial").datepicker({
minDate: dates.min,
maxDate: dates.max,
defaultDate: dates.min,
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: "M yy",
onClose: function() {
let month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
let year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
minUserDate = new Date(year, month, 1); // initial date
$(this).datepicker("setDate", minUserDate);
$("#date-final").datepicker("option", {
"minDate": minUserDate,
disabled: false
});
// hack to avoid needing to change date twice in second datepicker
setTimeout(() => { $("#date-final").datepicker("show") }, 10);
},
beforeShow: el => {
$("#ui-datepicker-div").toggleClass("hide-calendar", $(el).is("[data-calendar=\"false\"]"));
}
});
$("#date-final").datepicker({
maxDate: dates.max,
defaultDate: dates.max,
changeMonth: true,
changeYear: true,
showButtonPanel: true,
disabled: true,
dateFormat: "M yy",
onClose: function() {
let month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
let year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
maxUserDate = new Date(year, month, 1); // final date
$(this).datepicker("setDate", maxUserDate);
// use .setUTCHours(6,0,0) to adjust DST offset fror some months
let startUserDate = new Date(minUserDate.setUTCHours(6, 0, 0));
let endUserDate = new Date(maxUserDate.setUTCHours(6, 0, 0));
// pass new timeinterval to timeDimension player
userDates = L.TimeDimension.Util.explodeTimeRange(startUserDate, endUserDate, "P1M");
userFiles = userDates.map(month => timeFormat(month)); // order table names by date
// change date selectors from main screen to map
$("#date-initial").detach().appendTo("#datePickers");
$("#date-final").detach().appendTo("#datePickers");
$("#datePickers").css("display", "block");
// hide initial screen and show map
$("#startHeader").remove();
$("#initial-backdrop").remove();
$("#mainContainer")[0].style.setProperty("display", "flex", "important")
$("#mexmap").show();
// When closing final-date, either setup or update map
if (!map) {
resolve({ min: startUserDate, max: endUserDate });
} else {
// FIXME: no need to pass data here?
updateMap({ map: map, min: startUserDate, max: endUserDate });
}
},
beforeShow: (el, inst) => {
inst.input.datepicker("refresh");
$("#ui-datepicker-div").toggleClass("hide-calendar", $(el).is("[data-calendar=\"false\"]"));
}
});
})
}
const setupMap = () => { //(dates) => { const setupMap = () => { //(dates) => {
return new Promise(resolve => { return new Promise(resolve => {
...@@ -317,11 +138,6 @@ const setupMap = () => { //(dates) => { ...@@ -317,11 +138,6 @@ const setupMap = () => { //(dates) => {
minZoom: 8, minZoom: 8,
zoom: 6, zoom: 6,
attributionControl: false, attributionControl: false,
/*timeDimension: true,
timeDimensionOptions: {
times: userDates,
currentTime: dates.min
},*/
maxBounds: bounds maxBounds: bounds
}).setView([21.15, -100.94], 8); }).setView([21.15, -100.94], 8);
...@@ -367,9 +183,9 @@ const setupMap = () => { //(dates) => { ...@@ -367,9 +183,9 @@ const setupMap = () => { //(dates) => {
}); });
const offsetGlobal = (center, zoom, refMap, tgtMap) => { const offsetGlobal = (center, zoom, refMap, tgtMap) => {
var refC = refMap.getContainer(); let refC = refMap.getContainer();
var tgtC = tgtMap.getContainer(); let tgtC = tgtMap.getContainer();
var pt = refMap.project(center, zoom) let pt = refMap.project(center, zoom)
.subtract([refC.offsetLeft, refC.offsetTop]) .subtract([refC.offsetLeft, refC.offsetTop])
.subtract(refMap.getSize().divideBy(2)) .subtract(refMap.getSize().divideBy(2))
.add([tgtC.offsetLeft, tgtC.offsetTop]) .add([tgtC.offsetLeft, tgtC.offsetTop])
...@@ -379,39 +195,7 @@ const setupMap = () => { //(dates) => { ...@@ -379,39 +195,7 @@ const setupMap = () => { //(dates) => {
map.sync(overlay, { offsetFn: offsetGlobal }); map.sync(overlay, { offsetFn: offsetGlobal });
//console.log(userFiles); resolve(map);
// query db to get min/max values per month and indicator and store them in an object
// FIX: comment out to avoid DB calls
/*queryFiles().then(minmax => {
minmax.map(minmaxMonth => {
indicators.forEach((indicator) => {
minIndicators[indicator] = Math.min(minIndicators[indicator], minmaxMonth[`min${indicator}`]);
maxIndicators[indicator] = Math.max(maxIndicators[indicator], minmaxMonth[`max${indicator}`]);
});
});
resolve({ "map": map, "minIndicators": minIndicators, "maxIndicators": maxIndicators });
});*/
// FIX: resolve with fake values
resolve({ "map": map, "minIndicators": minIndicators, "maxIndicators": maxIndicators });
});
}
const flatten = arrays => {
return [].concat(arrays);
}
const queryFiles = () => {
return Promise.all(userFiles.map(getMinMax))
// the result is an array of arrays, so we'll flatten them here
.then(flatten);
}
const getMinMax = table => {
return new Promise(resolve => {
let minmaxQuery = `${baseUrl}/query/${table}?columns=${cols.join(", ")}`;
d3.json(minmaxQuery).then(minmax => {
resolve(minmax[0]);
});
}); });
} }
...@@ -450,67 +234,11 @@ const odClick = (e) => { ...@@ -450,67 +234,11 @@ const odClick = (e) => {
// TODO: trigger chart update to only draw selected origins and destinations? // TODO: trigger chart update to only draw selected origins and destinations?
} }
const populateMap = async(mapData) => { const populateMap = async (map) => {
// FIX: comment out to avoid DB calls
//const chartData = await getData();
// fake null data to avoid DB requests
chartData = [];
indicators.map(indicator => {
chartData[indicator] = [];
chartData[indicator].push({ name: `${indicator}0`, values: [{ "date": new Date("2016-01-01T06:00:00.000Z"), "value": 0 }] });
})
// Define charts with reusable components
/*indicators.map(async(indicator, index) => {
// indicatorVars[indicator].chart gives areaChart, perimeterChart, etc.
// First, make all charts with same general options
indicatorVars[indicator].chart = makeIndicatorGraph()
.width(Math.floor($(indicatorVars[indicator].container)[0].offsetParent.offsetWidth * 0.95))
.height(Math.floor($(indicatorVars[indicator].container)[0].offsetParent.offsetHeight * 0.95))
.lineVariables([`${indicator}0`]) // d.area is used to draw stuff on y axis
.displayName("date") // d.date is used to draw stuff on x axis
.lineAxisLabel("(m)")
.id(indicator)
.xAxisFormat(d3.timeFormat("%b '%y")) // label x axis as mm 'yy
.yAxisFormat(d3.format(indicatorsxAxisFormat[index])) // yAxis label in SI or other
// Then, specify some parameters for each chart
.tooltipUnits(indicatorsUnits[index])
.tooltipFormat(d3.format(indicatorsxAxisFormat[index])) // tooltip format in SI or other
.title(indicatorsUnits[index] == "" ? indicatorsNames[index] :
`${indicatorsNames[index]} (${indicatorsUnits[index]})`);
// Finally, set chart data with async function calling stuff from DB
indicatorVars[indicator].chart.data(chartData[indicator]);
// create chart with passed options
d3.select(indicatorVars[indicator].container)
.call(indicatorVars[indicator].chart);
// Reload chart data and force chart update
indicatorVars[indicator].chartData = indicatorVars[indicator].chart.data(); // get chart data
indicatorVars[indicator].chart.data(indicatorVars[indicator].chartData); // set chart data
// Highlight plot title according to selected option
let option = $("#indicatorSelect").val(); // option selected from dropdrown
d3.select(indicatorVars[option].container).select("svg text.title").classed("active", true);
});*/
let map = mapData.map,
minIndicators = mapData.minIndicators,
maxIndicators = mapData.maxIndicators;
//map.createPane("wb-Tiles");
//map.getPane("wb-Tiles").style.zIndex = 450;
// FIX: comment out to avoid DB calls
// create mvt layers
/*userFiles.forEach(f => {
f = mapboxLayer(f);
});*/
glmap = L.mapboxGL({ glmap = L.mapboxGL({
accessToken: "no-token", "accessToken": "no-token",
style: { "style": {
"version": 8, "version": 8,
"sources": {}, "sources": {},
"layers": [] "layers": []
...@@ -519,46 +247,15 @@ const populateMap = async(mapData) => { ...@@ -519,46 +247,15 @@ const populateMap = async(mapData) => {
// after mapboxGL map is ready with styles do this: // after mapboxGL map is ready with styles do this:
glmap.getMapboxMap().on("style.load", () => { glmap.getMapboxMap().on("style.load", () => {
// FIX: comment out to avoid DB calls
/*userFiles.forEach(monthYear => {
glmap.getMapboxMap().addLayer(currentTiles[monthYear]);
});
Object.keys(allTiles).forEach(layer => {
if (layer == userFiles[0]) {
glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0.7)
}
});*/
/*timeDimensionControl.addTo(map);
// Pass dummy geojson layer to timeDimension in order to register and sync
timeLayer = L.timeDimension.layer.Tile(L.geoJSON(), {
updateTimeDimension: true,
updateTimeDimensionMode: "replace",
waitForReady: true,
duration: "P1M"
});
timeLayer.addTo(map);*/
// FIX: comment out to avoid DB calls
// style currentTiles
/*let option = $("#indicatorSelect").val(); // option selected from dropdrown
styleTiles(option, minIndicators, maxIndicators)
.then(legend.addTo(map)); // add legend control -> it updates
*/
let baseLayers = { let baseLayers = {
"Carto Dark": cartoDarkLayer, "Carto Dark": cartoDarkLayer,
"Carto Light": cartoLightLayer, "Carto Light": cartoLightLayer,
"OpenStreetMap": osmLayer "OpenStreetMap": osmLayer
}; };
var overlays = {
// "<span id=\"cuencaOverlay\">Agua en la cuenca del Grijalva</span>": timeLayer
};
layerControl = L.control.layers(baseLayers, overlays).addTo(map); layerControl = L.control.layers(baseLayers).addTo(map);
makeBaseMap() // basemap.js makeBaseMap() // basemap.js
//.then( flowLayers => { });
legend.addTo(map); legend.addTo(map);
// fix for leaflet-mapbox-gl v. 0.0.11 that adds map's to tile pane: // fix for leaflet-mapbox-gl v. 0.0.11 that adds map's to tile pane:
...@@ -570,247 +267,14 @@ const populateMap = async(mapData) => { ...@@ -570,247 +267,14 @@ const populateMap = async(mapData) => {
}); });
} }
const updateMap = (mapData) => {
//console.log(userFiles);
// FIX: comment out to avoid DB calls
// clear tiles
/* currentTiles = {};
//retrieve or create tiles for current dates
userFiles.forEach(monthYear => {
if (Object.keys(allTiles).includes(monthYear)) {
currentTiles[monthYear] = allTiles[monthYear]; // recover tile if it has already been created
//currentJSONs[monthYear] = allJSONs[monthYear]; // recover json if it has already been created
return; // if file has already been processed, exit
} else { // if file cannot be found in allTiles, then add 1 to the number of files to process
let newTile = mapboxLayer(monthYear);
glmap.getMapboxMap().addLayer(newTile);
if (monthYear == userFiles[0]) {
glmap.getMapboxMap().setPaintProperty(monthYear, "fill-opacity", 0.7)
}
}
});
// update timeDimension times
timeLayer._timeDimension.setAvailableTimes(userDates, "replace");
timeLayer._timeDimension.setCurrentTime(mapData.min);
// clear minmax indicators objects
maxIndicators = {},
minIndicators = {};
indicators.forEach((indicator) => {
maxIndicators[indicator] = 0;
minIndicators[indicator] = 1e30;
});
// query db for new minmax values then style tiles
new Promise(resolve => {
queryFiles().then(minmax => {
minmax.map(minmaxMonth => {
indicators.forEach((indicator) => {
minIndicators[indicator] = Math.min(minIndicators[indicator], minmaxMonth[`min${indicator}`]);
maxIndicators[indicator] = Math.max(maxIndicators[indicator], minmaxMonth[`max${indicator}`]);
});
});
resolve({ "map": map, "minIndicators": minIndicators, "maxIndicators": maxIndicators });
})
}).then(values => { // once we have new minmax values, style all tiles
let option = $("#indicatorSelect").val(), // option selected from dropdrown
min = values.minIndicators,
max = values.maxIndicators;
styleTiles(option, min, max)
.then(legend.addTo(map)); // add legend control -> it updates
});
// Update charts
updateCharts();
*/
}
const updateCharts = async() => {
$(".loader").css("display", "block");
// TODO: add mask while fetching async data
// if user has drawn polygons, update chart with data inside selection
if (drawnItems.toGeoJSON().features.length != 0) {
let allData = await getDataInSelection();
indicators.map(async indicator => {
indicatorVars[indicator].chart.data(summarizeData(allData, indicator));
// indicatorVars[indicator].cd_chart.data(summarizeData(allData, indicator));
});
} else {
// otherwise use all data
let allData = await getData();
indicators.map(async indicator => {
indicatorVars[indicator].chart.data(allData[indicator]);
// indicatorVars[indicator].cd_chart.data(allData[indicator]);
});
}
$(".loader").hide("fade", 750);
}
// define MVT layer for given month table and all indicators
const mapboxLayer = (monthYear) => {
let pbfLayer = {
id: monthYear,
source: {
type: "vector",
tiles: [`${baseUrl}/${monthYear}/mvt/{z}/{x}/{y}?geom_column=geom&columns=${indicators.join()}`],
maxzoom: 19,
minzoom: 6
},
"source-layer": monthYear,
type: "fill",
"paint": {
"fill-opacity": 0,
/*"fill-color": [
"interpolate",
["linear"],
["get", "df"],
1, "rgba(255, 0, 0, 0.5)", // red
1.3, "rgba(0, 255, 0, 0.5)", // green
]/*,
"fill-outline-color": [
"interpolate",
["linear"],
["get", "df"],
1, "rgba(255, 0, 0, 0.6)", // red
1.3, "rgba(0, 255, 0, 0.6)", // green
]*/
}
}
currentTiles[monthYear] = pbfLayer;
allTiles[monthYear] = pbfLayer;
return pbfLayer;
}
const setupTimeDimensionControl = () => {
L.Control.TimeDimensionCustom = L.Control.TimeDimension.extend({
_getDisplayDateFormat: date => {
let d = new Date(date);
let year = d.getFullYear().toString();
let month = d.getUTCMonth();
return `${monthArray[month]} ${year}`;
}
});
timeDimensionControl = new L.Control.TimeDimensionCustom({
loopButton: true,
/*minSpeed: 1,
maxSpeed: 5,*/
timeSteps: 1,
playReverseButton: true,
//limitSliders: true,
playerOptions: {
//buffer: 5,
//minBufferReady: 5,
transitionTime: 125,
loop: true
},
timeZones: ["Local"]
});
}
L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({
_setAvailableTimes: function() {
if (this.options.times) {
return L.TimeDimension.Util.parseTimesExpression(this.options.times);
} else if (this.options.timeInterval) {
let tiArray = L.TimeDimension.Util.parseTimeInterval(this.options.timeInterval);
let period = this.options.period || "P1D";
let validTimeRange = this.options.validTimeRange || undefined;
//alert("times");
return L.TimeDimension.Util.explodeTimeRange(tiArray[0], tiArray[1], period, validTimeRange);
} else {
return [];
}
},
onAdd: function(map) {
// Don't call prototype so this_update() does not get called twice
//L.TimeDimension.Layer.prototype.onAdd.call(this, map);
this._map = map;
if (!this._timeDimension && map.timeDimension) {
this._timeDimension = map.timeDimension;
}
this._timeDimension.on("timeloading", this._onNewTimeLoading, this);
this._timeDimension.on("timeload", this._update, this);
this._timeDimension.registerSyncedLayer(this);
map.addLayer(this._baseLayer);
this._update();
},
onRemove: function(map) {
this._timeDimension.unregisterSyncedLayer(this);
this._timeDimension.off("timeloading", this._onNewTimeLoading, this);
this._timeDimension.off("timeload", this._update, this);
//this._baseLayer.getContainer().style.display = "none";
Object.keys(allTiles).forEach(layer => { // hide all tiles
glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0);
});
//this.eachLayer(map.removeLayer, map);
//this._map = null;
},
isReady: function(time) {
// to be implemented for each type of layer
return true;
},
_update: function() {
if (!this._baseLayer || !this._map) {
return;
}
var time = this._timeDimension.getCurrentTime();
// get data for time
let d = new Date(time),
year = d.getFullYear().toString(),
m = d.getUTCMonth(),
month = monthArray[m].toLowerCase(),
monthYear = `${month}_${year}`;
// Update title
let title = $("#title");
title.html(`<h2>Cobertura de agua en la cuenca del r&iacute;o Grijalva en ${month} de ${year}</h2>`);
// Update graphs only on timeload event
indicators.forEach(indicator => {
indicatorVars[indicator].chartData = indicatorVars[indicator].chart.data(); // get chart data
indicatorVars[indicator].chart.data(indicatorVars[indicator].chartData); // set chart data
// indicatorVars[indicator].cd_chart.data(indicatorVars[indicator].chartData); // set chart data
});
//console.time("process");
//console.log("data for", monthYear);
//console.log(currentTiles)
Object.keys(allTiles).forEach(layer => {
if (layer !== monthYear) { // hide all other months
glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0);
} else { // except current one
glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0.7);
}
});
//console.timeEnd("process");
}
});
L.timeDimension.layer.Tile = (layer, options) => {
return new L.TimeDimension.Layer.Tile(layer, options);
};
// When selecting indicator from dropdown, style tiles. // When selecting indicator from dropdown, style tiles.
$("#indicatorSelect").on("change", function() { $("#indicatorSelect").on("change", function() {
// style currentTiles
let option = this.value; // option selected from dropdrown let option = this.value; // option selected from dropdrown
flowMapsArray.forEach(layer => { flowMapsArray.forEach(layer => {
if (layer.options.customLayerId === option) { if (layer.options.customLayerId === option) {
map.addLayer(layer); map.addLayer(layer);
layer.on('click', odClick); layer.on("click", odClick);
/*layer.getLayers().forEach(l => {
console.log(l.feature.properties._isSelectedForPathDisplay)
});*/
// TODO: Recover each layer state and populate table according to that // TODO: Recover each layer state and populate table according to that
// layer._layers[i].feature.properties._isSelectedforPathDisplay // layer._layers[i].feature.properties._isSelectedforPathDisplay
...@@ -827,16 +291,14 @@ $("#indicatorSelect").on("change", function() { ...@@ -827,16 +291,14 @@ $("#indicatorSelect").on("change", function() {
}); });
// on select, update chart data // on select, update chart data
let odChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "topChart") let odChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "topChart");
odChart.data = odData[option]; odChart.data = odData[option];
let chordChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "bottomLeftChart") let chordChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "bottomLeftChart");
chordChart.data = odData[option]; chordChart.data = odData[option];
chordChart.data = chordChart.data.filter(function(e) { return e.flowCount > 0 }); chordChart.data = chordChart.data.filter( e => e.flowCount > 0 );
//console.log(amchart2.data.filter(function(e) { return e.flowCount > 0 }))
styleTiles(option, minIndicators, maxIndicators) legend.addTo(map); // add legend control -> it updates
.then(legend.addTo(map)); // add legend control -> it updates
// FIXME: re-adding control updates its contents... why? // FIXME: re-adding control updates its contents... why?
// Highlight plot title according to selected option // Highlight plot title according to selected option
indicators.forEach(indicator => { indicators.forEach(indicator => {
...@@ -844,33 +306,14 @@ $("#indicatorSelect").on("change", function() { ...@@ -844,33 +306,14 @@ $("#indicatorSelect").on("change", function() {
}); });
}); });
const styleTiles = (option, minIndicators, maxIndicators) => {
// define color scale domain based on min-max values for selected indicator
let domain = [minIndicators[option], maxIndicators[option]];
//console.log(domain)
scale = chroma.scale("PuBu").padding([0.5, 0]).domain(domain).classes(5);
Object.keys(currentTiles).forEach(layer => {
let color = [
"interpolate", ["linear"],
["get", option],
minIndicators[option], scale(minIndicators[option]).hex(),
maxIndicators[option], scale(maxIndicators[option]).hex()
];
//glmap.getMapboxMap().setPaintProperty(layer, "fill-color", color);
});
return Promise.resolve(scale);
}
let legend = L.control({ let legend = L.control({
position: "bottomright" position: "bottomright"
}); });
legend.onAdd = function() { legend.onAdd = () => {
let div = L.DomUtil.create("div", "info legend leaflet-bar"); let div = L.DomUtil.create("div", "info legend leaflet-bar");
let option = $("#indicatorSelect").val(); let option = $("#indicatorSelect").val();
let optionIndex = indicators.indexOf(option); let optionIndex = indicators.indexOf(option);
//let legendText = indicatorsUnits[optionIndex] == "" ? indicatorsNames[optionIndex] :
// `${indicatorsNames[optionIndex]} (${indicatorsUnits[optionIndex]})`;
//title //title
let title = L.DomUtil.create("h6", ""); let title = L.DomUtil.create("h6", "");
...@@ -881,37 +324,25 @@ legend.onAdd = function() { ...@@ -881,37 +324,25 @@ legend.onAdd = function() {
let list = L.DomUtil.create("ul", ""); let list = L.DomUtil.create("ul", "");
div.appendChild(list); div.appendChild(list);
//var html = `<h6>${indicatorsShortNames[optionIndex]}</h6><ul>`;
//let domain =
//scale = chroma.scale("PuBu").padding([0.5, 0]).domain(domain).classes(5);
// data
let classes = intervals[option].classes; let classes = intervals[option].classes;
//let classes = scale.classes();
/*classes.forEach((c, idx, array) => {
if (idx != array.length - 1) {
html += `<li><i style="background: ${scale(c).hex()}"></i>${d3.format(",.4~s")(classes[idx])} - ${d3.format(",.4~s")(classes[idx+1])}</li>`;
}
});*/
// create stuff for each type of flow // create stuff for each type of flow
classes.forEach((c, idx) => { classes.forEach((c, idx) => {
// create list element // create list element
let item = L.DomUtil.create('li'); let item = L.DomUtil.create("li");
// create canvas element with arc of appropriate thickness ad color // create canvas element with arc of appropriate thickness ad color
let canvas = L.DomUtil.create('canvas'); let canvas = L.DomUtil.create("canvas");
let originProp = L.DomUtil.testProp(['transformOrigin', 'WebkitTransformOrigin', 'msTransformOrigin']); let originProp = L.DomUtil.testProp(["transformOrigin", "WebkitTransformOrigin", "msTransformOrigin"]);
canvas.style[originProp] = '50% 50%'; canvas.style[originProp] = "50% 50%";
canvas.width = 18; canvas.width = 18;
canvas.height = 18; canvas.height = 18;
var ctx = canvas.getContext("2d"); let ctx = canvas.getContext("2d");
ctx.beginPath(); ctx.beginPath();
ctx.arc(18, 18, 15, 1.5 * Math.PI, Math.PI, true); ctx.arc(18, 18, 15, 1.5 * Math.PI, Math.PI, true);
ctx.lineWidth = intervals[option].thickness[idx]; ctx.lineWidth = intervals[option].thickness[idx];
ctx.lineCap = 'round'; ctx.lineCap = "round";
// line color // line color
ctx.strokeStyle = intervals[option].colors[idx];; ctx.strokeStyle = intervals[option].colors[idx];;
ctx.stroke(); ctx.stroke();
...@@ -924,7 +355,7 @@ legend.onAdd = function() { ...@@ -924,7 +355,7 @@ legend.onAdd = function() {
span.innerText = c; span.innerText = c;
// append text to list item // append text to list item
item.appendChild(span) item.appendChild(span);
// lastly, append item to list // lastly, append item to list
list.appendChild(item); list.appendChild(item);
}); });
......
...@@ -6,11 +6,9 @@ ...@@ -6,11 +6,9 @@
*/ */
/* global Promise, omnivore, JSZip, map, layerControl */ /* global Promise, omnivore, JSZip, map, layerControl */
/* exported makeBaseMap, baseLayerPromises, drawnItems */ /* exported makeBaseMap */
/* Lines related to displaying loading bar are commented */ let baseLayerPromises = [];
let baseLayerPromises = [], drawnItems;
// function to read compressed json and create a leaflet layer // function to read compressed json and create a leaflet layer
const zip2Lyr = (zipFile, layerName, layerTemplate) => { const zip2Lyr = (zipFile, layerName, layerTemplate) => {
...@@ -55,7 +53,7 @@ const createPane = (layerPane, zIndex) => { ...@@ -55,7 +53,7 @@ const createPane = (layerPane, zIndex) => {
map.getPane(layerPane).style["mix-blend-mode"] = "normal"; map.getPane(layerPane).style["mix-blend-mode"] = "normal";
} }
let descargas, presas, tuxtlaVH, zms, anps; let descargas, puentes, presas, cuencas, tuxtlaVH, zms, anps;
// *** WMS INEGI *** // *** WMS INEGI ***
// NOMBRES DE CUERPOS DE AGUA // NOMBRES DE CUERPOS DE AGUA
...@@ -97,14 +95,8 @@ let layer_limiteMunicipal= new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tun ...@@ -97,14 +95,8 @@ let layer_limiteMunicipal= new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tun
let layer_puentes = new L.geoJson(null, { let layer_puentes = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_puentes", pane: "pane_puentes",
//onEachFeature: pop_puentes,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// var context = {
// feature: feature,
// variables: {}
// };
let puenteMarker = L.BeautifyIcon.icon({ let puenteMarker = L.BeautifyIcon.icon({
// icon: "grip-lines-vertical",
icon: "puente", icon: "puente",
iconSize: [0, 0], iconSize: [0, 0],
iconAnchor: [7, 10], iconAnchor: [7, 10],
...@@ -125,12 +117,7 @@ let layer_puentes = new L.geoJson(null, { ...@@ -125,12 +117,7 @@ let layer_puentes = new L.geoJson(null, {
let layer_descargas = new L.geoJson(null, { let layer_descargas = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_descargas", pane: "pane_descargas",
//onEachFeature: pop_descargas,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let descargasMarker = L.BeautifyIcon.icon({ let descargasMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -152,12 +139,7 @@ let layer_descargas = new L.geoJson(null, { ...@@ -152,12 +139,7 @@ let layer_descargas = new L.geoJson(null, {
let layer_presas = new L.geoJson(null, { let layer_presas = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_presas", pane: "pane_presas",
//onEachFeature: pop_presas,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let presasMarker = L.BeautifyIcon.icon({ let presasMarker = L.BeautifyIcon.icon({
icon: "presa", icon: "presa",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -194,7 +176,6 @@ const style_cuencas = () => { ...@@ -194,7 +176,6 @@ const style_cuencas = () => {
let layer_cuencas = new L.geoJson(null, { let layer_cuencas = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_cuencas", pane: "pane_cuencas",
//onEachFeature: pop_cuencas,
style: style_cuencas style: style_cuencas
}); });
...@@ -214,7 +195,6 @@ const style_limZMs = () => { ...@@ -214,7 +195,6 @@ const style_limZMs = () => {
let layer_limZMs = new L.geoJson(null, { let layer_limZMs = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_limZMs", pane: "pane_limZMs",
//onEachFeature: pop_limZMs,
style: style_limZMs style: style_limZMs
}); });
...@@ -233,7 +213,6 @@ const style_ZMs = feature => { ...@@ -233,7 +213,6 @@ const style_ZMs = feature => {
fillOpacity: 1, fillOpacity: 1,
fillColor: "rgba(139,60,0,0.6)" fillColor: "rgba(139,60,0,0.6)"
} }
//break;
case "Villahermosa": case "Villahermosa":
return { return {
pane: "pane_ZMs", pane: "pane_ZMs",
...@@ -247,14 +226,12 @@ const style_ZMs = feature => { ...@@ -247,14 +226,12 @@ const style_ZMs = feature => {
fillOpacity: 1, fillOpacity: 1,
fillColor: "rgba(207,152,62,0.6)" fillColor: "rgba(207,152,62,0.6)"
} }
//break;
} }
} }
let layer_ZMs = new L.geoJson(null, { let layer_ZMs = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_ZMs", pane: "pane_ZMs",
//onEachFeature: pop_ZMs,
style: style_ZMs style: style_ZMs
}); });
...@@ -276,7 +253,6 @@ const style_ANPs = () => { ...@@ -276,7 +253,6 @@ const style_ANPs = () => {
let layer_ANPs = new L.geoJson(null, { let layer_ANPs = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_ANPs", pane: "pane_ANPs",
//onEachFeature: pop_ANPs,
style: style_ANPs style: style_ANPs
}); });
...@@ -295,12 +271,14 @@ const makeBaseMap = () => { ...@@ -295,12 +271,14 @@ const makeBaseMap = () => {
createPane("pane_wbnames",421); createPane("pane_wbnames",421);
layerControl.addOverlay(layer_nombresWB, "Nombres cuerpos de agua"); layerControl.addOverlay(layer_nombresWB, "Nombres cuerpos de agua");
zip2Lyr("../grijalva/data/puentes.zip", puentes, layer_puentes);
layerControl.addOverlay(layer_puentes, "&nbsp; <i class=\"fa fa-puente\" style=\"color:#808080;margin-top:3px; margin-left:0px;font-size: 10px;\"></i> &nbsp;Puentes"); layerControl.addOverlay(layer_puentes, "&nbsp; <i class=\"fa fa-puente\" style=\"color:#808080;margin-top:3px; margin-left:0px;font-size: 10px;\"></i> &nbsp;Puentes");
layerControl.addOverlay(layer_RedNacionalCaminos, "Red nacional de caminos <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c200\" alt=\"Red Nacional de Caminos\"/>"); layerControl.addOverlay(layer_RedNacionalCaminos, "Red nacional de caminos <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c200\" alt=\"Red Nacional de Caminos\"/>");
zip2Lyr("../grijalva/data/descargas.zip", descargas, layer_descargas); zip2Lyr("../grijalva/data/descargas.zip", descargas, layer_descargas);
layerControl.addOverlay(layer_descargas, "&nbsp; <i class=\"fa fa-desechos\" style=\"color:#808080;margin-top:3px;margin-left:0px;font-size: 12px;opacity:0.75;\"></i>&nbsp;&nbsp;Descargas residuales municipales e industriales"); layerControl.addOverlay(layer_descargas, "&nbsp; <i class=\"fa fa-desechos\" style=\"color:#808080;margin-top:3px;margin-left:0px;font-size: 12px;opacity:0.75;\"></i>&nbsp;&nbsp;Descargas residuales municipales e industriales");
zip2Lyr("../grijalva/data/presas.zip", presas, layer_presas); zip2Lyr("../grijalva/data/presas.zip", presas, layer_presas);
layerControl.addOverlay(layer_presas, "&nbsp; <i class=\"fa fa-presa\" style=\"color:#808080;margin-top:3px; margin-left:0px;font-size: 12px;\"></i> Presas principales"); layerControl.addOverlay(layer_presas, "&nbsp; <i class=\"fa fa-presa\" style=\"color:#808080;margin-top:3px; margin-left:0px;font-size: 12px;\"></i> Presas principales");
zip2Lyr("../grijalva/data/cuencas.zip", cuencas, layer_cuencas);
layerControl.addOverlay(layer_cuencas, "&nbsp; <svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(213,190,245,0.5)\" stroke=\"rgba(0,0,0,0.25)\" stroke-dasharray=\" \"></rect></svg> Cuenca y subcuencas del Grijalva, CONAGUA 2017"); layerControl.addOverlay(layer_cuencas, "&nbsp; <svg height=\"15\" width=\"15\"><path d=\"M0 0 L15 0 L15 10 L0 10 Z \" x=\"5\" y=\"5\" fill=\"rgba(213,190,245,0.5)\" stroke=\"rgba(0,0,0,0.25)\" stroke-dasharray=\" \"></rect></svg> Cuenca y subcuencas del Grijalva, CONAGUA 2017");
layerControl.addOverlay(layer_locUrban, "<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c102\" alt=\"Localidades urbanas\"/>"); layerControl.addOverlay(layer_locUrban, "<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c102\" alt=\"Localidades urbanas\"/>");
zip2Lyr("../grijalva/data/limites_TG_V.zip", tuxtlaVH, layer_limZMs); zip2Lyr("../grijalva/data/limites_TG_V.zip", tuxtlaVH, layer_limZMs);
......
...@@ -6,20 +6,20 @@ ...@@ -6,20 +6,20 @@
*/ */
/* globals updateBarChartOnHover, barChartData, am4charts, am4core, am4themes_animated, yearList */ /* globals updateBarChartOnHover, barChartData, am4charts, am4core, am4themes_animated, yearList */
/* export makeRadarChart, makeLineChart, makeAreaChart, makeBarChart, */ /* export makeRadarChart, makeLineChart, makeAreaChart, makeBarChart */
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function grijalva_theme(target) { const grijalva_theme = target => {
if (target instanceof am4core.ColorSet) { if (target instanceof am4core.ColorSet) {
target.list = [ target.list = [
am4core.color("#00c5ff"), am4core.color("#00c5ff"),
am4core.color("#ff5500"), am4core.color("#ff5500"),
am4core.color("#98e600"), am4core.color("#98e600")
]; ];
} }
} }
function customizeGrip(grip) { const customizeGrip = grip => {
// Remove default grip image // Remove default grip image
grip.icon.disabled = true; grip.icon.disabled = true;
...@@ -39,10 +39,10 @@ function customizeGrip(grip) { ...@@ -39,10 +39,10 @@ function customizeGrip(grip) {
// Themes begin // Themes begin
am4core.useTheme(am4themes_animated); am4core.useTheme(am4themes_animated);
am4core.useTheme(grijalva_theme); am4core.useTheme(grijalva_theme);
//let mainTextColor = getComputedStyle(document.body).getPropertyValue('--main-text-color'); //let mainTextColor = getComputedStyle(document.body).getPropertyValue("--main-text-color");
// Themes end // Themes end
let mainTextColor = getComputedStyle(document.body).getPropertyValue('--main-text-color'); let mainTextColor = getComputedStyle(document.body).getPropertyValue("--main-text-color");
const makeRadarSeries = (chart, value, category, name, color) => { const makeRadarSeries = (chart, value, category, name, color) => {
let radarSeries = chart.series.push(new am4charts.RadarSeries()); let radarSeries = chart.series.push(new am4charts.RadarSeries());
...@@ -98,10 +98,10 @@ const makeDateRange = (axis, start, width, color) => { ...@@ -98,10 +98,10 @@ const makeDateRange = (axis, start, width, color) => {
yearList.forEach( y => { yearList.forEach( y => {
let range = axis.axisRanges.create(); let range = axis.axisRanges.create();
range.date = new Date(y, start, 1, 0, 0, 0); range.date = new Date(y, start, 1, 0, 0, 0);
range.endDate = new Date(y, start+width, 1, 0, 0, 0); range.endDate = new Date(y, start + width, 1, 0, 0, 0);
range.axisFill.fill = am4core.color(color); range.axisFill.fill = am4core.color(color);
range.axisFill.fillOpacity = 0.4; range.axisFill.fillOpacity = 0.4;
}) });
} }
const makeAreaSeries = (chart, field, name) => { const makeAreaSeries = (chart, field, name) => {
...@@ -201,9 +201,9 @@ const makeRadarChart = (data, months, years) => { ...@@ -201,9 +201,9 @@ const makeRadarChart = (data, months, years) => {
//radarCategoryAxis.cursorTooltipEnabled = false; //radarCategoryAxis.cursorTooltipEnabled = false;
//FIXME: some months are not showing the appropriate name on tooltip on hover //FIXME: some months are not showing the appropriate name on tooltip on hover
// in the meantime this is way around to fix cursor columns and not show wrong // in the meantime this is a way around to fix cursor columns and not show wrong
// month tooltips // month tooltips
radarChart.cursor.events.on("cursorpositionchanged", function(ev) { radarChart.cursor.events.on("cursorpositionchanged", ev => {
let categoryAxis = ev.target.chart.xAxes.getIndex(0); let categoryAxis = ev.target.chart.xAxes.getIndex(0);
categoryAxis.tooltip.hide(); categoryAxis.tooltip.hide();
}); });
...@@ -339,7 +339,7 @@ const makeAreaChart = (data) => { ...@@ -339,7 +339,7 @@ const makeAreaChart = (data) => {
/* Set up cursor behavior */ /* Set up cursor behavior */
let previousDate = ""; let previousDate = "";
areaChart.cursor.events.on("cursorpositionchanged", function(ev) { areaChart.cursor.events.on("cursorpositionchanged", ev => {
let dateAxis = ev.target.chart.xAxes.getIndex(0); let dateAxis = ev.target.chart.xAxes.getIndex(0);
let yy = dateAxis.positionToDate(dateAxis.toAxisPosition(ev.target.xPosition)).getFullYear().toString(); let yy = dateAxis.positionToDate(dateAxis.toAxisPosition(ev.target.xPosition)).getFullYear().toString();
let mm = dateAxis.positionToDate(dateAxis.toAxisPosition(ev.target.xPosition)).getMonth().toString(); let mm = dateAxis.positionToDate(dateAxis.toAxisPosition(ev.target.xPosition)).getMonth().toString();
......
...@@ -81,7 +81,6 @@ const setupDates = () => { ...@@ -81,7 +81,6 @@ const setupDates = () => {
dateArray = dateArray.sort(sortInitialDateAscending); // order dates dateArray = dateArray.sort(sortInitialDateAscending); // order dates
dateMin = d3.min(dateArray); dateMin = d3.min(dateArray);
dateMax = d3.max(dateArray); dateMax = d3.max(dateArray);
//userFiles = dateArray.map( month => timeFormat(month)); // order table names by date
const dates = { min: dateMin, max: dateMax, dates: dateArray }; const dates = { min: dateMin, max: dateMax, dates: dateArray };
resolve(dates); resolve(dates);
...@@ -307,8 +306,8 @@ const populateMap = async (mapData) => { ...@@ -307,8 +306,8 @@ const populateMap = async (mapData) => {
}); });
glmap = L.mapboxGL({ glmap = L.mapboxGL({
accessToken: "no-token", "accessToken": "no-token",
style: { "style": {
"version": 8, "version": 8,
"sources": {}, "sources": {},
"layers": [] "layers": []
...@@ -319,11 +318,10 @@ const populateMap = async (mapData) => { ...@@ -319,11 +318,10 @@ const populateMap = async (mapData) => {
glmap.getMapboxMap().on("style.load", () => { glmap.getMapboxMap().on("style.load", () => {
glmap.getMapboxMap().addSource("basecuerposagua", { glmap.getMapboxMap().addSource("basecuerposagua", {
type: "vector", "type": "vector",
//tiles: [`${baseUrl}/basecuerposagua/mvt/{z}/{x}/{y}?geom_column=geom&columns=${indicators.join()},descrip`], "tiles": [`${baseUrl}/basecuerposagua/mvt/{z}/{x}/{y}?geom_column=geom&columns=descrip`],
tiles: [`${baseUrl}/basecuerposagua/mvt/{z}/{x}/{y}?geom_column=geom&columns=descrip`], "maxzoom": 14,
maxzoom: 14, "minzoom": 7
minzoom: 7
}); });
glmap.getMapboxMap().addLayer({ glmap.getMapboxMap().addLayer({
...@@ -408,7 +406,6 @@ const updateMap = (mapData) => { ...@@ -408,7 +406,6 @@ const updateMap = (mapData) => {
userFiles.forEach(monthYear => { userFiles.forEach(monthYear => {
if (Object.keys(allTiles).includes(monthYear)) { if (Object.keys(allTiles).includes(monthYear)) {
currentTiles[monthYear] = allTiles[monthYear]; // recover tile if it has already been created currentTiles[monthYear] = allTiles[monthYear]; // recover tile if it has already been created
//currentJSONs[monthYear] = allJSONs[monthYear]; // recover json if it has already been created
return; // if file has already been processed, exit return; // if file has already been processed, exit
} else { // if file cannot be found in allTiles, then add 1 to the number of files to process } else { // if file cannot be found in allTiles, then add 1 to the number of files to process
let newTile = mapboxLayer(monthYear); let newTile = mapboxLayer(monthYear);
...@@ -424,20 +421,19 @@ const updateMap = (mapData) => { ...@@ -424,20 +421,19 @@ const updateMap = (mapData) => {
timeLayer._timeDimension.setCurrentTime(mapData.min); timeLayer._timeDimension.setCurrentTime(mapData.min);
} }
// define MVT layer for given month table and all indicators // define MVT layer for given month table and description
const mapboxLayer = (monthYear) => { const mapboxLayer = (monthYear) => {
let pbfLayer = { let pbfLayer = {
id: monthYear, "id": monthYear,
source: { "source": {
type: "vector", "type": "vector",
//tiles: [`${baseUrl}/${monthYear}/mvt/{z}/{x}/{y}?geom_column=geom&columns=${indicators.join()},descrip`], "tiles": [`${baseUrl}/${monthYear}/mvt/{z}/{x}/{y}?geom_column=geom&columns=descrip`],
tiles: [`${baseUrl}/${monthYear}/mvt/{z}/{x}/{y}?geom_column=geom&columns=descrip`], "maxzoom": 14,
maxzoom: 14, "minzoom": 7
minzoom: 7
}, },
"source-layer": monthYear, "source-layer": monthYear,
type: "fill", "type": "fill",
"paint": { "paint": {
"fill-opacity": 0, "fill-opacity": 0,
"fill-color": ["match", ["get", "descrip"], "fill-color": ["match", ["get", "descrip"],
...@@ -583,7 +579,7 @@ const makeCharts = () => { ...@@ -583,7 +579,7 @@ const makeCharts = () => {
// create sets of unique months and years // create sets of unique months and years
yearList = [... new Set(userDates.map( date => new Date(date).getFullYear() ))]; yearList = [... new Set(userDates.map( date => new Date(date).getFullYear() ))];
let allYears = [... new Set(dateArray.map( date => new Date(date).getFullYear() ))]; let allYears = [... new Set(dateArray.map( date => new Date(date).getFullYear() ))];
//let formatter = new Intl.DateTimeFormat('es', { month: 'long' }); //let formatter = new Intl.DateTimeFormat("es", { month: "long" });
// RADAR CHART // RADAR CHART
// async queries for each date that has been loaded // async queries for each date that has been loaded
...@@ -707,8 +703,8 @@ const updateBarChartOnHover = (filterDate, data) => { ...@@ -707,8 +703,8 @@ const updateBarChartOnHover = (filterDate, data) => {
popBarsChart.data = cart_pb1; popBarsChart.data = cart_pb1;
popBarsChart.invalidateRawData(); popBarsChart.invalidateRawData();
// set barChart title when hovering on different bars // set barChart title when hovering on different bars
let ye = new Intl.DateTimeFormat('es', { year: 'numeric' }).format(filterDate); let ye = new Intl.DateTimeFormat("es", { year: "numeric" }).format(filterDate);
let mo = new Intl.DateTimeFormat('es', { month: 'short' }).format(filterDate); let mo = new Intl.DateTimeFormat("es", { month: "short" }).format(filterDate);
popBarsChart.titles.values[0].text = `Conteo por tipo de cuerpo en ${mo} ${ye}`; popBarsChart.titles.values[0].text = `Conteo por tipo de cuerpo en ${mo} ${ye}`;
// TODO: update barChart when changing dates on timeDimension? // TODO: update barChart when changing dates on timeDimension?
} }
......
...@@ -46,7 +46,6 @@ const setupMap = (dates) => { ...@@ -46,7 +46,6 @@ const setupMap = (dates) => {
attribution: "Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL." attribution: "Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL."
}); });
//let bounds = cuencaBufferMask.getBounds();
let southWest = L.latLng(19.87, -102.87), let southWest = L.latLng(19.87, -102.87),
northEast = L.latLng(23.02, -99.31), northEast = L.latLng(23.02, -99.31),
bounds = L.latLngBounds(southWest, northEast); bounds = L.latLngBounds(southWest, northEast);
...@@ -115,9 +114,9 @@ const setupMap = (dates) => { ...@@ -115,9 +114,9 @@ const setupMap = (dates) => {
}); });
const offsetGlobal = (center, zoom, refMap, tgtMap) => { const offsetGlobal = (center, zoom, refMap, tgtMap) => {
var refC = refMap.getContainer(); let refC = refMap.getContainer();
var tgtC = tgtMap.getContainer(); let tgtC = tgtMap.getContainer();
var pt = refMap.project(center, zoom) let pt = refMap.project(center, zoom)
.subtract([refC.offsetLeft, refC.offsetTop]) .subtract([refC.offsetLeft, refC.offsetTop])
.subtract(refMap.getSize().divideBy(2)) .subtract(refMap.getSize().divideBy(2))
.add([tgtC.offsetLeft, tgtC.offsetTop]) .add([tgtC.offsetLeft, tgtC.offsetTop])
...@@ -137,8 +136,8 @@ const populateMap = async(mapData) => { ...@@ -137,8 +136,8 @@ const populateMap = async(mapData) => {
let map = mapData.map; let map = mapData.map;
glmap = L.mapboxGL({ glmap = L.mapboxGL({
accessToken: "no-token", "accessToken": "no-token",
style: { "style": {
"version": 8, "version": 8,
"sources": {}, "sources": {},
"layers": [] "layers": []
...@@ -149,7 +148,7 @@ const populateMap = async(mapData) => { ...@@ -149,7 +148,7 @@ const populateMap = async(mapData) => {
glmap.getMapboxMap().on("style.load", () => { glmap.getMapboxMap().on("style.load", () => {
glmap.getMapboxMap().addLayer(tiles); glmap.getMapboxMap().addLayer(tiles);
//glmap.getMapboxMap().setPaintProperty(tiles, "fill-opacity", 0.7) //glmap.getMapboxMap().setPaintProperty(tiles, "fill-opacity", 0.7);
timeDimensionControl.addTo(map); timeDimensionControl.addTo(map);
// Pass dummy geojson layer to timeDimension in order to register and sync // Pass dummy geojson layer to timeDimension in order to register and sync
...@@ -166,7 +165,7 @@ const populateMap = async(mapData) => { ...@@ -166,7 +165,7 @@ const populateMap = async(mapData) => {
"Carto Light": cartoLightLayer, "Carto Light": cartoLightLayer,
"OpenStreetMap": osmLayer "OpenStreetMap": osmLayer
}; };
var overlays = { let overlays = {
// "<span id=\"cuencaOverlay\">Agua en la cuenca del Grijalva</span>": timeLayer // "<span id=\"cuencaOverlay\">Agua en la cuenca del Grijalva</span>": timeLayer
}; };
...@@ -202,7 +201,6 @@ const populateMap = async(mapData) => { ...@@ -202,7 +201,6 @@ const populateMap = async(mapData) => {
} }
}); });
} }
//let html = `<div><h6>A&ntilde;o</h6></div><div class="colors", style="background: linear-gradient(to bottom, ${colors.join(",")})">`;
let html = "<div><h6>A&ntilde;o</h6></div><div class=\"colors\">"; let html = "<div><h6>A&ntilde;o</h6></div><div class=\"colors\">";
// create legend items // create legend items
years.forEach( y => { years.forEach( y => {
...@@ -225,15 +223,15 @@ const populateMap = async(mapData) => { ...@@ -225,15 +223,15 @@ const populateMap = async(mapData) => {
// define MVT layer for given table and all trimester column // define MVT layer for given table and all trimester column
const mapboxLayer = (table) => { const mapboxLayer = (table) => {
let pbfLayer = { let pbfLayer = {
id: table, "id": table,
source: { "source": {
type: "vector", "type": "vector",
tiles: [`${baseUrl}/${table}/mvt/{z}/{x}/{y}?geom_column=geom&columns=yeartrimes`], "tiles": [`${baseUrl}/${table}/mvt/{z}/{x}/{y}?geom_column=geom&columns=yeartrimes`],
maxzoom: 19, "maxzoom": 19,
minzoom: 6 "minzoom": 6
}, },
"source-layer": table, "source-layer": table,
type: "fill", "type": "fill",
"paint": { "paint": {
"fill-opacity": 0.7, "fill-opacity": 0.7,
"fill-color": [ "fill-color": [
...@@ -243,20 +241,9 @@ const mapboxLayer = (table) => { ...@@ -243,20 +241,9 @@ const mapboxLayer = (table) => {
2014, "rgb(49,54,149)", 2014, "rgb(49,54,149)",
2016, "rgb(255,255,191)", 2016, "rgb(255,255,191)",
2019, "rgb(158,1,66)" 2019, "rgb(158,1,66)"
/*2014, "rgba(0, 255, 0, 0.5)", // green ]
2019, "rgba(255, 0, 0, 0.5)", // red*/
],/*
"fill-outline-color": [
"interpolate",
["linear"],
["get", "df"],
1, "rgba(255, 0, 0, 0.6)", // red
1.3, "rgba(0, 255, 0, 0.6)", // green
]*/
} }
} }
/*currentTiles[monthYear] = pbfLayer;
allTiles[monthYear] = pbfLayer;*/
return pbfLayer; return pbfLayer;
} }
...@@ -295,7 +282,6 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({ ...@@ -295,7 +282,6 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({
let tiArray = L.TimeDimension.Util.parseTimeInterval(this.options.timeInterval); let tiArray = L.TimeDimension.Util.parseTimeInterval(this.options.timeInterval);
let period = this.options.period || "P1D"; let period = this.options.period || "P1D";
let validTimeRange = this.options.validTimeRange || undefined; let validTimeRange = this.options.validTimeRange || undefined;
//alert("times");
return L.TimeDimension.Util.explodeTimeRange(tiArray[0], tiArray[1], period, validTimeRange); return L.TimeDimension.Util.explodeTimeRange(tiArray[0], tiArray[1], period, validTimeRange);
} else { } else {
return []; return [];
...@@ -338,7 +324,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({ ...@@ -338,7 +324,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({
return; return;
} }
var time = this._timeDimension.getCurrentTime(); let time = this._timeDimension.getCurrentTime();
//TODO: get current time, parse quarter and compare tile value. Incremental add over time //TODO: get current time, parse quarter and compare tile value. Incremental add over time
// get data for time // get data for time
...@@ -347,14 +333,12 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({ ...@@ -347,14 +333,12 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({
m = d.getUTCMonth(), m = d.getUTCMonth(),
yeartrimester = year + "." + (m / 3 + 1), yeartrimester = year + "." + (m / 3 + 1),
yearQ = `Q${m/3+1} ${year}`; yearQ = `Q${m/3+1} ${year}`;
//month = monthArray[m].toLowerCase(),
//monthYear = `${month}_${year}`;
// Update title // Update title
let title = $("#title"); let title = $("#title");
title.html(`<h2>Crecimiento urbano en la regi&oacute;n metropolitana centro pa&iacute;s en ${yearQ}</h2>`); title.html(`<h2>Crecimiento urbano en la regi&oacute;n metropolitana centro pa&iacute;s en ${yearQ}</h2>`);
// styleTiles based on yeartrimester value
// filter tiles based on yeartrimester value
let filter = ["<=", ["get", "yeartrimes"], parseFloat(yeartrimester)]; let filter = ["<=", ["get", "yeartrimes"], parseFloat(yeartrimester)];
glmap.getMapboxMap().setFilter("urbanization_year", filter); glmap.getMapboxMap().setFilter("urbanization_year", filter);
} }
......
...@@ -9,17 +9,15 @@ ...@@ -9,17 +9,15 @@
// amchart // amchart
am4core.ready(function() { am4core.ready(function() {
// am4core.useTheme(urban_theme);
let mainTextColor = getComputedStyle(document.body).getPropertyValue('--main-text-color'); let mainTextColor = getComputedStyle(document.body).getPropertyValue("--main-text-color");
// bar and line chart // bar and line chart
var chart = am4core.create("topChart", am4charts.XYChart); let chart = am4core.create("topChart", am4charts.XYChart);
let ctitle = chart.titles.create(); let ctitle = chart.titles.create();
ctitle.text = "Área urbanizada trimestralmente"; ctitle.text = "Área urbanizada trimestralmente";
ctitle.fontSize = 15; ctitle.fontSize = 15;
//title.marginBottom = 30;
ctitle.fill = am4core.color(mainTextColor); ctitle.fill = am4core.color(mainTextColor);
// Create axes // Create axes
...@@ -88,8 +86,6 @@ am4core.ready(function() { ...@@ -88,8 +86,6 @@ am4core.ready(function() {
valueAxisL.fontSize = 15; valueAxisL.fontSize = 15;
valueAxisL.renderer.labels.template.fontSize = 15; valueAxisL.renderer.labels.template.fontSize = 15;
//valueAxisL.calculateTotals = true; //valueAxisL.calculateTotals = true;
//valueAxisL.min = valueAxis3.minZoomed;
//valueAxisL.max = valueAxis3.maxZoomed;
// Modify chart's colors // Modify chart's colors
chart.colors.list = [ chart.colors.list = [
...@@ -163,12 +159,8 @@ am4core.ready(function() { ...@@ -163,12 +159,8 @@ am4core.ready(function() {
chart.legend.labels.template.fill = am4core.color(mainTextColor); chart.legend.labels.template.fill = am4core.color(mainTextColor);
//Add scrollbar //Add scrollbar
// chart.legend.labels.template.fill = am4core.color(mainTextColor);
chart.scrollbarX = new am4charts.XYChartScrollbar(); chart.scrollbarX = new am4charts.XYChartScrollbar();
// chart.scrollbarX.series.push(series3);
chart.scrollbarX.minHeight = 1; chart.scrollbarX.minHeight = 1;
//chart.scrollbarX.series.push(series3);
chart.scrollbarX.parent = chart.bottomAxesContainer; chart.scrollbarX.parent = chart.bottomAxesContainer;
// pie chart // pie chart
...@@ -223,7 +215,7 @@ am4core.ready(function() { ...@@ -223,7 +215,7 @@ am4core.ready(function() {
// Themes end // Themes end
var rchart = am4core.create("bottomRightChart", am4charts.RadarChart); let rchart = am4core.create("bottomRightChart", am4charts.RadarChart);
// chart.hiddenState.properties.opacity = 0; // this creates initial fade-in // chart.hiddenState.properties.opacity = 0; // this creates initial fade-in
let query_r = `${baseUrl}/query/${table}?columns=sum(area)/10000 as area,DATE_PART('month',date) as mm,concat('Q', DATE_PART('quarter',date)::text) as qq&group=mm,qq &sort=mm`; let query_r = `${baseUrl}/query/${table}?columns=sum(area)/10000 as area,DATE_PART('month',date) as mm,concat('Q', DATE_PART('quarter',date)::text) as qq&group=mm,qq &sort=mm`;
...@@ -238,8 +230,8 @@ am4core.ready(function() { ...@@ -238,8 +230,8 @@ am4core.ready(function() {
rchart.endAngle = rchart.startAngle + 180; rchart.endAngle = rchart.startAngle + 180;
// Create axes // Create axes
// var dateAxis = chart.xAxes.push(new am4charts.DateAxis()); // let dateAxis = chart.xAxes.push(new am4charts.DateAxis());
var dateAxis = rchart.xAxes.push(new am4charts.CategoryAxis()); let dateAxis = rchart.xAxes.push(new am4charts.CategoryAxis());
dateAxis.dataFields.category = "qq"; dateAxis.dataFields.category = "qq";
// dateAxis.baseInterval = { timeUnit: "month", count: 3 }; // dateAxis.baseInterval = { timeUnit: "month", count: 3 };
//dateAxis.renderer.innerRadius = am4core.percent(40); //dateAxis.renderer.innerRadius = am4core.percent(40);
...@@ -252,7 +244,7 @@ am4core.ready(function() { ...@@ -252,7 +244,7 @@ am4core.ready(function() {
dateAxis.cursorTooltipEnabled = false; dateAxis.cursorTooltipEnabled = false;
// dateAxis.calculateTotals = true; // dateAxis.calculateTotals = true;
var valueAxis = rchart.yAxes.push(new am4charts.ValueAxis()); let valueAxis = rchart.yAxes.push(new am4charts.ValueAxis());
valueAxis.renderer.inversed = true; valueAxis.renderer.inversed = true;
valueAxis.renderer.radius = am4core.percent(40); valueAxis.renderer.radius = am4core.percent(40);
valueAxis.renderer.minGridDistance = 15; valueAxis.renderer.minGridDistance = 15;
...@@ -265,7 +257,7 @@ am4core.ready(function() { ...@@ -265,7 +257,7 @@ am4core.ready(function() {
// valueAxis.calculateTotals = true; // valueAxis.calculateTotals = true;
//Add series //Add series
var columnSeries = rchart.series.push(new am4charts.RadarColumnSeries()); let columnSeries = rchart.series.push(new am4charts.RadarColumnSeries());
// columnSeries.dataFields.dateX = "date"; // columnSeries.dataFields.dateX = "date";
columnSeries.dataFields.categoryX = "qq"; //date columnSeries.dataFields.categoryX = "qq"; //date
...@@ -281,7 +273,7 @@ am4core.ready(function() { ...@@ -281,7 +273,7 @@ am4core.ready(function() {
columnSeries.tooltip.background.fillOpacity = 0.5; columnSeries.tooltip.background.fillOpacity = 0.5;
columnSeries.columns.template.tooltipText = "[bold]{qq}[/]\nTotal {valueY.formatNumber('#,###.##')} Ha"; columnSeries.columns.template.tooltipText = "[bold]{qq}[/]\nTotal {valueY.formatNumber('#,###.##')} Ha";
columnSeries.cursorTooltipEnabled = false; columnSeries.cursorTooltipEnabled = false;
columnSeries.columns.template.adapter.add("fill", function(fill, target) { columnSeries.columns.template.adapter.add("fill", (fill, target) => {
if (target.dataItem && (target.dataItem.categoryX == "Q1")) { if (target.dataItem && (target.dataItem.categoryX == "Q1")) {
return am4core.color("#F18275"); return am4core.color("#F18275");
} else if (target.dataItem && (target.dataItem.categoryX == "Q2")) { } else if (target.dataItem && (target.dataItem.categoryX == "Q2")) {
...@@ -295,13 +287,7 @@ am4core.ready(function() { ...@@ -295,13 +287,7 @@ am4core.ready(function() {
} }
}); });
/* //ANILLO EXTERIOR //ANILLO EXTERIOR
var range = dateAxis.axisRanges.create();
range.category = "January";
range.endCategory = "April";
range.axisFill.fill = am4core.color("#396478");
range.axisFill.fillOpacity = 0.3;*/
let yearsAxis = rchart.yAxes.push(new am4charts.CategoryAxis()); let yearsAxis = rchart.yAxes.push(new am4charts.CategoryAxis());
let bubbleSeries = rchart.series.push(new am4charts.RadarSeries()); let bubbleSeries = rchart.series.push(new am4charts.RadarSeries());
...@@ -314,9 +300,7 @@ am4core.ready(function() { ...@@ -314,9 +300,7 @@ am4core.ready(function() {
}); });
// weekday axis // weekday axis
//var weekDayAxis = chart.yAxes.push(new am4charts.CategoryAxis());
yearsAxis.dataFields.category = "yy"; yearsAxis.dataFields.category = "yy";
//yearsAxis.data = dailyData;
yearsAxis.renderer.innerRadius = am4core.percent(50); yearsAxis.renderer.innerRadius = am4core.percent(50);
yearsAxis.renderer.minGridDistance = 10; yearsAxis.renderer.minGridDistance = 10;
yearsAxis.renderer.grid.template.location = 0; yearsAxis.renderer.grid.template.location = 0;
...@@ -330,12 +314,10 @@ am4core.ready(function() { ...@@ -330,12 +314,10 @@ am4core.ready(function() {
yearsAxis.numberFormatter.numberFormat = "####"; yearsAxis.numberFormatter.numberFormat = "####";
// bubble series // bubble series
//var bubbleSeries = chart.series.push(new am4charts.RadarSeries());
bubbleSeries.dataFields.categoryX = "qq"; bubbleSeries.dataFields.categoryX = "qq";
bubbleSeries.dataFields.categoryY = "yy"; bubbleSeries.dataFields.categoryY = "yy";
bubbleSeries.dataFields.value = "area"; bubbleSeries.dataFields.value = "area";
bubbleSeries.yAxis = yearsAxis; bubbleSeries.yAxis = yearsAxis;
//bubbleSeries.data = dailyData;
bubbleSeries.strokeOpacity = 0; bubbleSeries.strokeOpacity = 0;
bubbleSeries.maskBullets = false; bubbleSeries.maskBullets = false;
bubbleSeries.cursorTooltipEnabled = false; bubbleSeries.cursorTooltipEnabled = false;
...@@ -344,16 +326,14 @@ am4core.ready(function() { ...@@ -344,16 +326,14 @@ am4core.ready(function() {
bubbleSeries.tooltip.background.fillOpacity = 0.5; bubbleSeries.tooltip.background.fillOpacity = 0.5;
bubbleSeries.dataItems.template.locations.categoryX = 0.5; bubbleSeries.dataItems.template.locations.categoryX = 0.5;
var bubbleBullet = bubbleSeries.bullets.push(new am4charts.CircleBullet()) let bubbleBullet = bubbleSeries.bullets.push(new am4charts.CircleBullet());
bubbleBullet.locationX = 0.5; bubbleBullet.locationX = 0.5;
//bubbleBullet.stroke = am4core.color(mainTextColor);
//bubbleBullet.fill = am4core.color("#b9ce37");
bubbleBullet.tooltipText = "[bold]Q{date.formatDate('q yyyy')}:[/] \n{value.formatNumber('#,###.0')} Ha"; bubbleBullet.tooltipText = "[bold]Q{date.formatDate('q yyyy')}:[/] \n{value.formatNumber('#,###.0')} Ha";
bubbleBullet.adapter.add("tooltipY", function(tooltipY, target) { bubbleBullet.adapter.add("tooltipY", (tooltipY, target) => {
return -target.circle.radius; return -target.circle.radius;
}); });
// TODO: Fix these calls to automatically use available years // TODO: Fix these calls to automatically use available years
bubbleBullet.adapter.add("fill", function(fill, target) { bubbleBullet.adapter.add("fill", (fill, target) => {
if (target.dataItem && (target.dataItem.categoryY == "2014")) { if (target.dataItem && (target.dataItem.categoryY == "2014")) {
return am4core.color("#313695"); return am4core.color("#313695");
} else if (target.dataItem && (target.dataItem.categoryY == "2015")) { } else if (target.dataItem && (target.dataItem.categoryY == "2015")) {
...@@ -371,7 +351,7 @@ am4core.ready(function() { ...@@ -371,7 +351,7 @@ am4core.ready(function() {
} }
}); });
// TODO: Fix these calls to automatically use available years // TODO: Fix these calls to automatically use available years
bubbleBullet.adapter.add("stroke", function(fill, target) { bubbleBullet.adapter.add("stroke", (fill, target) => {
if (target.dataItem && (target.dataItem.categoryY == "2014")) { if (target.dataItem && (target.dataItem.categoryY == "2014")) {
return am4core.color("#313695"); return am4core.color("#313695");
} else if (target.dataItem && (target.dataItem.categoryY == "2015")) { } else if (target.dataItem && (target.dataItem.categoryY == "2015")) {
...@@ -397,7 +377,7 @@ am4core.ready(function() { ...@@ -397,7 +377,7 @@ am4core.ready(function() {
rchart.cursor.innerRadius = am4core.percent(40); rchart.cursor.innerRadius = am4core.percent(40);
rchart.cursor.lineY.disabled = true; rchart.cursor.lineY.disabled = true;
var label = rchart.radarContainer.createChild(am4core.Label); let label = rchart.radarContainer.createChild(am4core.Label);
label.horizontalCenter = "middle"; label.horizontalCenter = "middle";
label.verticalCenter = "middle"; label.verticalCenter = "middle";
label.fill = am4core.color(mainTextColor); label.fill = am4core.color(mainTextColor);
...@@ -405,7 +385,7 @@ am4core.ready(function() { ...@@ -405,7 +385,7 @@ am4core.ready(function() {
//label.fontWeight = "bold"; //label.fontWeight = "bold";
label.text = "TOTAL\nTRIMESTRAL"; label.text = "TOTAL\nTRIMESTRAL";
var title = rchart.createChild(am4core.Label); let title = rchart.createChild(am4core.Label);
title.fill = am4core.color("#b9ce37"); title.fill = am4core.color("#b9ce37");
title.fontSize = 15; title.fontSize = 15;
title.isMeasured = false; title.isMeasured = false;
......
...@@ -5,28 +5,11 @@ ...@@ -5,28 +5,11 @@
* August-September 2019 * August-September 2019
*/ */
/* global baseFileSize, formatBytes, Promise, omnivore, JSZip, map, layerControl, updateCharts */ /* global Promise, omnivore, JSZip, map, layerControl, updateCharts */
/* exported makeBaseMap, baseLayerPromises, drawnItems */ /* exported makeBaseMap, baseLayerPromises, drawnItems */
/* Lines related to displaying loading bar are commented */ let baseLayerPromises = [],
drawnItems;
let baseLayerPromises = [];
/* baseSize = 0,
baseDisplaySize,
baseLoadedSize = 0,
baseLoadedDisplaySize,
baseLayerCounter = 0,
currentBaseLayer = 1;*/
let drawnItems;
/*Object.keys(baseFileSize).forEach((name) => {
if (name.split(".")[1] == "zip") {
baseSize += parseFloat(baseFileSize[name].size); // file size to load for zipped base layers
baseDisplaySize = formatBytes(baseSize, 2); // size in pretty units
baseLayerCounter++;
}
});*/
// function to read compressed json and create a leaflet layer // function to read compressed json and create a leaflet layer
const zip2Lyr = (zipFile, layerName, layerTemplate) => { const zip2Lyr = (zipFile, layerName, layerTemplate) => {
...@@ -49,17 +32,7 @@ const zip2Lyr = (zipFile, layerName, layerTemplate) => { ...@@ -49,17 +32,7 @@ const zip2Lyr = (zipFile, layerName, layerTemplate) => {
.then( ([file, type]) => { .then( ([file, type]) => {
file.async("string").then( file.async("string").then(
function success(text) { // 5) display the result function success(text) { // 5) display the result
/*let baseFile = zipFile.split("/")[3]; if (type == "json") {
¬baseLoadedSize += parseFloat(baseFileSize[baseFile].size); // cumulative loaded size
baseLoadedDisplaySize = formatBytes(baseLoadedSize); // in pretty units
let baseBarWidth = (baseLoadedSize/baseSize*100);*/
/*currentBaseLayer++;
let baseFiles = currentBaseLayer <= baseLayerCounter ? currentBaseLayer : baseLayerCounter;
$("#basemap-fileLoad").html("Cargando capa " + baseFiles + " de " + baseLayerCounter + "<br>" +
"<span class=\"progress\"><span id=\"baseBar\" class=\"progress-bar progress-bar-striped progress-bar-animated\" role=\"progressbar\" style=\"width: " + baseBarWidth + "%;\" aria-valuenow=\"" + baseBarWidth + "\" aria-valuemin=\"0\" aria-valuemax=\"100\"></span>" +
"<span class=\"justify-content-center d-flex position-absolute w-100\">" + baseLoadedDisplaySize + "/" + baseDisplaySize + "</span></span>");
*/if (type == "json") {
layerTemplate.addData(JSON.parse(text)); layerTemplate.addData(JSON.parse(text));
} else if (type == "topojson") { } else if (type == "topojson") {
layerName = omnivore.topojson.parse(text, null, layerTemplate); layerName = omnivore.topojson.parse(text, null, layerTemplate);
...@@ -168,12 +141,7 @@ let layer_areaVerdeUrbana= new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tun ...@@ -168,12 +141,7 @@ let layer_areaVerdeUrbana= new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tun
let layer_escuelas = new L.geoJson(null, { let layer_escuelas = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_escuelas", pane: "pane_escuelas",
//onEachFeature: pop_escuelas,
pointToLayer: (feature, latlng) => { pointToLayer: (feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let escuelaMarker = L.BeautifyIcon.icon({ let escuelaMarker = L.BeautifyIcon.icon({
icon: "escuela", icon: "escuela",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -195,12 +163,7 @@ let layer_escuelas = new L.geoJson(null, { ...@@ -195,12 +163,7 @@ let layer_escuelas = new L.geoJson(null, {
let layer_hospitales = new L.geoJson(null, { let layer_hospitales = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_hospitales", pane: "pane_hospitales",
//onEachFeature: pop_hospitales,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let hospitalMarker = L.BeautifyIcon.icon({ let hospitalMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -223,12 +186,7 @@ let layer_hospitales = new L.geoJson(null, { ...@@ -223,12 +186,7 @@ let layer_hospitales = new L.geoJson(null, {
let layer_hoteles = new L.geoJson(null, { let layer_hoteles = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_hoteles", pane: "pane_hoteles",
//onEachFeature: pop_hoteles,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let hotelMarker = L.BeautifyIcon.icon({ let hotelMarker = L.BeautifyIcon.icon({
icon: "bed", icon: "bed",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -250,14 +208,8 @@ let layer_hoteles = new L.geoJson(null, { ...@@ -250,14 +208,8 @@ let layer_hoteles = new L.geoJson(null, {
let layer_puentes = new L.geoJson(null, { let layer_puentes = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_puentes", pane: "pane_puentes",
//onEachFeature: pop_puentes,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// var context = {
// feature: feature,
// variables: {}
// };
let puenteMarker = L.BeautifyIcon.icon({ let puenteMarker = L.BeautifyIcon.icon({
// icon: "grip-lines-vertical",
icon: "puente", icon: "puente",
iconSize: [0, 0], iconSize: [0, 0],
iconAnchor: [7, 10], iconAnchor: [7, 10],
...@@ -278,12 +230,7 @@ let layer_puentes = new L.geoJson(null, { ...@@ -278,12 +230,7 @@ let layer_puentes = new L.geoJson(null, {
let layer_puerto = new L.geoJson(null, { let layer_puerto = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_puerto", pane: "pane_puerto",
//onEachFeature: pop_puerto,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let puertoMarker = L.BeautifyIcon.icon({ let puertoMarker = L.BeautifyIcon.icon({
icon: "puertoindustrial", icon: "puertoindustrial",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -305,13 +252,8 @@ let layer_puerto = new L.geoJson(null, { ...@@ -305,13 +252,8 @@ let layer_puerto = new L.geoJson(null, {
let layer_frontera = new L.geoJson(null, { let layer_frontera = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_frontera", pane: "pane_frontera",
//onEachFeature: pop_frontera,
styles: null, styles: null,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let fronteraMarker = L.BeautifyIcon.icon({ let fronteraMarker = L.BeautifyIcon.icon({
icon: "puntofronterizo", icon: "puntofronterizo",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -333,12 +275,7 @@ let layer_frontera = new L.geoJson(null, { ...@@ -333,12 +275,7 @@ let layer_frontera = new L.geoJson(null, {
let layer_descargas = new L.geoJson(null, { let layer_descargas = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_descargas", pane: "pane_descargas",
//onEachFeature: pop_descargas,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let descargasMarker = L.BeautifyIcon.icon({ let descargasMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -360,12 +297,7 @@ let layer_descargas = new L.geoJson(null, { ...@@ -360,12 +297,7 @@ let layer_descargas = new L.geoJson(null, {
let layer_presas = new L.geoJson(null, { let layer_presas = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_presas", pane: "pane_presas",
//onEachFeature: pop_presas,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let presasMarker = L.BeautifyIcon.icon({ let presasMarker = L.BeautifyIcon.icon({
icon: "presa", icon: "presa",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -402,7 +334,6 @@ const style_cuencas = () => { ...@@ -402,7 +334,6 @@ const style_cuencas = () => {
let layer_cuencas = new L.geoJson(null, { let layer_cuencas = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_cuencas", pane: "pane_cuencas",
//onEachFeature: pop_cuencas,
style: style_cuencas style: style_cuencas
}); });
...@@ -422,7 +353,6 @@ const style_limZMs = () => { ...@@ -422,7 +353,6 @@ const style_limZMs = () => {
let layer_limZMs = new L.geoJson(null, { let layer_limZMs = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_limZMs", pane: "pane_limZMs",
//onEachFeature: pop_limZMs,
style: style_limZMs style: style_limZMs
}); });
...@@ -441,7 +371,6 @@ const style_ZMs = feature => { ...@@ -441,7 +371,6 @@ const style_ZMs = feature => {
fillOpacity: 1, fillOpacity: 1,
fillColor: "rgba(139,60,0,0.6)" fillColor: "rgba(139,60,0,0.6)"
} }
//break;
case "Villahermosa": case "Villahermosa":
return { return {
pane: "pane_ZMs", pane: "pane_ZMs",
...@@ -455,14 +384,12 @@ const style_ZMs = feature => { ...@@ -455,14 +384,12 @@ const style_ZMs = feature => {
fillOpacity: 1, fillOpacity: 1,
fillColor: "rgba(207,152,62,0.6)" fillColor: "rgba(207,152,62,0.6)"
} }
//break;
} }
} }
let layer_ZMs = new L.geoJson(null, { let layer_ZMs = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_ZMs", pane: "pane_ZMs",
//onEachFeature: pop_ZMs,
style: style_ZMs style: style_ZMs
}); });
...@@ -484,7 +411,6 @@ const style_ANPs = () => { ...@@ -484,7 +411,6 @@ const style_ANPs = () => {
let layer_ANPs = new L.geoJson(null, { let layer_ANPs = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_ANPs", pane: "pane_ANPs",
//onEachFeature: pop_ANPs,
style: style_ANPs style: style_ANPs
}); });
...@@ -521,7 +447,7 @@ const toggleButtons = () => { ...@@ -521,7 +447,7 @@ const toggleButtons = () => {
b.onClick = null; b.onClick = null;
b.classList.remove("draw-control-disabled"); b.classList.remove("draw-control-disabled");
} }
}) });
} }
const makeBaseMap = () => { const makeBaseMap = () => {
...@@ -547,10 +473,6 @@ const makeBaseMap = () => { ...@@ -547,10 +473,6 @@ const makeBaseMap = () => {
createPane("pane_escuelas", 420); createPane("pane_escuelas", 420);
createPane("pane_wbnames",421); createPane("pane_wbnames",421);
/*$("#basemap-fileLoad").html("Cargando capa 1 de " + baseLayerCounter + "<br>" +
"<span class=\"progress\"><span id=\"baseBar\" class=\"progress-bar progress-bar-striped progress-bar-animated\" role=\"progressbar\" style=\"width: 0%;\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\"></span>" +
"<span class=\"justify-content-center d-flex position-absolute w-100\">0/" + baseDisplaySize + "</span></span>");*/
layerControl.addOverlay(layer_nombresWB, "Nombres cuerpos de agua"); layerControl.addOverlay(layer_nombresWB, "Nombres cuerpos de agua");
zip2Lyr("../grijalva/data/escuelas.zip", escuelas, layer_escuelas); zip2Lyr("../grijalva/data/escuelas.zip", escuelas, layer_escuelas);
layerControl.addOverlay(layer_escuelas, "Escuelas con 50 personas ocupadas o más<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#409400;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Básico<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#df6400;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Medio superior<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#c0d1e5;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Otras escuelas"); layerControl.addOverlay(layer_escuelas, "Escuelas con 50 personas ocupadas o más<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#409400;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Básico<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#df6400;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Medio superior<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class=\"fa fa-escuela\" style=\"color:#c0d1e5;margin-top:3px; margin-left:0px;font-size: 13px;\"></i> Otras escuelas");
...@@ -699,18 +621,12 @@ const makeBaseMap = () => { ...@@ -699,18 +621,12 @@ const makeBaseMap = () => {
draw: { draw: {
polygon: { polygon: {
showArea: true, showArea: true,
//allowIntersection: false, // Restricts shapes to simple polygons
//drawError: {
//color: "#f9a800",
//message: "<strong>you can't draw that!" // Message that will show when intersect
//},
shapeOptions: { shapeOptions: {
color: "#42ffc3" color: "#42ffc3"
} }
}, },
// disable toolbar item by setting it to false // disable toolbar item by setting it to false
polyline: { polyline: {
//allowIntersection:false,
shapeOptions: { shapeOptions: {
color: "#42ffc3" color: "#42ffc3"
} }
...@@ -725,8 +641,7 @@ const makeBaseMap = () => { ...@@ -725,8 +641,7 @@ const makeBaseMap = () => {
circle: false // Turns off this drawing tool circle: false // Turns off this drawing tool
}, },
edit: { edit: {
featureGroup: drawnItems, featureGroup: drawnItems
//remove: false
} }
}); });
map.addControl(drawControl); map.addControl(drawControl);
......
...@@ -219,12 +219,12 @@ const makeIndicatorGraph = () => { ...@@ -219,12 +219,12 @@ const makeIndicatorGraph = () => {
// define axes with ranges // define axes with ranges
xLine = d3.scaleTime().range([0, width - margin.left - margin.right - 30]).clamp(true); xLine = d3.scaleTime().range([0, width - margin.left - margin.right - 30]).clamp(true);
yLine = d3.scaleLinear().range([height - margin.left - margin.right, 0 + 35]) yLine = d3.scaleLinear().range([height - margin.left - margin.right, 0 + 35]);
// scale data range // scale data range
xLine.domain([minDate, maxDate]).nice(); xLine.domain([minDate, maxDate]).nice();
//yLine.domain(d3.extent(data, function(d) { return d[lineVariables[0]]; })).nice(); //yLine.domain(d3.extent(data, d => d[lineVariables[0]] )).nice();
//yLine.domain([0, d3.max(data, function(d) { return d[lineVariables[0]]; })]).nice(); //yLine.domain([0, d3.max(data, d => d[lineVariables[0]] )]).nice();
// Calculate min and max values of data to define chart y-axis domain // Calculate min and max values of data to define chart y-axis domain
//let minDomain = d3.min(data.map(d => d.values).flat().map(d => d.value)); //let minDomain = d3.min(data.map(d => d.values).flat().map(d => d.value));
...@@ -281,7 +281,7 @@ const makeIndicatorGraph = () => { ...@@ -281,7 +281,7 @@ const makeIndicatorGraph = () => {
// color axis labels // color axis labels
g.selectAll(".y.axis g.tick text") g.selectAll(".y.axis g.tick text")
.style("fill", "#b2b2b2"); // function (d,i) {return (i%2)?"red":"blue";}) .style("fill", "#b2b2b2"); // (d,i) => (i%2)?"red":"blue")
let title = selection.select(".title.label"); let title = selection.select(".title.label");
title.text(chart.title()) title.text(chart.title())
...@@ -323,8 +323,8 @@ const makeIndicatorGraph = () => { ...@@ -323,8 +323,8 @@ const makeIndicatorGraph = () => {
//.nice(d3.timeMonth) //.nice(d3.timeMonth)
.range([0, width - margin.left - margin.right - 30]) .range([0, width - margin.left - margin.right - 30])
.clamp(true); .clamp(true);
//yLine.domain(d3.extent(data, function(d) { return d[lineVariables[0]]; })) //yLine.domain(d3.extent(data, d => d[lineVariables[0]] ));
//yLine.domain([0, d3.max(data, function(d) { return d[lineVariables[0]]; })]).nice() //yLine.domain([0, d3.max(data, d => d[lineVariables[0]] )]).nice();
// Calculate min and max values of data to define chart y-axis domain // Calculate min and max values of data to define chart y-axis domain
//let minDomain = d3.min(data.map(d => d.values).flat().map(d => d.value)); //let minDomain = d3.min(data.map(d => d.values).flat().map(d => d.value));
...@@ -458,7 +458,7 @@ const makeIndicatorGraph = () => { ...@@ -458,7 +458,7 @@ const makeIndicatorGraph = () => {
let circles = g.select(".circles"), let circles = g.select(".circles"),
tooltip = d3.select(".tooltip"); tooltip = d3.select(".tooltip");
//tooltipFormat = d3.timeFormat("%b "%y"), //tooltipFormat = d3.timeFormat("%b "%y"),
//tooltipFormat = d3.format(",.2f") //tooltipFormat = d3.format(",.2f");
//tooltipFormat = d3.format(",.3s"); //tooltipFormat = d3.format(",.3s");
circles.selectAll("g") // using nested data, so need to make a g to contain stuff circles.selectAll("g") // using nested data, so need to make a g to contain stuff
......
...@@ -106,7 +106,7 @@ const setupDates = () => { ...@@ -106,7 +106,7 @@ const setupDates = () => {
d3.json(layersQuery).then(layers => { d3.json(layersQuery).then(layers => {
layers.forEach(layer => { layers.forEach(layer => {
dateArray.push(timeParse(layer.f_table_name)); // convert filenames to dates dateArray.push(timeParse(layer.f_table_name)); // convert filenames to dates
}) });
dateArray = dateArray.sort(sortInitialDateAscending); // order dates dateArray = dateArray.sort(sortInitialDateAscending); // order dates
dateMin = d3.min(dateArray); dateMin = d3.min(dateArray);
...@@ -199,7 +199,7 @@ const populateDates = (dates) => { // fill out date pickers with available dates ...@@ -199,7 +199,7 @@ const populateDates = (dates) => { // fill out date pickers with available dates
// hide initial screen and show map // hide initial screen and show map
$("#startHeader").remove(); $("#startHeader").remove();
$("#initial-backdrop").remove(); $("#initial-backdrop").remove();
$("#mainContainer")[0].style.setProperty("display", "flex", "important") $("#mainContainer")[0].style.setProperty("display", "flex", "important");
$("#mexmap").show(); $("#mexmap").show();
// When closing final-date, either setup or update map // When closing final-date, either setup or update map
...@@ -215,7 +215,7 @@ const populateDates = (dates) => { // fill out date pickers with available dates ...@@ -215,7 +215,7 @@ const populateDates = (dates) => { // fill out date pickers with available dates
$("#ui-datepicker-div").toggleClass("hide-calendar", $(el).is("[data-calendar=\"false\"]")); $("#ui-datepicker-div").toggleClass("hide-calendar", $(el).is("[data-calendar=\"false\"]"));
} }
}); });
}) });
} }
const setupMap = (dates) => { const setupMap = (dates) => {
...@@ -296,9 +296,9 @@ const setupMap = (dates) => { ...@@ -296,9 +296,9 @@ const setupMap = (dates) => {
}); });
const offsetGlobal = (center, zoom, refMap, tgtMap) => { const offsetGlobal = (center, zoom, refMap, tgtMap) => {
var refC = refMap.getContainer(); let refC = refMap.getContainer();
var tgtC = tgtMap.getContainer(); let tgtC = tgtMap.getContainer();
var pt = refMap.project(center, zoom) let pt = refMap.project(center, zoom)
.subtract([refC.offsetLeft, refC.offsetTop]) .subtract([refC.offsetLeft, refC.offsetTop])
.subtract(refMap.getSize().divideBy(2)) .subtract(refMap.getSize().divideBy(2))
.add([tgtC.offsetLeft, tgtC.offsetTop]) .add([tgtC.offsetLeft, tgtC.offsetTop])
...@@ -404,8 +404,8 @@ const populateMap = async (mapData) => { ...@@ -404,8 +404,8 @@ const populateMap = async (mapData) => {
}); });
glmap = L.mapboxGL({ glmap = L.mapboxGL({
accessToken: "no-token", "accessToken": "no-token",
style: { "style": {
"version": 8, "version": 8,
"sources": {}, "sources": {},
"layers": [] "layers": []
...@@ -420,7 +420,7 @@ const populateMap = async (mapData) => { ...@@ -420,7 +420,7 @@ const populateMap = async (mapData) => {
Object.keys(allTiles).forEach(layer => { Object.keys(allTiles).forEach(layer => {
if (layer == userFiles[0]) { if (layer == userFiles[0]) {
glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0.7) glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0.7);
} }
}); });
...@@ -444,7 +444,7 @@ const populateMap = async (mapData) => { ...@@ -444,7 +444,7 @@ const populateMap = async (mapData) => {
"Carto Light": cartoLightLayer, "Carto Light": cartoLightLayer,
"OpenStreetMap": osmLayer "OpenStreetMap": osmLayer
}; };
var overlays = { let overlays = {
"<span id=\"cuencaOverlay\">Agua en la cuenca del Grijalva</span>": timeLayer "<span id=\"cuencaOverlay\">Agua en la cuenca del Grijalva</span>": timeLayer
}; };
...@@ -475,7 +475,7 @@ const updateMap = (mapData) => { ...@@ -475,7 +475,7 @@ const updateMap = (mapData) => {
let newTile = mapboxLayer(monthYear); let newTile = mapboxLayer(monthYear);
glmap.getMapboxMap().addLayer(newTile); glmap.getMapboxMap().addLayer(newTile);
if (monthYear == userFiles[0]) { if (monthYear == userFiles[0]) {
glmap.getMapboxMap().setPaintProperty(monthYear, "fill-opacity", 0.7) glmap.getMapboxMap().setPaintProperty(monthYear, "fill-opacity", 0.7);
} }
} }
}); });
...@@ -502,7 +502,7 @@ const updateMap = (mapData) => { ...@@ -502,7 +502,7 @@ const updateMap = (mapData) => {
}); });
}); });
resolve({"map": map, "minIndicators": minIndicators, "maxIndicators": maxIndicators}); resolve({"map": map, "minIndicators": minIndicators, "maxIndicators": maxIndicators});
}) });
}).then( values => { // once we have new minmax values, style all tiles }).then( values => { // once we have new minmax values, style all tiles
let option = $("#indicatorSelect").val(), // option selected from dropdrown let option = $("#indicatorSelect").val(), // option selected from dropdrown
min = values.minIndicators, min = values.minIndicators,
...@@ -537,31 +537,17 @@ const updateCharts = async () => { ...@@ -537,31 +537,17 @@ const updateCharts = async () => {
// define MVT layer for given month table and all indicators // define MVT layer for given month table and all indicators
const mapboxLayer = (monthYear) => { const mapboxLayer = (monthYear) => {
let pbfLayer = { let pbfLayer = {
id: monthYear, "id": monthYear,
source: { "source": {
type: "vector", "type": "vector",
tiles: [`${baseUrl}/${monthYear}/mvt/{z}/{x}/{y}?geom_column=geom&columns=${indicators.join()}`], "tiles": [`${baseUrl}/${monthYear}/mvt/{z}/{x}/{y}?geom_column=geom&columns=${indicators.join()}`],
maxzoom: 19, "maxzoom": 19,
minzoom: 6 "minzoom": 6
}, },
"source-layer": monthYear, "source-layer": monthYear,
type: "fill", "type": "fill",
"paint": { "paint": {
"fill-opacity": 0, "fill-opacity": 0,
/*"fill-color": [
"interpolate",
["linear"],
["get", "df"],
1, "rgba(255, 0, 0, 0.5)", // red
1.3, "rgba(0, 255, 0, 0.5)", // green
]/*,
"fill-outline-color": [
"interpolate",
["linear"],
["get", "df"],
1, "rgba(255, 0, 0, 0.6)", // red
1.3, "rgba(0, 255, 0, 0.6)", // green
]*/
} }
} }
currentTiles[monthYear] = pbfLayer; currentTiles[monthYear] = pbfLayer;
...@@ -647,7 +633,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({ ...@@ -647,7 +633,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({
return; return;
} }
var time = this._timeDimension.getCurrentTime(); let time = this._timeDimension.getCurrentTime();
// get data for time // get data for time
let d = new Date(time), let d = new Date(time),
...@@ -668,7 +654,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({ ...@@ -668,7 +654,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({
//console.time("process"); //console.time("process");
//console.log("data for", monthYear); //console.log("data for", monthYear);
//console.log(currentTiles) //console.log(currentTiles);
Object.keys(allTiles).forEach(layer => { Object.keys(allTiles).forEach(layer => {
if (layer !== monthYear) { // hide all other months if (layer !== monthYear) { // hide all other months
glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0); glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0);
...@@ -701,7 +687,7 @@ $("#indicatorSelect").on("change", function() { ...@@ -701,7 +687,7 @@ $("#indicatorSelect").on("change", function() {
const styleTiles = (option, minIndicators, maxIndicators) => { const styleTiles = (option, minIndicators, maxIndicators) => {
// define color scale domain based on min-max values for selected indicator // define color scale domain based on min-max values for selected indicator
let domain = [minIndicators[option], maxIndicators[option]]; let domain = [minIndicators[option], maxIndicators[option]];
//console.log(domain) //console.log(domain);
scale = chroma.scale("PuBu").padding([0.5, 0]).domain(domain).classes(5); scale = chroma.scale("PuBu").padding([0.5, 0]).domain(domain).classes(5);
Object.keys(currentTiles).forEach(layer => { Object.keys(currentTiles).forEach(layer => {
let color = [ let color = [
...@@ -726,7 +712,7 @@ legend.onAdd = () => { ...@@ -726,7 +712,7 @@ legend.onAdd = () => {
let optionIndex = indicators.indexOf(option); let optionIndex = indicators.indexOf(option);
let legendText = indicatorsUnits[optionIndex] == "" ? indicatorsNames[optionIndex] : let legendText = indicatorsUnits[optionIndex] == "" ? indicatorsNames[optionIndex] :
`${indicatorsNames[optionIndex]} (${indicatorsUnits[optionIndex]})`; `${indicatorsNames[optionIndex]} (${indicatorsUnits[optionIndex]})`;
var html = `<h6>${legendText}</h6><ul>`; let html = `<h6>${legendText}</h6><ul>`;
let classes = scale.classes(); let classes = scale.classes();
classes.forEach( (c, idx, array) => { classes.forEach( (c, idx, array) => {
if (idx != array.length - 1) { if (idx != array.length - 1) {
......
...@@ -5,28 +5,11 @@ ...@@ -5,28 +5,11 @@
* August-September 2019 * August-September 2019
*/ */
/* global baseFileSize, formatBytes, Promise, omnivore, JSZip, map, glmap, layerControl, updateCharts, baseUrl */ /* global Promise, omnivore, JSZip, map, glmap, layerControl, updateCharts, baseUrl */
/* exported makeBaseMap, baseLayerPromises, drawnItems */ /* exported makeBaseMap, baseLayerPromises, drawnItems */
/* Lines related to displaying loading bar are commented */ let baseLayerPromises = [],
drawnItems;
let baseLayerPromises = [];
/* baseSize = 0,
baseDisplaySize,
baseLoadedSize = 0,
baseLoadedDisplaySize,
baseLayerCounter = 0,
currentBaseLayer = 1;*/
let drawnItems;
/*Object.keys(baseFileSize).forEach((name) => {
if (name.split(".")[1] == "zip") {
baseSize += parseFloat(baseFileSize[name].size); // file size to load for zipped base layers
baseDisplaySize = formatBytes(baseSize, 2); // size in pretty units
baseLayerCounter++;
}
});*/
// function to read compressed json and create a leaflet layer // function to read compressed json and create a leaflet layer
const zip2Lyr = (zipFile, layerName, layerTemplate) => { const zip2Lyr = (zipFile, layerName, layerTemplate) => {
...@@ -49,17 +32,6 @@ const zip2Lyr = (zipFile, layerName, layerTemplate) => { ...@@ -49,17 +32,6 @@ const zip2Lyr = (zipFile, layerName, layerTemplate) => {
.then(([file, type]) => { .then(([file, type]) => {
file.async("string").then( file.async("string").then(
function success(text) { // 5) display the result function success(text) { // 5) display the result
/*let baseFile = zipFile.split("/")[3];
¬baseLoadedSize += parseFloat(baseFileSize[baseFile].size); // cumulative loaded size
baseLoadedDisplaySize = formatBytes(baseLoadedSize); // in pretty units
let baseBarWidth = (baseLoadedSize/baseSize*100);*/
/*currentBaseLayer++;
let baseFiles = currentBaseLayer <= baseLayerCounter ? currentBaseLayer : baseLayerCounter;
$("#basemap-fileLoad").html("Cargando capa " + baseFiles + " de " + baseLayerCounter + "<br>" +
"<span class=\"progress\"><span id=\"baseBar\" class=\"progress-bar progress-bar-striped progress-bar-animated\" role=\"progressbar\" style=\"width: " + baseBarWidth + "%;\" aria-valuenow=\"" + baseBarWidth + "\" aria-valuemin=\"0\" aria-valuemax=\"100\"></span>" +
"<span class=\"justify-content-center d-flex position-absolute w-100\">" + baseLoadedDisplaySize + "/" + baseDisplaySize + "</span></span>");
*/
if (type == "json") { if (type == "json") {
layerTemplate.addData(JSON.parse(text)); layerTemplate.addData(JSON.parse(text));
} else if (type == "topojson") { } else if (type == "topojson") {
...@@ -119,7 +91,7 @@ const getCuencasColor = s => { ...@@ -119,7 +91,7 @@ const getCuencasColor = s => {
"rgba(168,56,0,0.3)"; "rgba(168,56,0,0.3)";
} }
let pistasaereas, autobuses, supermercados, bancos, agebsbypop, agebsbydens, agricolaoi, agricolapv, escuelas, hospitales, hoteles, subcuencas, tuxtlaVH, zms; let pistasaereas, autobuses, supermercados, bancos, agebsbypop, agebsbydens, escuelas, hospitales, hoteles, subcuencas, tuxtlaVH, zms;
// *** WMS INEGI *** // *** WMS INEGI ***
// AEROPUERTOS // AEROPUERTOS
...@@ -127,7 +99,6 @@ let layer_aeropuertos = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel ...@@ -127,7 +99,6 @@ let layer_aeropuertos = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tunnel
layers: "c201", layers: "c201",
format: "image/svg+xml", format: "image/svg+xml",
transparent: true, transparent: true,
//pane: "pane_aeropuertosypistas",
attribution: "INEGI 2019", attribution: "INEGI 2019",
minZoom: 9 minZoom: 9
}); });
...@@ -195,26 +166,19 @@ let layer_limiteMunicipal = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tu ...@@ -195,26 +166,19 @@ let layer_limiteMunicipal = new L.tileLayer.wms("http://gaia.inegi.org.mx/NLB/tu
// *** FIN WMS INEGI *** // *** FIN WMS INEGI ***
let layer_pistasaereas = new L.geoJson(null, { let layer_pistasaereas = new L.geoJson(null, {
attribution: "", attribution: "",
//pane: "pane_aeropuertosypistas",
minZoom: 9, minZoom: 9,
//onEachFeature: pop_escuelas,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let avionMarker = L.BeautifyIcon.icon({ let avionMarker = L.BeautifyIcon.icon({
icon: "plane", icon: "plane",
iconSize: [0, 0], iconSize: [0, 0],
iconAnchor: [7, 10], iconAnchor: [7, 10],
iconShape: "", //"circle", iconShape: "",
popupAnchor: [0, 0], popupAnchor: [0, 0],
innerIconStyle: "font-size: 15px;", innerIconStyle: "font-size: 15px;",
html: "<span class=\"fa-stack\"><i class=\"fas fa-plane fa-stack-1x\" style=\"color:#fada5e;\"></i></span>", html: "<span class=\"fa-stack\"><i class=\"fas fa-plane fa-stack-1x\" style=\"color:#fada5e;\"></i></span>",
borderWidth: 0, borderWidth: 0,
borderColor: "transparent", borderColor: "transparent",
backgroundColor: "transparent" //, backgroundColor: "transparent",
// textColor: "#C0C0C0"
}); });
return new L.Marker(latlng, { return new L.Marker(latlng, {
icon: avionMarker icon: avionMarker
...@@ -230,24 +194,18 @@ let aeropuertosypistasaereas = new L.layerGroup([layer_aeropuertos, layer_pistas ...@@ -230,24 +194,18 @@ let aeropuertosypistasaereas = new L.layerGroup([layer_aeropuertos, layer_pistas
let layer_autobuses = new L.geoJson(null, { let layer_autobuses = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_autobuses", pane: "pane_autobuses",
//onEachFeature: pop_escuelas,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let busMarker = L.BeautifyIcon.icon({ let busMarker = L.BeautifyIcon.icon({
icon: "bus1", icon: "bus1",
iconSize: [0, 0], iconSize: [0, 0],
iconAnchor: [7, 10], iconAnchor: [7, 10],
iconShape: "", //"circle", iconShape: "",
popupAnchor: [0, 0], popupAnchor: [0, 0],
innerIconStyle: "font-size: 8px;", innerIconStyle: "font-size: 8px;",
html: "<span class=\"fa-stack\"><i class=\"fas fa-bus1 fa-stack-1x\" style=\"color:#fda50f;\"></i></span>", html: "<span class=\"fa-stack\"><i class=\"fas fa-bus1 fa-stack-1x\" style=\"color:#fda50f;\"></i></span>",
borderWidth: 0, borderWidth: 0,
borderColor: "transparent", borderColor: "transparent",
backgroundColor: "transparent" //, backgroundColor: "transparent"
// textColor: "#C0C0C0"
}); });
return new L.Marker(latlng, { return new L.Marker(latlng, {
icon: busMarker icon: busMarker
...@@ -258,12 +216,7 @@ let layer_autobuses = new L.geoJson(null, { ...@@ -258,12 +216,7 @@ let layer_autobuses = new L.geoJson(null, {
let layer_supermercados = new L.geoJson(null, { let layer_supermercados = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_supermercados", pane: "pane_supermercados",
//onEachFeature: pop_escuelas,
pointToLayer: (feature, latlng) => { pointToLayer: (feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let shoppingMarker = L.BeautifyIcon.icon({ let shoppingMarker = L.BeautifyIcon.icon({
icon: "shopping-cart", icon: "shopping-cart",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -271,11 +224,10 @@ let layer_supermercados = new L.geoJson(null, { ...@@ -271,11 +224,10 @@ let layer_supermercados = new L.geoJson(null, {
iconShape: "circle", iconShape: "circle",
popupAnchor: [0, 0], popupAnchor: [0, 0],
innerIconStyle: "font-size: 15px;", innerIconStyle: "font-size: 15px;",
// html: "<span class=\"fa-stack\"><i class=\"fas fa-shopping-cart fa-stack-1x\" style=\"color:#808080;\"></i></span>",
borderWidth: 0, borderWidth: 0,
borderColor: "transparent", borderColor: "transparent",
backgroundColor: "transparent", backgroundColor: "transparent",
textColor: getCommerceColor(feature.properties["nombre_act"]) //textColor: "#C0C0C0" textColor: getCommerceColor(feature.properties["nombre_act"])
}); });
return new L.Marker(latlng, { return new L.Marker(latlng, {
icon: shoppingMarker icon: shoppingMarker
...@@ -286,17 +238,12 @@ let layer_supermercados = new L.geoJson(null, { ...@@ -286,17 +238,12 @@ let layer_supermercados = new L.geoJson(null, {
let layer_bancos = new L.geoJson(null, { let layer_bancos = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_bancos", pane: "pane_bancos",
//onEachFeature: pop_escuelas,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let bancosMarker = L.BeautifyIcon.icon({ let bancosMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
iconAnchor: [7, 10], iconAnchor: [7, 10],
iconShape: "", //"circle", iconShape: "",
popupAnchor: [0, 0], popupAnchor: [0, 0],
innerIconStyle: "font-size: 12px;", innerIconStyle: "font-size: 12px;",
html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:#05ac72;\"></i><i class =\"fas fa-dollar fa-stack-1x fa-inverse\"></i></span>", html: "<span class=\"fa-stack\"><i class=\"fas fa-desechos fa-stack-1x\" style=\"color:#05ac72;\"></i><i class =\"fas fa-dollar fa-stack-1x fa-inverse\"></i></span>",
...@@ -314,12 +261,7 @@ let layer_bancos = new L.geoJson(null, { ...@@ -314,12 +261,7 @@ let layer_bancos = new L.geoJson(null, {
let layer_escuelas = new L.geoJson(null, { let layer_escuelas = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_escuelas", pane: "pane_escuelas",
//onEachFeature: pop_escuelas,
pointToLayer: (feature, latlng) => { pointToLayer: (feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let escuelaMarker = L.BeautifyIcon.icon({ let escuelaMarker = L.BeautifyIcon.icon({
icon: "escuela", icon: "escuela",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -341,12 +283,7 @@ let layer_escuelas = new L.geoJson(null, { ...@@ -341,12 +283,7 @@ let layer_escuelas = new L.geoJson(null, {
let layer_hospitales = new L.geoJson(null, { let layer_hospitales = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_hospitales", pane: "pane_hospitales",
//onEachFeature: pop_hospitales,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let hospitalMarker = L.BeautifyIcon.icon({ let hospitalMarker = L.BeautifyIcon.icon({
icon: "desechos", icon: "desechos",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -369,12 +306,7 @@ let layer_hospitales = new L.geoJson(null, { ...@@ -369,12 +306,7 @@ let layer_hospitales = new L.geoJson(null, {
let layer_hoteles = new L.geoJson(null, { let layer_hoteles = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_hoteles", pane: "pane_hoteles",
//onEachFeature: pop_hoteles,
pointToLayer: (_feature, latlng) => { pointToLayer: (_feature, latlng) => {
// let context = {
// feature: feature,
// variables: {}
// };
let hotelMarker = L.BeautifyIcon.icon({ let hotelMarker = L.BeautifyIcon.icon({
icon: "bed", icon: "bed",
iconSize: [0, 0], iconSize: [0, 0],
...@@ -398,7 +330,6 @@ const style_cuencas = feature => { ...@@ -398,7 +330,6 @@ const style_cuencas = feature => {
pane: "pane_agebsbydens", pane: "pane_agebsbydens",
opacity: 1, opacity: 1,
color: "rgba(168,0,0,0.3)", color: "rgba(168,0,0,0.3)",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 1.0, weight: 1.0,
...@@ -410,7 +341,6 @@ const style_cuencas = feature => { ...@@ -410,7 +341,6 @@ const style_cuencas = feature => {
let layer_cuencas = new L.geoJson(null, { let layer_cuencas = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_cuencas", pane: "pane_cuencas",
//onEachFeature: pop_cuencas,
style: style_cuencas style: style_cuencas
}); });
...@@ -430,7 +360,6 @@ const style_limZMs = () => { ...@@ -430,7 +360,6 @@ const style_limZMs = () => {
let layer_limZMs = new L.geoJson(null, { let layer_limZMs = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_limZMs", pane: "pane_limZMs",
//onEachFeature: pop_limZMs,
style: style_limZMs style: style_limZMs
}); });
...@@ -449,7 +378,6 @@ const style_ZMs = feature => { ...@@ -449,7 +378,6 @@ const style_ZMs = feature => {
fillOpacity: 1, fillOpacity: 1,
fillColor: "rgba(139,60,0,0.6)" fillColor: "rgba(139,60,0,0.6)"
} }
//break;
case "Villahermosa": case "Villahermosa":
return { return {
pane: "pane_ZMs", pane: "pane_ZMs",
...@@ -463,14 +391,12 @@ const style_ZMs = feature => { ...@@ -463,14 +391,12 @@ const style_ZMs = feature => {
fillOpacity: 1, fillOpacity: 1,
fillColor: "rgba(207,152,62,0.6)" fillColor: "rgba(207,152,62,0.6)"
} }
//break;
} }
} }
let layer_ZMs = new L.geoJson(null, { let layer_ZMs = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_ZMs", pane: "pane_ZMs",
//onEachFeature: pop_ZMs,
style: style_ZMs style: style_ZMs
}); });
...@@ -479,7 +405,6 @@ const style_agebsbypop = feature => { ...@@ -479,7 +405,6 @@ const style_agebsbypop = feature => {
pane: "pane_agebsbypop", pane: "pane_agebsbypop",
opacity: .6, opacity: .6,
color: "#4d4d4d", color: "#4d4d4d",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 0.5, //1.0, weight: 0.5, //1.0,
...@@ -492,7 +417,6 @@ const style_agebsbypop = feature => { ...@@ -492,7 +417,6 @@ const style_agebsbypop = feature => {
let layer_agebsbypop = new L.geoJson(null, { let layer_agebsbypop = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_agebsbypop", pane: "pane_agebsbypop",
//onEachFeature: pop_ANPs,
style: style_agebsbypop style: style_agebsbypop
}); });
...@@ -501,7 +425,6 @@ const style_agebsbydens = feature => { ...@@ -501,7 +425,6 @@ const style_agebsbydens = feature => {
pane: "pane_agebsbydens", pane: "pane_agebsbydens",
opacity: .6, opacity: .6,
color: "#4d4d4d", color: "#4d4d4d",
//dashArray: "3 2",
lineCap: "butt", lineCap: "butt",
lineJoin: "miter", lineJoin: "miter",
weight: 0.5, //1.0, weight: 0.5, //1.0,
...@@ -514,7 +437,6 @@ const style_agebsbydens = feature => { ...@@ -514,7 +437,6 @@ const style_agebsbydens = feature => {
let layer_agebsbydens = new L.geoJson(null, { let layer_agebsbydens = new L.geoJson(null, {
attribution: "", attribution: "",
pane: "pane_agebsbydens", pane: "pane_agebsbydens",
//onEachFeature: pop_ANPs,
style: style_agebsbydens style: style_agebsbydens
}); });
...@@ -656,11 +578,6 @@ const makeBaseMap = () => { ...@@ -656,11 +578,6 @@ const makeBaseMap = () => {
createPane("pane_agebsbypop", 421); createPane("pane_agebsbypop", 421);
createPane("pane_agebsbydens", 422); createPane("pane_agebsbydens", 422);
/*$("#basemap-fileLoad").html("Cargando capa 1 de " + baseLayerCounter + "<br>" +
"<span class=\"progress\"><span id=\"baseBar\" class=\"progress-bar progress-bar-striped progress-bar-animated\" role=\"progressbar\" style=\"width: 0%;\" aria-valuenow=\"0\" aria-valuemin=\"0\" aria-valuemax=\"100\"></span>" +
"<span class=\"justify-content-center d-flex position-absolute w-100\">0/" + baseDisplaySize + "</span></span>");*/
layerControl.addOverlay(layer_nombresWB, "Nombres cuerpos de agua"); layerControl.addOverlay(layer_nombresWB, "Nombres cuerpos de agua");
zip2Lyr("../grijalva/data/escuelas.zip", escuelas, layer_escuelas); zip2Lyr("../grijalva/data/escuelas.zip", escuelas, layer_escuelas);
layerControl.addOverlay(layer_RedNacionalCaminos, "Red Nacional de Caminos <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c200\" alt=\"Red Nacional de Caminos\"/>"); layerControl.addOverlay(layer_RedNacionalCaminos, "Red Nacional de Caminos <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"http://gaia.inegi.org.mx/NLB/tunnel/wms/mdm6wms?map=/opt/map/mdm60/mdm61leyendaprueba.map&Request=GetLegendGraphic&format=image/png&Version=1.1.1&Service=WMS&LAYER=c200\" alt=\"Red Nacional de Caminos\"/>");
......
...@@ -106,7 +106,7 @@ const setupDates = () => { ...@@ -106,7 +106,7 @@ const setupDates = () => {
d3.json(layersQuery).then(layers => { d3.json(layersQuery).then(layers => {
layers.forEach(layer => { layers.forEach(layer => {
dateArray.push(timeParse(layer.f_table_name)); // convert filenames to dates dateArray.push(timeParse(layer.f_table_name)); // convert filenames to dates
}) });
dateArray = dateArray.sort(sortInitialDateAscending); // order dates dateArray = dateArray.sort(sortInitialDateAscending); // order dates
dateMin = d3.min(dateArray); dateMin = d3.min(dateArray);
...@@ -199,7 +199,7 @@ const populateDates = (dates) => { // fill out date pickers with available dates ...@@ -199,7 +199,7 @@ const populateDates = (dates) => { // fill out date pickers with available dates
// hide initial screen and show map // hide initial screen and show map
$("#startHeader").remove(); $("#startHeader").remove();
$("#initial-backdrop").remove(); $("#initial-backdrop").remove();
$("#mainContainer")[0].style.setProperty("display", "flex", "important") $("#mainContainer")[0].style.setProperty("display", "flex", "important");
$("#mexmap").show(); $("#mexmap").show();
// When closing final-date, either setup or update map // When closing final-date, either setup or update map
...@@ -215,7 +215,7 @@ const populateDates = (dates) => { // fill out date pickers with available dates ...@@ -215,7 +215,7 @@ const populateDates = (dates) => { // fill out date pickers with available dates
$("#ui-datepicker-div").toggleClass("hide-calendar", $(el).is("[data-calendar=\"false\"]")); $("#ui-datepicker-div").toggleClass("hide-calendar", $(el).is("[data-calendar=\"false\"]"));
} }
}); });
}) });
} }
const setupMap = (dates) => { const setupMap = (dates) => {
...@@ -296,9 +296,9 @@ const setupMap = (dates) => { ...@@ -296,9 +296,9 @@ const setupMap = (dates) => {
}); });
const offsetGlobal = (center, zoom, refMap, tgtMap) => { const offsetGlobal = (center, zoom, refMap, tgtMap) => {
var refC = refMap.getContainer(); let refC = refMap.getContainer();
var tgtC = tgtMap.getContainer(); let tgtC = tgtMap.getContainer();
var pt = refMap.project(center, zoom) let pt = refMap.project(center, zoom)
.subtract([refC.offsetLeft, refC.offsetTop]) .subtract([refC.offsetLeft, refC.offsetTop])
.subtract(refMap.getSize().divideBy(2)) .subtract(refMap.getSize().divideBy(2))
.add([tgtC.offsetLeft, tgtC.offsetTop]) .add([tgtC.offsetLeft, tgtC.offsetTop])
...@@ -420,7 +420,7 @@ const populateMap = async (mapData) => { ...@@ -420,7 +420,7 @@ const populateMap = async (mapData) => {
Object.keys(allTiles).forEach(layer => { Object.keys(allTiles).forEach(layer => {
if (layer == userFiles[0]) { if (layer == userFiles[0]) {
glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0.7) glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0.7);
} }
}); });
...@@ -444,7 +444,7 @@ const populateMap = async (mapData) => { ...@@ -444,7 +444,7 @@ const populateMap = async (mapData) => {
"Carto Light": cartoLightLayer, "Carto Light": cartoLightLayer,
"OpenStreetMap": osmLayer "OpenStreetMap": osmLayer
}; };
var overlays = { let overlays = {
"<span id=\"cuencaOverlay\">Agua en la cuenca del Grijalva</span>": timeLayer "<span id=\"cuencaOverlay\">Agua en la cuenca del Grijalva</span>": timeLayer
}; };
...@@ -475,7 +475,7 @@ const updateMap = (mapData) => { ...@@ -475,7 +475,7 @@ const updateMap = (mapData) => {
let newTile = mapboxLayer(monthYear); let newTile = mapboxLayer(monthYear);
glmap.getMapboxMap().addLayer(newTile); glmap.getMapboxMap().addLayer(newTile);
if (monthYear == userFiles[0]) { if (monthYear == userFiles[0]) {
glmap.getMapboxMap().setPaintProperty(monthYear, "fill-opacity", 0.7) glmap.getMapboxMap().setPaintProperty(monthYear, "fill-opacity", 0.7);
} }
} }
}); });
...@@ -502,7 +502,7 @@ const updateMap = (mapData) => { ...@@ -502,7 +502,7 @@ const updateMap = (mapData) => {
}); });
}); });
resolve({"map": map, "minIndicators": minIndicators, "maxIndicators": maxIndicators}); resolve({"map": map, "minIndicators": minIndicators, "maxIndicators": maxIndicators});
}) });
}).then( values => { // once we have new minmax values, style all tiles }).then( values => { // once we have new minmax values, style all tiles
let option = $("#indicatorSelect").val(), // option selected from dropdrown let option = $("#indicatorSelect").val(), // option selected from dropdrown
min = values.minIndicators, min = values.minIndicators,
...@@ -547,21 +547,7 @@ const mapboxLayer = (monthYear) => { ...@@ -547,21 +547,7 @@ const mapboxLayer = (monthYear) => {
"source-layer": monthYear, "source-layer": monthYear,
type: "fill", type: "fill",
"paint": { "paint": {
"fill-opacity": 0, "fill-opacity": 0
/*"fill-color": [
"interpolate",
["linear"],
["get", "df"],
1, "rgba(255, 0, 0, 0.5)", // red
1.3, "rgba(0, 255, 0, 0.5)", // green
]/*,
"fill-outline-color": [
"interpolate",
["linear"],
["get", "df"],
1, "rgba(255, 0, 0, 0.6)", // red
1.3, "rgba(0, 255, 0, 0.6)", // green
]*/
} }
} }
currentTiles[monthYear] = pbfLayer; currentTiles[monthYear] = pbfLayer;
...@@ -647,7 +633,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({ ...@@ -647,7 +633,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({
return; return;
} }
var time = this._timeDimension.getCurrentTime(); let time = this._timeDimension.getCurrentTime();
// get data for time // get data for time
let d = new Date(time), let d = new Date(time),
...@@ -668,7 +654,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({ ...@@ -668,7 +654,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({
//console.time("process"); //console.time("process");
//console.log("data for", monthYear); //console.log("data for", monthYear);
//console.log(currentTiles) //console.log(currentTiles);
Object.keys(allTiles).forEach(layer => { Object.keys(allTiles).forEach(layer => {
if (layer !== monthYear) { // hide all other months if (layer !== monthYear) { // hide all other months
glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0); glmap.getMapboxMap().setPaintProperty(layer, "fill-opacity", 0);
...@@ -701,7 +687,7 @@ $("#indicatorSelect").on("change", function() { ...@@ -701,7 +687,7 @@ $("#indicatorSelect").on("change", function() {
const styleTiles = (option, minIndicators, maxIndicators) => { const styleTiles = (option, minIndicators, maxIndicators) => {
// define color scale domain based on min-max values for selected indicator // define color scale domain based on min-max values for selected indicator
let domain = [minIndicators[option], maxIndicators[option]]; let domain = [minIndicators[option], maxIndicators[option]];
//console.log(domain) //console.log(domain);
scale = chroma.scale("PuBu").padding([0.5, 0]).domain(domain).classes(5); scale = chroma.scale("PuBu").padding([0.5, 0]).domain(domain).classes(5);
Object.keys(currentTiles).forEach(layer => { Object.keys(currentTiles).forEach(layer => {
let color = [ let color = [
...@@ -726,7 +712,7 @@ legend.onAdd = () => { ...@@ -726,7 +712,7 @@ legend.onAdd = () => {
let optionIndex = indicators.indexOf(option); let optionIndex = indicators.indexOf(option);
let legendText = indicatorsUnits[optionIndex] == "" ? indicatorsNames[optionIndex] : let legendText = indicatorsUnits[optionIndex] == "" ? indicatorsNames[optionIndex] :
`${indicatorsNames[optionIndex]} (${indicatorsUnits[optionIndex]})`; `${indicatorsNames[optionIndex]} (${indicatorsUnits[optionIndex]})`;
var html = `<h6>${legendText}</h6><ul>`; let html = `<h6>${legendText}</h6><ul>`;
let classes = scale.classes(); let classes = scale.classes();
classes.forEach( (c, idx, array) => { classes.forEach( (c, idx, array) => {
if (idx != array.length - 1) { if (idx != array.length - 1) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment