Ronsoco/js/Metodos.js
2019-11-06 17:19:21 -03:00

860 lines
24 KiB
JavaScript

var Grafico;
var G_viento;
var G_vientoKm;
var G_presion;
var G_uv;
var G_iluminancia;
//PERMISOS DEL NAVEGADOR ACTUALES SOBRE GEOLOCALIZACION
function Obtener_Permisos_del_Navegador_GPS() {
try {
navigator.permissions.query({ name: "geolocation" }).then(function (result) {
switch (result.state) {
case "granted":
console.log("Geolocalizacion permitida.");
ObtenerGPS_Navegador();
break;
case "prompt":
console.log("Geolocalizacion en preguntar. Se lanza modal.");
$("#ventanaModalGps").modal("show");
break;
case "denied":
console.log("Geolocalizacion denegada.");
var mesg = " Su geolocalización esta denegada!.";
API_EMA.LeerRegistroEstacion(API_EMA.estaciones[0].id_estacion, true);
$("#modal_titulo").html("Permiso de Geolocalizacion Denegada");
$("#modal_cuerpo").html(
"Su Navegador tiene el permiso de Geolocalizacion denegado para este sitio.<br> Si lo activa, podemos brindarle una mejor experiencia, en caso que no lo desee, tambien lo entendemos y le sugerimos que ignore esta advertencia."
);
$("#modal_botones").html("");
$.notify("Geolocalización del navegador denegada!.", {
position: "right bottom",
className: "warn",
autoHideDelay: 5000,
autoHide: true,
clickToHide: true
});
$(document).on("click", ".notifyjs-corner", function () {
//RESPONDE NO
$("#ventanaModalGps").modal("show");
$(this).trigger("notify-hide");
});
break;
default:
ObtenerGPS_Navegador();
}
});
} catch (error) {
console.log("No pudo consultar los permisos");
ErrorObtiendoGPS("Imposible");
}
}
//POSICION ACTUAL DEL NAVEGADOR
function ObtenerGPS_Navegador() {
if (getCookie("estacion_seleccionada") == null) {
console.log("No hay seleccionada en cookie. Busca la mas cercana en linea.");
navigator.geolocation.getCurrentPosition(
Estacion_Mas_Cercana_GeoDistancia,
ErrorObtiendoGPS,
{ enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }
);
} else {
if(getCookie("estado_estacion")=="En línea"){
console.log("Estacion registrada en cookie y en linea.");
API_EMA.distancia = getCookie("estacion_distancia");
API_EMA.LeerRegistroEstacion(getCookie("estacion_seleccionada"), true);
}
else{
// que busque la mas cercana en linea
console.log("Estacion en cookie Fuera de linea. Busca la mas cercana en linea...");
$.notify("Buscamos la mas cercana a ella!.", {
position: "right bottom",
className: "success",
autoHideDelay: 5000,
autoHide: true,
clickToHide: true
});
$.notify("La estación preseleccionada se encuentra OFFLINE :(.", {
position: "right bottom",
className: "info",
autoHideDelay: 5000,
autoHide: true,
clickToHide: true
});
navigator.geolocation.getCurrentPosition(
Estacion_Mas_Cercana_GeoDistancia,
ErrorObtiendoGPS,
{ enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }
);
}
}
}
//DISTANCIA ENTRE LAS ESTACIONES GEOPOSICIONES
function Una_Estacion_GeoDistancia(position) {
console.log("Selecciono una estacion del Menu, busca distancia.");
var estacionMenuId = getCookie("MenuEstacionSeleccion");
Latitud_navegador = position.coords.latitude;
Longitud_navegador = position.coords.longitude;
//console.log("GPS_Navegador: "+ Latitud_navegador +","+Longitud_navegador );
var Bandera = false;
var lon2;
var lat2;
var Estacion;
var R;
var dLat;
var dLong;
var a;
var c;
var dist;
API_EMA.estaciones.forEach(function (registro) {
if (registro.id_estacion == estacionMenuId)
{ Bandera = true;
Estado=registro.estado;
lon2 = registro.longitud;
lat2 = registro.latitud;
Estacion = registro.id_estacion;
rad = function (x) {return (x * Math.PI) / 180;};
R = 6378.137; //Radio de la tierra en km
dLat = rad(lat2 - Latitud_navegador);
dLong = rad(lon2 - Longitud_navegador);
a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(Latitud_navegador)) *
Math.cos(rad(lat2)) *
Math.sin(dLong / 2) *
Math.sin(dLong / 2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
dist = R * c;
dist = dist.toFixed(1); //Retorna un decimales
// console.log("Distancia: "+dist);
API_EMA.distancia = dist;
setCookie("estacion_seleccionada", Estacion);
setCookie("estacion_distancia", dist);
setCookie("estado_estacion", Estado);
API_EMA.LeerRegistroEstacion(Estacion, true);
}
});
if(!Bandera){console.log("No encontro la distancia, de la estacion seleccionada.");
setCookie("estacion_distancia", " - ");
setCookie("estado_estacion", "S/D");
setCookie("estacion_seleccionada", estacionMenuId);
API_EMA.distancia = " - ";
API_EMA.LeerRegistroEstacion(estacionMenuId, true);
}
}
//DISTANCIA ENTRE LAS ESTACIONES GEOPOSICIONES
function Estacion_Mas_Cercana_GeoDistancia(position) {
Latitud_navegador = position.coords.latitude;
Longitud_navegador = position.coords.longitude;
var DistanciaMenor = 9999999;
var Bandera = false;
var EstacionMasCercana;
var EstadoMenor;
var Estado;
var lon2;
var lat2;
var Estacion;
var R;
var dLat;
var dLong;
var a;
var c;
var dist;
API_EMA.estaciones.forEach(function (registro) {
lon2 = registro.longitud;
lat2 = registro.latitud;
Estacion = registro.id_estacion;
Estado = registro.estado;
/*En línea*/
if (Estado=="En línea") {
Bandera = true;
if (Latitud_navegador != 0 && Longitud_navegador != 0) {
if (Latitud_navegador == lat2 && Longitud_navegador == lon2) {
DistanciaMenor = 0;
EstacionMasCercana = Estacion;
} else {
rad = function (x) {
return (x * Math.PI) / 180;
};
R = 6378.137; //Radio de la tierra en km
dLat = rad(lat2 - Latitud_navegador);
dLong = rad(lon2 - Longitud_navegador);
a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(Latitud_navegador)) *
Math.cos(rad(lat2)) *
Math.sin(dLong / 2) *
Math.sin(dLong / 2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
dist = R * c;
dist = dist.toFixed(1); //Retorna un decimales
dist = parseFloat(dist);
if (DistanciaMenor > dist) {
DistanciaMenor = dist;
EstacionMasCercana = Estacion;
EstadoMenor = Estado;
}
}
}
}
});
if(!Bandera)
{ // Si no encuentra ninguna en linea, cercana.
console.log("No hay estaciones en linea en el sistema. Se pone la primera.");
setCookie("estacion_distancia", " - ");
setCookie("estado_estacion", API_EMA.estaciones[0].estado);
setCookie("estacion_seleccionada", API_EMA.estaciones[0].id_estacion);
API_EMA.distancia = " - ";
API_EMA.LeerRegistroEstacion(API_EMA.estaciones[0].id_estacion, true);
}else{
// En linea, mas cercana.
API_EMA.distancia = DistanciaMenor;
setCookie("estacion_seleccionada", EstacionMasCercana);
setCookie("estacion_distancia", DistanciaMenor);
setCookie("estado_estacion", EstadoMenor);
API_EMA.LeerRegistroEstacion(EstacionMasCercana, true);
}
}
function ErrorObtiendoGPS(err) {
$("#myModal").modal("show");
if(getCookie("MenuEstacionSeleccion") != null){
API_EMA.estaciones.forEach(function (registro) {
if (registro.id_estacion == getCookie("MenuEstacionSeleccion"))
{
console.log("Sin Geolocalización y por menu seleccionada.");
setCookie("estacion_distancia", "S/D");
setCookie("estado_estacion", registro.estado);
setCookie("estacion_seleccionada", registro.id_estacion);
API_EMA.distancia = " - ";
API_EMA.LeerRegistroEstacion(registro.id_estacion, true);
}
});
}else{
console.log(err.message);
console.log("Se carga una por defecto: " + API_EMA.estaciones[0].id_estacion);
API_EMA.LeerRegistroEstacion(API_EMA.estaciones[0].id_estacion, true);
}
}
// GRAFICO VIENTOS
function ActualizarGraficos() {
G_viento.value = API_EMA.observaciones[0].viento_direccion;
G_vientoKm.value = API_EMA.observaciones[0].viento_rafagas;
G_presion.value = API_EMA.observaciones[0].presion_absoluta;
G_uv.value = API_EMA.observaciones[0].luxer_uv;
G_iluminancia.value =
parseFloat(API_EMA.observaciones[0].luxer_intencidad);
}
// GRAFICO PRINCIPAL
function Mostrar_Graficos() {
API_EMA.grafico = false;
// GRAFICO DEL TIEMPO CHARTJS
//Se genera el grafico
var labels = API_EMA.estadisticas.map(function (e) {
return moment(e.hora).format("DD/MM/YYYY H") + ":00";
});
var humedadMax = API_EMA.estadisticas.map(function (e) {
return e.humedad_externa_max;
});
var humedadMin = API_EMA.estadisticas.map(function (e) {
return e.humedad_externa_min;
});
var TempMax = API_EMA.estadisticas.map(function (e) {
return e.temperatura_externa_max;
});
var TemMin = API_EMA.estadisticas.map(function (e) {
return e.temperatura_externa_min;
});
var LluviaMax = API_EMA.estadisticas.map(function (e) {
return e.lluvia_acumulado_hora_max;
});
var VientoMax = API_EMA.estadisticas.map(function (e) {
return e.viento_velocidad_max;
});
var LuxerMax = API_EMA.estadisticas.map(function (e) {
return e.luxer_intencidad_max || 0;
});
var LuxerMin = API_EMA.estadisticas.map(function (e) {
return e.luxer_intencidad_min || 0;
});
var UVMax = API_EMA.estadisticas.map(function (e) {
return e.luxer_uv_max || 0;
});
var UVMin = API_EMA.estadisticas.map(function (e) {
return e.luxer_uv_min || 0;
});
var VientoR_Max = API_EMA.estadisticas.map(function (e) {
return e.viento_rafagas_max || 0;
});
var PresionA_Max = API_EMA.estadisticas.map(function (e) {
return e.presion_absoluta_max || 0;
});
labels.reverse();
humedadMax.reverse();
humedadMin.reverse();
TempMax.reverse();
TemMin.reverse();
LluviaMax.reverse();
VientoMax.reverse();
LuxerMax.reverse();
LuxerMin.reverse();
UVMax.reverse();
UVMin.reverse();
VientoR_Max.reverse();
PresionA_Max.reverse();
//console.log(API_EMA.estadisticas);
var ctx = document.getElementById("graph");
if (Grafico != undefined) {
//console.log("borro grafico");
Grafico.destroy();
}
Grafico = new Chart(ctx, {
type: "line",
data: {
labels: labels,
datasets: [
{
label: "Humedad_Max",
data: humedadMax,
pointRadius: 1,
backgroundColor: ["rgba(200, 0, 0, 0.2)"],
borderColor: ["rgba(200,0,0,1)"],
borderWidth: 1
},
{
label: "Humedad_Min",
data: humedadMin,
pointRadius: 1,
backgroundColor: ["rgba(100,0,0, 0.6)"],
borderColor: ["rgba(100,0,0,1)"],
borderWidth: 1,
hidden: true
},
{
label: "Lluvia",
data: LluviaMax,
pointRadius: 1,
backgroundColor: ["rgba(100,100,100, 0.6)"],
borderColor: ["rgba(100,100,100,1)"],
borderWidth: 1,
hidden: true
},
{
label: "VientoMax",
data: VientoMax,
pointRadius: 1,
backgroundColor: ["rgba(100,180,0, 0.7)"],
borderColor: ["rgba(100,190,0,1)"],
borderWidth: 1,
hidden: true
},
{
label: "RafagasMax",
data: VientoR_Max,
pointRadius: 1,
backgroundColor: ["rgba(100,80,0, 0.7)"],
borderColor: ["rgba(100,80,0,1)"],
borderWidth: 1,
hidden: true
},
{
label: "Presion_Max",
data: PresionA_Max,
pointRadius: 1,
backgroundColor: ["rgba(10,8,0, 0.2)"],
borderColor: ["rgba(10,9,0,1)"],
borderWidth: 1,
hidden: true
},
{
label: "Temperatura_Max",
data: TempMax,
pointRadius: 1,
backgroundColor: ["rgba(100,80,0, 0.2)"],
borderColor: ["rgba(100,90,0,1)"],
borderWidth: 1
},
{
label: "Temperatura_Min",
data: TemMin,
pointRadius: 1,
backgroundColor: ["rgba(100,80,0, 0.7)"],
borderColor: ["rgba(100,90,0,1)"],
borderWidth: 1,
hidden: true
},
{
label: "UV_Max",
data: UVMax,
pointRadius: 1,
backgroundColor: ["rgba(100,80,200, 0.2)"],
borderColor: ["rgba(100,90,200,1)"],
borderWidth: 1,
hidden: true
},
{
label: "UV_Min",
data: UVMin,
pointRadius: 1,
backgroundColor: ["rgba(100,80,200, 0.7)"],
borderColor: ["rgba(100,90,0,1)"],
borderWidth: 1,
hidden: true
},
{
label: "Luxer_Max",
data: LuxerMax,
pointRadius: 1,
backgroundColor: ["rgba(100,80,100, 0.2)"],
borderColor: ["rgba(100,90,0,1)"],
borderWidth: 1,
hidden: true
},
{
label: "Luxer_Min",
data: LuxerMin,
pointRadius: 1,
backgroundColor: ["rgba(100,80,100, 0.7)"],
borderColor: ["rgba(100,90,0,1)"],
borderWidth: 1,
hidden: true
}
]
},
options: {
elements: { point: { hitRadius: 10, hoverRadius: 10 } },
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
}
});
// GRAFICO VIENTO DIRECCION
G_viento = new RadialGauge({
renderTo: "grafico_vientos",
minValue: 0,
maxValue: 360,
majorTicks: ["N", "NE", "E", "SE", "S", "SW", "W", "NW", "N"],
minorTicks: 22,
ticksAngle: 360,
startAngle: 180,
strokeTicks: false,
highlights: false,
colorPlate: "#a33",
colorMajorTicks: "#f5f5f5",
colorMinorTicks: "#ddd",
colorNumbers: "#ccc",
colorNeedle: "rgba(240, 128, 128, 1)",
colorNeedleEnd: "rgba(255, 160, 122, .9)",
valueBox: false,
valueTextShadow: false,
colorCircleInner: "#fff",
colorNeedleCircleOuter: "#ccc",
needleCircleSize: 15,
needleCircleOuter: false,
animationRule: "linear",
needleType: "arrow",
needleStart: -10,
needleEnd: 80,
needleWidth: 4,
borders: true,
borderInnerWidth: 0,
borderMiddleWidth: 0,
borderOuterWidth: 10,
colorBorderOuter: "#ccc",
colorBorderOuterEnd: "#ccc",
colorNeedleShadowDown: "#222",
borderShadowWidth: 0,
animationDuration: 2500
}).draw();
// GRAFICO VIENTO KILOMETROS
G_vientoKm = new RadialGauge({
renderTo: "grafico_vientos_km",
units: "Rafagas",
minValue: 0,
maxValue: 220,
valueTextShadow: false,
valueInt: 1,
valueDec: 2,
colorValueBoxBackground: "#cccccc",
colorValueBoxShadow: true,
colorValueTextShadow: true,
majorTicks: [
"0",
"20",
"40",
"60",
"80",
"100",
"120",
"140",
"160",
"180",
"200",
"220"
],
minorTicks: 10,
strokeTicks: true,
highlights: [
{
from: 40,
to: 80,
color: "rgba(255, 0, 0, .10)"
},
{
from: 80,
to: 120,
color: "rgba(255, 0, 0, .35)"
},
{
from: 120,
to: 160,
color: "rgba(255, 0, 0, .75)"
},
{
from: 160,
to: 220,
color: "rgba(255, 0, 0, .95)"
}
],
colorPlate: "#fff",
borderShadowWidth: 0,
borders: false,
needleType: "arrow",
needleWidth: 2,
needleCircleSize: 7,
needleCircleOuter: true,
needleCircleInner: false,
animationDuration: 1500,
animationRule: "linear"
}).draw();
// GRAFICO PRESION ATMOSFERICA
G_presion = new RadialGauge({
renderTo: "grafico_presion",
units: "Hpa",
minValue: 970,
maxValue: 1050,
majorTicks: [
"970",
"980",
"990",
"1000",
"1010",
"1020",
"1030",
"1040",
"1050"
],
minorTicks: 10,
strokeTicks: true,
highlights: [
{
from: 1015,
to: 1050,
color: "rgba(200, 50, 50, .75)"
}
],
colorPlate: "#fff",
borderShadowWidth: 0,
borders: false,
valueBox: false,
needleType: "arrow",
needleWidth: 2,
needleCircleSize: 7,
needleCircleOuter: true,
needleCircleInner: false,
animationDuration: 1500,
animationRule: "linear"
}).draw();
// GRAFICO RAYOS UV
G_uv = new RadialGauge({
renderTo: "grafico_uv",
units: "UV",
minValue: 0,
maxValue: 11,
majorTicks: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"],
minorTicks: 1,
strokeTicks: true,
highlights: [
{
from: 0,
to: 2,
color: "rgba(57, 162, 1, 1)"
},
{
from: 2,
to: 5,
color: "rgba(57, 102, 1, 1)"
},
{
from: 5,
to: 7,
color: "rgba(200, 50, 50, 1)"
},
{
from: 7,
to: 9,
color: "rgba(255, 0, 0, 1)"
},
{
from: 9,
to: 11,
color: "rgba(92, 43, 136, 1)"
}
],
colorPlate: "#fff",
borderShadowWidth: 0,
borders: false,
valueBox: false,
needleType: "arrow",
needleWidth: 2,
needleCircleSize: 7,
needleCircleOuter: true,
needleCircleInner: false,
animationDuration: 1500,
animationRule: "linear"
}).draw();
// GRAFICO DE Iluminacia
G_iluminancia = new RadialGauge({
renderTo: "grafico_iluminancia",
units: "Klux",
minValue: 0,
maxValue: 300,
majorTicks: [
"0",
"20",
"40",
"60",
"80",
"100",
"120",
"140",
"160",
"180",
"200",
"220",
"240",
"260",
"280",
"300"
],
minorTicks: 5,
strokeTicks: true,
highlights: [
{
from: 0,
to: 40,
color: "rgba(255, 255, 0, .15)"
},
{
from: 40,
to: 80,
color: "rgba(255, 255, 0, .35)"
},
{
from: 80,
to: 120,
color: "rgba(255, 255, 0, .45)"
},
{
from: 120,
to: 160,
color: "rgba(255, 255, 112, 1)"
},
{
from: 160,
to: 300,
color: "rgba(255, 255, 0, 1)"
}
],
colorPlate: "#fff",
borderShadowWidth: 0,
borders: false,
valueBox: false,
needleType: "arrow",
needleWidth: 2,
needleCircleSize: 7,
needleCircleOuter: true,
needleCircleInner: false,
animationDuration: 1500,
animationRule: "linear"
}).draw();
// Se setea la variable que ya se crearon los graficos
API_EMA.grafico = true;
}
//BUSCADOR DE ESTACIONES - MENU SUPERIOR
function MenuBuqueda (DatosEstaciones) {
var options = {
data: DatosEstaciones,
getValue: function (element) {
return element.ciudad + ", " + element.pais;
},
template: {
type: "custom",
method: function (value, item) {
var Estadospan='danger';
if (item.estado=="En línea") {Estadospan = 'success';}
return " <span class='badge badge-"+Estadospan+" badge-pill pull-right' ><small>"+item.estado+"</small></span> <br><table><tr><td><img width='45' height='45' src='./imgs/Estacion-Carpincho.png' /> </td><td><b>"+item.ciudad + ", " + item.pais + "</b><br> <small><b>Estación:</b> "+item.nombre+"</small></td></tr></table>";
}
},
list: {
onClickEvent: function () {
var id = $("#buscador").getSelectedItemData().id_estacion;
API_EMA.observaciones = [];
API_EMA.grafico = false;
API_EMA.tabla = false;
setCookie("MenuEstacionSeleccion",id);
navigator.geolocation.getCurrentPosition(
Una_Estacion_GeoDistancia,
ErrorObtiendoGPS,
{ enableHighAccuracy: true, timeout: 5000, maximumAge: 0 });
},
onKeyEnterEvent: function () {
var id = $("#buscador").getSelectedItemData().id_estacion;
API_EMA.observaciones = [];
API_EMA.grafico = false;
API_EMA.tabla = false;
setCookie("MenuEstacionSeleccion",id);
navigator.geolocation.getCurrentPosition(
Una_Estacion_GeoDistancia,
ErrorObtiendoGPS,
{ enableHighAccuracy: true, timeout: 5000, maximumAge: 0 } );
},
match: {
enabled: true
},
maxNumberOfElements: 6,
showAnimation: {
type: "slide",
time: 300
},
hideAnimation: {
type: "slide",
time: 300
}
},
theme: "round"
};
//$("#buscador").easyAutocomplete(options);
$("#buscador").easyAutocomplete(options).click(function(){
$(this).triggerHandler(jQuery.Event("keyup", { keyCode: 65, which: 65}))
});
}
//ARMAR DATATABLE
function ArmarDatatable() {
API_EMA.tabla = false;
$("#dt_principal").DataTable({
dom: "Bfrtip",
buttons: ["copy", "csv"],
scrollX: true,
scrollCollapse: true,
//processing: true,
//deferLoading: 57,
ordering: true,
destroy: true,
order: [[0, "asc"]],
language: {
decimal: "",
emptyTable: "No datos disponibles.",
info:
"Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
infoEmpty: "Mostrando registros del 0 al 0 de un total 0 registros",
infoFiltered: "(filtrados de _MAX_ total registros)",
infoPostFix: "",
thousands: ",",
lengthMenu: "Mostrando _MENU_ registros",
loadingRecords: "Cargando...",
processing: "Procesando...",
search: "Buscar:",
zeroRecords: "No hay datos encontrados en el filtro.",
paginate: {
first: "Primero",
last: "Ultimo",
next: "Prox",
previous: "Ant"
},
aria: {
sortAscending: ": activate to sort column ascending",
sortDescending: ": activate to sort column descending"
}
}
});
API_EMA.tabla = true;
}
// METODOS PARA GET Y SET COOKIE
function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + 1 * 24 * 60 * 60 * 1000);
document.cookie = key + "=" + value + ";expires=" + expires.toUTCString();
}
function getCookie(key) {
var keyValue = document.cookie.match("(^|;) ?" + key + "=([^;]*)(;|$)");
return keyValue ? keyValue[2] : null;
}
function getMax(arr, prop) {
var max;
for (var i = 0; i < arr.length; i++) {
if (!max || parseFloat(arr[i][prop]) > parseFloat(max)) max = arr[i][prop];
}
//console.log(max);
if (typeof max === "undefined" || max === null) {
max = "SD";
}
return max;
}
function getMin(arr, prop) {
var min;
for (var i = 0; i < arr.length; i++) {
if (!min || parseFloat(arr[i][prop]) < parseFloat(min)) min = arr[i][prop];
}
if (typeof min === "undefined" || min === null) {
min = "SD";
}
return min;
}
function CambiarFondo(intensidad){
// console.log(intensidad)
if(intensidad>5){
// $('#cuerpo').css("background-image", "url(./imgs/Pna.jpg)");
}
if(intensidad <=35){
// $('#cuerpo').css("background-image", "url(./imgs/Pna2.jpg)");
}
if(intensidad<5 && intensidad>-1){
// $('#cuerpo').css("background-image", "url(./imgs/noche.jpg)");
}
}