React setstate with datamaps? - javascript

I am using Datamaps for this example. I have a Datamap that, when clicked in .datamaps-subunit.MI, changes the color of the portion. I would also like to store a number into my React state. However, the code below results in a this.setState is not a function error.
lemap:function(){
var map = new Datamap({
element: document.getElementById('maincontains'),
scope: 'usa',
fills: {defaultFill: 'rgb(217, 217, 217)'},
done: function(datamap) {
datamap.svg.select('.datamaps-subunit.MI').on('click', function(geography) {
var m = {};
var bis = this;
m[geography.id] = 'pink';
datamap.updateChoropleth(m);
this.setState({trumpnum: 12});
});
}
});
},

Fixed it by adding var sting = this right beneath the function.
lemap:function(){
var sting = this;
var map = new Datamap({
element: document.getElementById('maincontains'),
scope: 'usa',
fills: {defaultFill: 'rgb(217, 217, 217)'},
done: function(datamap) {
datamap.svg.select('.datamaps-subunit.MI').on('click', function(geography) {
var m = {};
var bis = this;
m[geography.id] = 'pink';
datamap.updateChoropleth(m);
sting.setState({trumpnum: 12});
});
}
});
},

Related

User memory limit exceeded in GEE

I started using GEE recently. I wanted to apply the non-parametric Mann-Kendall method to a collection of Sentinel-1 images. However there is a memory error in the code and this is my problem. Link code:https://code.earthengine.google.com/4bf1dbbcd116c8e3f5c584fbb45e8c19
var quadricula = ee.Geometry.Polygon([[-51.20732599322313,-15.60026586116677],[-51.20732599322313,-15.455379154650098],[-51.262600956602036,-15.455379154650098],[-51.262600956602036,-15.60026586116677]]);
//Map.addLayer(quadricula);
// Filter collection to dates of interest.
var Sentinel1 = ee.ImageCollection('COPERNICUS/S1_GRD')
.filterDate('2015-01-01', '2022-01-01')
.filterBounds(quadricula);
print('Quantidade de imagens no intervalo definido:',Sentinel1.size());
//===========================================================================//
var wrapper = require('users/adugnagirma/gee_s1_ard:wrapper');
var helper = require('users/adugnagirma/gee_s1_ard:utilities');
//---------------------------------------------------------------------------//
// DEFINE PARAMETERS
//---------------------------------------------------------------------------//
//var geometry = ee.Geometry.Polygon([[-51.20732599322313,-15.60026586116677],[-51.20732599322313,-15.455379154650098],[-51.262600956602036,-15.455379154650098],[-51.262600956602036,-15.60026586116677]]);
//Map.addLayer(geometry);
var parameter = {//1. Data Selection
START_DATE: "2015-01-01",
STOP_DATE: "2022-01-01",
POLARIZATION:'VVVH',
ORBIT : 'BOTH',
GEOMETRY: quadricula, //uncomment if interactively selecting a region of interest
//GEOMETRY: ee.Geometry.Polygon([[[104.80, 11.61],[104.80, 11.36],[105.16, 11.36],[105.16, 11.61]]], null, false), //Uncomment if providing coordinates
//GEOMETRY: ee.Geometry.Polygon([[[112.05, -0.25],[112.05, -0.45],[112.25, -0.45],[112.25, -0.25]]], null, false),
//2. Additional Border noise correction
APPLY_ADDITIONAL_BORDER_NOISE_CORRECTION: true,
//3.Speckle filter
APPLY_SPECKLE_FILTERING: true,
SPECKLE_FILTER_FRAMEWORK: 'MULTI',
SPECKLE_FILTER: 'REFINED LEE',
SPECKLE_FILTER_KERNEL_SIZE: 5,
SPECKLE_FILTER_NR_OF_IMAGES: 10,
//4. Radiometric terrain normalization
APPLY_TERRAIN_FLATTENING: true,
DEM: ee.Image('NASA/NASADEM_HGT/001'),
TERRAIN_FLATTENING_MODEL: 'VOLUME',
TERRAIN_FLATTENING_ADDITIONAL_LAYOVER_SHADOW_BUFFER: 0,
//5. Output
FORMAT : 'DB',
CLIP_TO_ROI: true,
SAVE_ASSETS: false
};
//---------------------------------------------------------------------------//
// DO THE JOB
//---------------------------------------------------------------------------//
//Preprocess the S1 collection
var s1_preprocces = wrapper.s1_preproc(parameter);
var s1 = s1_preprocces[0];
s1_preprocces = s1_preprocces[1];
//---------------------------------------------------------------------------//
// VISUALIZE
//---------------------------------------------------------------------------//
//Visulaization of the first image in the collection in RGB for VV, VH, images
var visparam = {};
if (parameter.POLARIZATION=='VVVH'){
if (parameter.FORMAT=='DB'){
var s1_preprocces_view = s1_preprocces.map(helper.add_ratio_lin).map(helper.lin_to_db2);
var s1_view = s1.map(helper.add_ratio_lin).map(helper.lin_to_db2);
visparam = {bands:['VV','VH','VVVH_ratio'],min: [-20, -25, 1],max: [0, -5, 15]};
}
else {
var s1_preprocces_view = s1_preprocces.map(helper.add_ratio_lin);
var s1_view = s1.map(helper.add_ratio_lin);
visparam = {bands:['VV','VH','VVVH_ratio'], min: [0.01, 0.0032, 1.25],max: [1, 0.31, 31.62]};
}
}
else {
if (parameter.FORMAT=='DB') {
s1_preprocces_view = s1_preprocces.map(helper.lin_to_db);
s1_view = s1.map(helper.lin_to_db);
visparam = {bands:[parameter.POLARIZATION],min: -25,max: 0} ;
}
else {
s1_preprocces_view = s1_preprocces;
s1_view = s1;
visparam = {bands:[parameter.POLARIZATION],min: 0,max: 0.2};
}
}
// Calcula o MRFDI
var MRFDI = s1_preprocces.map(function(image) {
return image.normalizedDifference(['VV', 'VH']).rename('MRFDI');
});
var addMRFDI = function (image) {
var MRFDI = image.expression('(VV - VH)/(VV + VH)', {
'VV' : image.select('VV'),
'VH' : image.select('VH'),
}).float();
return image.addBands(MRFDI.rename('MRFDI'));
};
var MRFDI = s1_preprocces.map(addMRFDI)
.select('MRFDI');
// Calcula o RVI
var RVI = s1_preprocces.map(function(image) {
return image.normalizedDifference(['VV', 'VH']).rename('RVI');
});
var addRVI = function (image) {
var RVI = image.expression('(4*VH)/(VV + VH)', {
'VV' : image.select('VV'),
'VH' : image.select('VH'),
}).float();
return image.addBands(RVI.rename('RVI'));
};
var RVI = s1_preprocces.map(addRVI)
.select('RVI');
Map.centerObject(parameter.GEOMETRY, 12);
Map.addLayer(s1_view.first(), visparam, 'First image in the input S1 collection', true);
Map.addLayer(s1_preprocces_view.first(), visparam, 'First image in the processed S1 collection', true);
//---------------------------------------------------------------------------//
// EXPORT
//---------------------------------------------------------------------------//
//Convert format for export
if (parameter.FORMAT=='DB'){
s1_preprocces = s1_preprocces.map(helper.lin_to_db);
}
//Save processed collection to asset
if(parameter.SAVE_ASSETS) {
helper.Download.ImageCollection.toAsset(s1_preprocces, '',
{scale: 10,
region: s1_preprocces.geometry(),
type: 'float'});
}
print('Quantidade de imagens s1_preprocces:',s1_preprocces.size());
// Define an image collection time series to chart, MODIS vegetation indices
// in this case.
var imgCol = s1_preprocces
.select(['VV', 'VH']);
//=================================================================================//
//mann-kendall
var coll = s1_preprocces.map(function(image) {
return image.select().addBands(image.normalizedDifference(['VH', 'VV']));
})
.filter(ee.Filter.calendarRange(8, 9, 'month'));
Map.addLayer(coll, {}, 'coll');
var afterFilter = ee.Filter.lessThan({
leftField: 'system:time_start',
rightField: 'system:time_start'
});
var joined = ee.ImageCollection(ee.Join.saveAll('after').apply({
primary: coll,
secondary: coll,
condition: afterFilter
}));
var sign = function(i, j) { // i and j are images
return ee.Image(j).neq(i) // Zero case
.multiply(ee.Image(j).subtract(i).clamp(-1, 1)).int();
};
var kendall = ee.ImageCollection(joined.map(function(current) {
var afterCollection = ee.ImageCollection.fromImages(current.get('after'));
return afterCollection.map(function(image) {
// The unmask is to prevent accumulation of masked pixels that
// result from the undefined case of when either current or image
// is masked. It won't affect the sum, since it's unmasked to zero.
return ee.Image(sign(current, image)).unmask(0);
});
// Set parallelScale to avoid User memory limit exceeded.
}).flatten()).reduce('sum', 2);
var palette_sens = {min: -0.001, max: 0.001, palette: [
'red', 'white', 'green']};
var palette = ['red', 'white', 'green'];
// Stretch this as necessary.g
Map.addLayer(kendall, {palette: palette}, 'kendall');
var slope = function(i, j) { // i and j are images
return ee.Image(j).subtract(i)
.divide(ee.Image(j).date().difference(ee.Image(i).date(), 'days'))
.rename('slope')
.float();
};
var slopes = ee.ImageCollection(joined.map(function(current) {
var afterCollection = ee.ImageCollection.fromImages(current.get('after'));
return afterCollection.map(function(image) {
return ee.Image(slope(current, image));
});
}).flatten());
var sensSlope = slopes.reduce(ee.Reducer.median(), 2); // Set parallelScale.
Map.addLayer(sensSlope, palette_sens, 'sensSlope');
var epochDate = ee.Date('1970-01-01');
var sensIntercept = coll.map(function(image) {
var epochDays = image.date().difference(epochDate, 'days').float();
return image.subtract(sensSlope.multiply(epochDays)).float();
}).reduce(ee.Reducer.median(), 2);
Map.addLayer(sensIntercept, {}, 'sensIntercept');
Map.addLayer(table, {color: 'blue'});
I hope to resolve this impasse without changing the adopted time interval and reducing the size of the study area.

