add and remove logic in minimap changed

parent 8cf0e2a8
MAPBOX_ACCESS_TOKEN = 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';
MAX_OPACITY = 1;
FIRST_IMAGE_LAYER_INDEX = 2;
// create wkt polygon
const format = new ol.format.WKT();
const feature = format.readFeature(polygon, {
const wktFormat = new ol.format.WKT();
const polygonFeature = wktFormat.readFeature(polygon, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
});
// Create layers
const mapbox = new ol.layer.Tile({
const mapLayer = new ol.layer.Tile({
name: 'mapbox',
source: new ol.source.XYZ({
url:'https://api.tiles.mapbox.com/v4/mapbox.light/{z}/{x}/{y}.png?access_token='+MAPBOX_ACCESS_TOKEN
})
});
const vector = new ol.layer.Vector({
const polygonLayer = new ol.layer.Vector({
name: 'polygon',
source: new ol.source.Vector({
features: [feature]
features: [polygonFeature]
})
});
const layers = new Map();
// create map
const map = new ol.Map({
target: 'minimap',
layers: [mapbox, vector],
layers: [mapLayer, polygonLayer],
view: new ol.View({
center: ol.proj.fromLonLat([-99.19, 19.61]),
zoom: 4,
......@@ -34,98 +37,80 @@ const map = new ol.Map({
})
});
// fit to polygon
map.getView().fit(feature.getGeometry());
// fit (zoom) to polygon
map.getView().fit(polygonFeature.getGeometry());
// show first date
// show first layer date
let currentDate = labels[0];
addImageLayer(currentDate)
addImageLayer({
layerDate: currentDate
});
// main function to change layers
// data = { layerDate: to change all layers by date }
// data = { layerName: to add single layer }
function addImageLayer(data) {
if (data.layerDate) {
currentDate = data.layerDate;
}
function addImageLayer(labelDate) {
$.ajax({
type: 'POST',
dataType: "json",
data: {'purchase_id': purchase_id, 'report': zone, 'date': labelDate},
data: {'purchase_id': purchase_id, 'report': zone, 'date': currentDate},
url: '/reports/tiles/tileinfo',
success: function (data) {
success: response => {
changeLayers(data.layerName);
setOpacity($('#opacitySlide').val());
map.getView().setMinZoom(response.zoom.min);
map.getView().setMaxZoom(response.zoom.max);
}
});
}
// remove old layers and add layers with new date
function changeLayers(especific_layerName) {
const layersToChance = especific_layerName ? especific_layerName.split() : getSelectedLayersName();
currentDate = labelDate;
removeImageLayers()
removeLayer(especific_layerName);
// add layer
getSelectedCheckboxes().forEach(layer_type => {
layersToChance.forEach(layerName => {
const xyz = new ol.layer.Tile({
name: layer_type,
opacity: (layer_type == 'TCI') ? 1 : $('#opacitySlide').val(),
name: layerName,
source: new ol.source.XYZ({
projection: 'EPSG:3857',
url: '/reports/tiles/'+purchase_id+'/'+zone+'/'+layer_type+'/'+labelDate+'/{z}/{x}/{-y}.png',
tilePixelRatio: 2,
minZoom: data.zoom.min,
maxZoom: data.zoom.max
url: '/reports/tiles/'+purchase_id+'/'+zone+'/'+layerName+'/'+currentDate+'/{z}/{x}/{-y}.png',
tilePixelRatio: 2
})
});
if (layerName === 'TCI') {
map.getLayers().insertAt(FIRST_IMAGE_LAYER_INDEX, xyz);
} else {
map.addLayer(xyz);
})
// fit and zoom
map.getView().setMinZoom(data.zoom.min);
map.getView().setMaxZoom(data.zoom.max);
}
layers.set(layerName, xyz);
});
}
function removeImageLayers() {
map.getLayers().getArray().slice().forEach(layer => {
if(layer.get('name') != 'mapbox' && layer.get('name') != 'polygon') {
map.removeLayer(layer)
// remove all if there isn't layername
function removeLayer(layerName) {
if (!layerName) {
layers.forEach(layer => { map.removeLayer(layer); });
layers.clear();
return;
}
})
map.removeLayer(layers.get(layerName));
layers.delete(layerName);
}
// set opacity to layers
function setOpacity(value) {
map.getLayers().getArray().slice().forEach(layer => {
if(layer.get('name') != 'mapbox' && layer.get('name') != 'polygon' && layer.get('name') != 'TCI') {
layers.forEach(layer => {
if(layer.get('name') != 'TCI') {
layer.setOpacity(value)
}
})
}
function getSelectedCheckboxes() {
const inputs = $("input[name=layer_type]:checked");
let values = []
Object.keys(inputs).forEach(key => {
let value = inputs[key].value;
if (value) {values.push(value)}
})
return values;
}
function getChartDataIndex(id) {
let foundIndex;
myChart.config.data.datasets.forEach(function (data, index) {
let label = 'sclcheck-' + data.label.toLowerCase().replace(' ', '-');
if (label === id) {
foundIndex = index;
}
})
return foundIndex;
}
$('input[name=layer_type]').on('click', function(){
const input = $(this);
const index = getChartDataIndex(input.parent().attr('id'));
if (index > -1) {
myChart.getDatasetMeta(index).hidden=!input.prop("checked");
myChart.update()
}
addImageLayer(currentDate);
});
......@@ -25,10 +25,13 @@ document.getElementById("myChart").onclick = function (evt) {
if(activePoint.length>0){
var firstPoint = activePoint[0];
//console.log(firstPoint)
//console.log(firstPoint._datasetIndex) //indice de la clase a la que pertenece (vegetación, agua, etc.)
var label = myChart.data.labels[firstPoint._index];
addImageLayer(label)
//console.log(firstPoint._datasetIndex) //indice de la clase a la que pertenece (vegetación, agua, etc.)
addImageLayer({
layerDate: label
});
//console.log(myChart.legend.legendItems[firstPoint._datasetIndex].text) //nombre de la capa a la que pertenece (vegetación, agua, etc.)
//if (!firstPoint) return;
activePoints.forEach(function (value, index) {
......
......@@ -275,31 +275,28 @@
{% block scripts %}
<script id="rendered-js">
$('input[id="inputRange"]').on('input', function () {
let control = $(this);
let controlMin = control.attr('min');
let controlMax = control.attr('max');
let controlVal = control.val();
let controlThumbWidth = control.data('thumbwidth');
let range = controlMax - controlMin;
let position = (controlVal - controlMin) / range * 100;
let positionOffset = Math.round(controlThumbWidth * position / 100) - controlThumbWidth / 2;
let fecha = $("option:eq(" + controlVal + ")").text();
let valor = $("option:eq(" + controlVal + ")").val();
addImageLayer({
layerDate: valor
});
var control = $(this),
controlMin = control.attr('min'),
controlMax = control.attr('max'),
controlVal = control.val(),
controlThumbWidth = control.data('thumbwidth');
var range = controlMax - controlMin;
var position = (controlVal - controlMin) / range * 100;
var positionOffset = Math.round(controlThumbWidth * position / 100) - controlThumbWidth / 2;
var fecha = $("option:eq(" + controlVal + ")").text();
var valor = $("option:eq(" + controlVal + ")").val();
addImageLayer(valor);
$("#maptitle").empty();
$("#maptitle").append("Map Date: " + fecha);
$("#tooltiptext").empty();
$("#tooltiptext").append(fecha);
});
var slider2 = document.getElementById("inputRange");
var sliderOffsetX = slider2.getBoundingClientRect().left - document.documentElement.getBoundingClientRect().left;
var sliderOffsetY = slider2.getBoundingClientRect().top - document.documentElement.getBoundingClientRect().top;
var sliderWidth = slider2.offsetWidth - 1;
......@@ -310,20 +307,19 @@
value = sliderValAtPos - 1;
var fecha = $("option:eq(" + value + ")").text();
var valor = $("option:eq(" + value + ")").val();
$("#tooltiptext").empty();
$("#tooltiptext").css({"margin-left": currentMouseXPos + 'px', "margin-top": sliderOffsetY + 'px'});
$("#tooltiptext").append(fecha);
});
</script>
<!-- page script -->
<script>
var legendOnClickHandler = function (e, legendItem) {
var index = legendItem.datasetIndex;
var ch = this.chart;
let checkbox_id = '#sclcheck-'+legendItem.text.toLowerCase().replace(/\s/g, '-');
const legendOnClickHandler = function (e, legendItem) {
const index = legendItem.datasetIndex;
const ch = this.chart;
const checkbox_id = '#sclcheck-'+legendItem.text.toLowerCase().replace(/\s/g, '-');
// isDatasetVisible return the opposite status?
if (ch.getDatasetMeta(index).hidden === null) {
......@@ -331,14 +327,22 @@
} else {
ch.getDatasetMeta(index).hidden = !ch.getDatasetMeta(index).hidden;
}
ch.update();
$(checkbox_id+" :input").prop("checked", !ch.getDatasetMeta(index).hidden);
addImageLayer(currentDate);
const layerInput = $(checkbox_id+" :input");
layerInput.prop("checked", !ch.getDatasetMeta(index).hidden);
if (layerInput.prop("checked")) {
addImageLayer({
layerName: layerInput.val()
});
} else {
removeLayer(layerInput.val());
}
};
var showSCLcheckboxes = function(datasets) {
const showSCLcheckboxes = function (datasets) {
if (!datasets || datasets.length < 1) {
return;
}
......@@ -350,6 +354,43 @@
});
}
const getSelectedLayersName = function () {
const inputs = $("input[name=layer_type]:checked");
let values = []
Object.keys(inputs).forEach(key => {
let value = inputs[key].value;
if (value) {values.push(value)}
});
return values;
}
const getChartDataIndex = function (id) {
const datasetsLabels = myChart.config.data.datasets.map(data =>
'sclcheck-' + data.label.toLowerCase().replace(' ', '-')
);
return datasetsLabels.indexOf(id);
}
$('input[name=layer_type]').on('click', function() {
const input = $(this);
const index = getChartDataIndex(input.parent().attr('id'));
if (index > -1) {
myChart.getDatasetMeta(index).hidden=!input.prop("checked");
myChart.update();
}
if (input.prop("checked")) {
addImageLayer({
layerName: input.val()
});
} else {
removeLayer(input.val());
}
});
var label;
// Recibimos el JSON con los datos desde el View
{% autoescape off %}
......
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