Live update highcharts-gauge from dweet

I would like to have the gauge chart update live dweet data, which is success.
The problem is that every time a new data is pushed to the array humidityData, a new pointer is added in the gauge chart as shown here:
guage chart Though I'd like to have one live-updating-pointer instead.
Could this be done by pop() the prev data?
<script language="JavaScript">
//Array to store sensor data
var humidityData = []
<!--START-->
$(document).ready(function() {
//My Dweet thing's name
var name = 'dweetThingName'
//Humidity chart
var setupSecondChart = function() {
var chart2 = {
type: 'gauge'
};
var title = {...};
var pane = {...};
var yAxis = {...};
var tooltip = {
formatter: function () {
return '<b>' + "Humidity: " + Highcharts.numberFormat(this.y, 2) + "%";
}
};
//Series_Humidity
humiditySeries = [{
name: 'Humidity %',
data: humidityData,
tooltip: {
valueSuffix: '%'
}
}]
//Json_Humidity
var humJson = {};
humJson.chart = chart2;
humJson.title = title;
humJson.tooltip = tooltip;
humJson.xAxis = xAxis;
humJson.yAxis = yAxis;
humJson.legend = legend;
humJson.exporting = exporting;
humJson.series = humiditySeries;
humJson.plotOptions = plotOptions;
console.log("Sereies: : " +humJson)
//Container_Humidity
$('#containerHumidity').highcharts(humJson);
}
var humiditySeries = [] ....
dweetio.get_all_dweets_for(name, function(err, dweets){
for(theDweet in dweets.reverse())
{
var dweet = dweets[theDweet];
//Dweet's variables' names
val2 = dweet.content["Humidity"]
//Add the vals into created arrayDatas
humidityData.push(val2)
console.log("HumidityData: " + humidityData)
}
//Call other charts
setupSecondChart()
});
When you initialize/update your chart make sure that data array contains only one element. The dial is created for every point in this array (to visualize it on the plot).

I want to multiply chart data according as array length

I used this ,to multiply doughnut chart according as array(arr) has,but it can't change to object,(data has string type).So chart doesn't appear here..,how fix it
var arr=['HTML','CSS','JS'],i,data;
data ='[';
for(i=0;i<arr.length;i++){
if(i==arr.length-1){
data+='{value:"300",color:"#fff",highlight:"#aaa",label:arr[i]}';
}
else{
data+='{value:"300",color:"#fff",highlight:"#aaa",label:arr[i]},';
}
}
data += ']';
var dat = data;
window.onload = function () {
var ctx = document.getElementById("chart-area").getContext("2d");
window.myBar = new Chart(ctx).Doughnut(dat,{
responsive: true,
});
};
//want like this
dat =[{value:"300",color:"#fff",highlight:"#aaa",label:"HTML"},
{value:"200",color:"#fff",highlight:"#aaa",label:"CSS"}];
You are creating your array as a String.
You need to create an array of objects [{},{},{}].
The method used to INSERT a new object in an array is PUSH().
Check the fiddle. Now it´s working OK (move the mouse on the screen to see the chart is there (you will only see it when mouse is over it):
window.onload = function() {
var arr = ['HTML', 'CSS', 'JS'],
i, data;
data = [];
for (i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
data.push({
value: "300",
color: "#fff",
highlight: "#aaa",
label: arr[i]
});
} else {
data.push({
value: "300",
color: "#fff",
highlight: "#aaa",
label: arr[i]
});
}
}
var dat = data;
var ctx = document.getElementById("chart-area").getContext("2d");
window.myBar = new Chart(ctx).Doughnut(dat, {
responsive: true,
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/nnnick/Chart.js/master/Chart.js"></script>
<canvas id="chart-area"></canvas>

Values are not being saved to the array

I am pretty new to javascript and jquery. I currently have a xml file that I'm trying to parse by using jquery and javascript, but for some reason the values that I store on the array are not being saved.
var categories = new Array(); // Array for the categories
var data = {
categories: []
};
var sources = [
{
src:'',
title: '',
desc: ''
}];
var i = 0;
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
sources[i] = [];
sources[i].src = el.find('media\\:content, content').attr('url');
sources[i].title = el.find("title").text();
sources[i].desc = 'Moscone Center';
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
}
i++;
});
});
If i do console.log(categories) it prints all the categories on the array but if I do console.log(categories.length) I keep getting 0...
console.log(categories.length); // This should be outputting 5 but I keep getting 0 for the size.
for (var i=0; i<categories.length; i++) {
var category = {
name: categories[i],
videos: []
};
}
I appreciate any help that anybody can give me. Thanks
$.get function is asynchronous so you should try putting the logging inside the callback function.
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
....
});
console.log(categories.length);
});

how to create a complex javascript structure

i want to create a structure like that:
[{title:'Imágenes', extensions:'jpg,gif,png'}, {title:'Todos', extensions:'*'}]
but i need to create it from a string, in this way (in "js+jquery+php rare mode"):
items = 'Imágenes jpg,gif,png|Todos *'.split('|').each(function() {
list(title, ext) = explode(' ', $this);
filters[] = array('title' => title, 'ext' => ext);
});
i found structures like:
var theStatus = new Object();
function testIt() {
theStatus.Home = 'mouseover';
theStatus['Place'] = 'click';
for (var i in theStatus)
{
alert('theStatus[\''+i+'\'] is ' + theStatus[i])
}
}
and like:
$.alerts = {
verticalOffset: -75,
horizontalOffset: 0,
repositionOnResize: true,
overlayOpacity: .01,
overlayColor: '#FFF'
}
but i cant do nothing functional.
Thanks in advance.
This is how I would do it:
items = 'Imágenes jpg,gif,png|Todos *'.split("|").map(function (itemString) {
var parts = itemString.split(" ");
return { title: parts[0], extensions: parts[1] };
});
Or you can do this if you use jQuery and need to support older browsers:
items = $.map('Imágenes jpg,gif,png|Todos *'.split("|"), function () {
var parts = this.split(" ");
return { title: parts[0], extensions: parts[1] };
});
Your pseudocode is close.
Try the following vanilla javascript:
var str = 'Imágenes jpg,gif,png|Todos *';
var objs = str.split('|');
var objects = [];
for (var i = 0; i < objs.length; i++) {
var parts = objs[i].split(' ');
objects.push({ title: parts[0], extensions: parts[1] });
}
// objects is now an array of custom objects in the format you specified.

Categories