Reduction over an image collection Google Earth Engine - javascript

I am using CHIRPS data set (daily precipitation) to derive mean, median, min and max precipitation within a certain time frame. Then, I want to extract the values at specific locations included in a point shapefile and save the results in a table.
The script seem to work but the output table only has zeros (0) as values for the 4 variables.
Please see the script below
var lng = 65.64;
var lat = 34.35;
var point = ee.Geometry.Point(lat, lng);
//var aoi = point.buffer(100000); // Create an area (1km buffer around point)
var country = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017')
.filter(ee.Filter.eq('country_co', 'AF'));
var aoi = country;
Map.setCenter(lng, lat, 5); // Center the map on this location, zoom level 10
var start = '2018-02-15'; // initial date of the image collection
var end = '2018-07-15'; //final date of the image collection
var p1 = ee.Geometry.Point([69.78086, 34.65411])
var p2 = ee.Geometry.Point([61.82234, 30.66048])
var table = ee.FeatureCollection(ee.List([ee.Feature(p1),ee.Feature(p2)]))
var AddPrMean = function(image) {
var PrMean = image.reduce(ee.Reducer.mean()).rename('PrMean');
return image.addBands(PrMean);
};
var AddPrMedian = function(image) {
var PrMedian = image.reduce(ee.Reducer.median()).rename('PrMedian');
return image.addBands(PrMedian);
};
var AddPrMin = function(image) {
var PrMin = image.reduce(ee.Reducer.min()).rename('PrMin');
return image.addBands(PrMin);
};
var AddPrMax = function(image) {
var PrMax = image.reduce(ee.Reducer.max()).rename('PrMax');
return image.addBands(PrMax);
};
var dataset = ee.ImageCollection('UCSB-CHG/CHIRPS/DAILY')
.filterDate(start, end)
.filterBounds(aoi)
.map(AddPrMean)
.map(AddPrMedian)
.map(AddPrMin)
.map(AddPrMax);
var composites = dataset.select(['PrMean','PrMedian','PrMin','PrMax']).first();
var YieldLocations = ee.FeatureCollection(table);
var YPrec = composites.reduceRegions(YieldLocations, ee.Reducer.max(), 1);
print(YPrec); ```

I found a solution that seems to work, however, the median always gives 0 as result.
var lat = 34.35;
var point = ee.Geometry.Point(lat, lng);
//var aoi = point.buffer(100000); // Create an area (1km buffer around point)
var country = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017')
.filter(ee.Filter.eq('country_co', 'AF'));
var aoi = country;
Map.setCenter(lng, lat, 5); // Center the map on this location, zoom level 10
var start = '2018-02-15'; // initial date of the image collection
var end = '2018-07-15'; //final date of the image collection
var p1 = ee.Geometry.Point([69.78086, 34.65411])
var p2 = ee.Geometry.Point([61.82234, 30.66048])
var table = ee.FeatureCollection(ee.List([ee.Feature(p1),ee.Feature(p2)]))
var dataset = ee.ImageCollection('UCSB-CHG/CHIRPS/DAILY')
.filterDate(start, end)
.filterBounds(aoi);
var PrMean = dataset.mean().rename('PrMean');
var PrMedian = dataset.median().rename('PrMedian');
var PrMin = dataset.min().rename('PrMin');
var PrMax = dataset.max().rename('PrMax');
var composites = PrMean
.addBands(PrMedian)
.addBands(PrMin)
.addBands(PrMax);
var YieldLocations = ee.FeatureCollection(table);
var YPrec = composites.reduceRegions(YieldLocations, ee.Reducer.max(), 1);
print(YPrec);```

Related

google-apps script - loops

I have a project I been working on to read data from one sheet and iterate through the designated columns grab that data and place it on a template that will be uploaded to Google ads. See the code below (A SIMPLE LOOP IS NEEDED SEE MY CODE FOR COMMENTS!). Please note that i'm new to this and it may look like an eye sore. I been stuck on this for a while now trying literally everything I found with no success. if you need additional attachments or clarification please let me know.
//============================================================================*
// This program is an inventory based program that will create AdGroups based *
// On your current inventory Spreadsheet on your G-Drive *
// ===========================================================================*
function main() {
var feedCSVname = "FILE_NAME.csv"
var feedSheetName = "INVENTORY SHEET"
var TemplateURL = "SHEET_URL_HERE"
var Template_sheetName = "TEMPLATE_SHEET_NAME"
var push_sheetName = "Upload"
var done = "Done"
// ==== Parse CSV file and dump all contents to inventory sheet =========
var feedFile = DriveApp.getFilesByName(feedCSVname).next();
var feedData = Utilities.parseCsv(feedFile.getBlob().getDataAsString());
var Template = SpreadsheetApp.openByUrl(TemplateURL);
var feedSheet = Template.getSheetByName(feedSheetName);
feedSheet.clear().getRange(1, 1, feedData.length, feedData[0].length).setValues(feedData);
// Create a new columns "Status" so we can loop through
feedSheet.getRange('BI1').setValue('Status');
//==================== Feed Column Locations ============================
var CidColumn = 2;
var sellingPriceColumn = 10;
var yearColumn = 13;
var makeColumn = 14;
var modelColumn = 15;
var trimColumn = 16;
var dealernameColumn = 39;
var countofmakemodelyearColumn = 47;
var lowest_priceColumn = 52;
var mm_lowest_priceColumn = 53;
var m_lowest_priceColumn = 54;
var URL1Column = 58;
var URL2Column = 59;
var URL3Column = 60;
var status = 61;
var feedRows = 2 // Since row 1 has headers
var lastrow = feedSheet.getLastRow();
//======================= Feed Row Data ================================
var sellingPrice = feedSheet.getRange(feedRows, sellingPriceColumn).getValue();
var year = feedSheet.getRange(feedRows, yearColumn).getValue();
var make = feedSheet.getRange(feedRows, makeColumn).getValue();
var model = feedSheet.getRange(feedRows, modelColumn).getValue();
var dealername = feedSheet.getRange(feedRows, dealernameColumn).getValue();
var URL1 = feedSheet.getRange(feedRows, URL1Column).getValue();
var URL2 = feedSheet.getRange(feedRows, URL2Column).getValue();
var URL3 = feedSheet.getRange(feedRows, URL3Column).getValue();
//==================== Write Data To Template ==========================
// I need to loop this process
var templateSheet = Template.getSheetByName(Template_sheetName);
templateSheet.getRange('B2').setValue("Campaign Name");
templateSheet.getRange('B3').setValue(make);
templateSheet.getRange('B4').setValue(model);
templateSheet.getRange('B5').setValue(year);
templateSheet.getRange('D2').setValue(URL1);
templateSheet.getRange('D3').setValue(URL2);
templateSheet.getRange('D4').setValue(URL3);
feedSheet.getRange(feedRows, status).setValue(done);
// when this column and row = "Done" then go to next row
var readStatusColumn = feedSheet.getRange(feedRows, status).getValue();
if (readStatusColumn == done) {
//Then go to next row loop process
}
//================ Copy all data to push sheet =========================
//Copy contents of the Template sheet and paste to the Upload sheet
var copyRange = templateSheet.getRange('A8:J113');
var pushSheet = Template.getSheetByName(push_sheetName);
var paste2pushSheet = pushSheet.getRange(pushSheet.getLastRow() + 1, 1);
copyRange.copyTo(paste2pushSheet, {
contentsOnly: true
});
//End Loop
}

Get, treat and set data from a spreadsheet to another

I'm new to GAS. I'm trying to accomplish four tasks in a single spreadsheet with three separate sheets to relate to.
I want to copy data from the 'rawData sheet', set it in an array, rearrange the array, and set the values in the 'destination sheet'. And keep it active for new submissions (i.e. getLastRow/appendRow).
In 'destination sheet' I want to color code based on status.
Create a button in 'destination sheet' to mark row(case) complete and move from 'destination' to the 'complete sheet'.
And add onEdit triggers for each.
Your input is greatly appreciated.
Thanks.
function colorCode() {
var range = outerArray;
Logger.log(range);
var row = dBoard.getRange(dBoard.getLastRow(),1,1,dBoard.getLastColumn());
var submitter = range[3];
var status = range[11];
Logger.log(submitter);
Logger.log(status);
//var column = range.getColumn();
//var row = range.getRow();
if (status === "Approved"){
var rowToColor = row.offset(0,0,1,13);
rowToColor.setBackground("#6bb2ff");
}
else if (status === "Requester"){
var rowToColor = row.offset(0,0,1,13);
rowToColor.setBackground("#ffe16b");
}
else if (range === 12 && range > 1 && status === "Denied"){
var rowToColor = row.offset(0,0,1,13);
rowToColor.setBackground("#f9441b");
}
}
var ss = SpreadsheetApp.getActiveSpreadsheet();
var source1 = ss.getSheetByName("Copy of rawData");
var dBoard = ss.getSheetByName("dBoard2");
//function copyData() {
//var rawD = source1.getRange(1,1,source1.getLastRow(),source1.getLastColumn()).getValues();
//Logger.log(rawD);
function setData() {
var rawD = source1.getRange(source1.getLastRow(),1,1,source1.getLastColumn()).getValues();
//Logger.log(limits);
var columnA = rawD[0][0];
var columnB = rawD[0][18];
var columnC = rawD[0][13];
var columnD = rawD[0][2];
var columnE = rawD[0][3]
var columnF = rawD[0][4];
var columnG = rawD[0][5];
var columnH = rawD[0][6];
var columnI = rawD[0][7];
var columnJ = rawD[0][8];
var columnK = rawD[0][9];
var columnL = rawD[0][11];
var columnM = rawD[0][12];
var outerArray = [columnA,
columnB,
columnC,
columnD,
columnE,
columnF,
columnG,
columnH,
columnI,
columnJ,
columnK,
columnL,
columnM];
Logger.log(columnA);
Logger.log(columnB);
Logger.log(outerArray);
dBoard.getRange(2,1,outerArray.length,outerArray.length);
dBoard.appendRow(outerArray);
}

create arrow using leafletjs

I want to create a arrow in leaflet using poly lines of multipolylines whichever suits..
The arrow class should take in following param
baselatitude = base of the arrow where the arrow will be on map
baselongitude = base of the arrow where the arrow will be on map
pointlatitude = the tip of the arrow on the map
pointlongitude = the tip of the arrow on the map
apointlatitude
apointlongitude
bpointlatitude
bpointlongitude
angle = rotation degree
can anyone please provide guidance on creating the arrow using following param . It would be nice to if you can create a leaflet class extension L.arrow
did that myself for fit my requirement .. pasting in if somebody finds it useful someday
feature.geometry.coordinates[0] is the geoJson collection where all the coordinates are retrieved
L.Playback.WindArrowMarker = L.Marker.extend({
initialize: function (startLatLng, options, feature) {
this._min = 99;
this._max = 0;
this._arrowStyleOptions = [
{ color: '#ffff00' },
{ color: '#00ffff' },
{ color: '#00ff00' }];
var ArrowData = feature.geometry.coordinates[0];
var ArrowBaseLon = ArrowData[0];
var ArrowBaseLat = ArrowData[1];
var ArrowPointLat = ArrowData[2];
var ArrowPointLon = ArrowData[3];
var ArrowPointALat = ArrowData[4];
var ArrowPointALon = ArrowData[5];
var ArrowPointBLat = ArrowData[6];
var ArrowPointBLon = ArrowData[7];
var ArrowHeight = ArrowData[8];
var ArrowMagnitude = ArrowData[9];
var ArrowBearing = ArrowData[10];
if (ArrowMagnitude > this._max) this._max = ArrowMagnitude;
if (ArrowMagnitude < this._min) this._min = ArrowMagnitude;
var styleToUse=this._getArrowStyle(ArrowMagnitude);
//Create Arrow structure and assign first value from the playback data
//baseLtlg //PointLtlg
this._arrowbase = L.polyline([[ArrowBaseLat, ArrowBaseLon], [ArrowPointLat, ArrowPointLon]], styleToUse);
//PointLtlg //PointAtLtlg
this._arrowpointA = L.polyline([[ArrowPointLat, ArrowPointLon], [ArrowPointALat, ArrowPointALon]], styleToUse);
//PointLtlg //PointBLtlg
this._arrowpointB = L.polyline([[ArrowPointLat, ArrowPointLon], [ArrowPointBLat, ArrowPointBLon]], styleToUse);
//Call leaflet marker initialization to attach this as marker
L.Marker.prototype.initialize.call(this, [ArrowBaseLat, ArrowBaseLon], {});
//Calculate windspeed
var windspeed = this._calculateWindspeed(ArrowMagnitude, feature.modeldata.Adder, feature.modeldata.Multiplier)
//Attach a popup
this._arrowbase.bindPopup(this.getPopupContent(ArrowBearing, windspeed));
},
_calculateWindspeed: function (magnitude, adder, multiplier) {
return (magnitude - parseFloat(adder)) / multiplier
},
_getArrowStyle: function (magnitude) {
this._arrowMagMed = 7;
this._arrowMagHigh = 10;
if (magnitude > this._arrowMagHigh)
styleToUse = this._arrowStyleOptions[2];
else if (magnitude > this._arrowMagMed)
styleToUse = this._arrowStyleOptions[1];
else
styleToUse = this._arrowStyleOptions[0];
return styleToUse;
},
getPopupContent: function (bearing, windspeed) {
return sprintf("Wind blowing from: %s deg(from North)<br> Wind Speed(m/s): %s", bearing.toFixed(1), windspeed.toFixed(1));
},
addTo: function (map) {
this._arrowbase.addTo(map);
this._arrowpointA.addTo(map);
this._arrowpointB.addTo(map);
},
move: function (windData,transitionTime, modelData) {
var ArrowBaseLon = windData[0];
var ArrowBaseLat = windData[1];
var ArrowPointLat = windData[2];
var ArrowPointLon = windData[3];
var ArrowPointALat = windData[4];
var ArrowPointALon = windData[5];
var ArrowPointBLat = windData[6];
var ArrowPointBLon = windData[7];
var ArrowHeight = windData[8];
var ArrowMagnitude = windData[9];
var ArrowBearing = windData[10];
var styleToUse = this._getArrowStyle(ArrowMagnitude);
//Assign color based on magnitude
this._arrowbase.setStyle(styleToUse);
this._arrowpointA.setStyle(styleToUse);
this._arrowpointB.setStyle(styleToUse);
//Set Base,Apoint,Bpoint LatLongs as they are the ones changing
this._arrowbase.setLatLngs([[ArrowBaseLat, ArrowBaseLon], [ArrowPointLat, ArrowPointLon]])
this._arrowpointA.setLatLngs([[ArrowPointLat, ArrowPointLon], [ArrowPointALat, ArrowPointALon]])
this._arrowpointB.setLatLngs([[ArrowPointLat, ArrowPointLon], [ArrowPointBLat, ArrowPointBLon]])
//Calculate windspeed
var windspeed = this._calculateWindspeed(ArrowMagnitude, modelData.Adder, modelData.Multiplier)
//Check if popup is attached
if (this._arrowbase._popup) {
//Set popup content while moving
this._arrowbase._popup.setContent(this.getPopupContent(ArrowBearing, windspeed));
}
}
});
It would be nice to if you can create a leaflet class extension L.arrow
No: this is not a place where people make things for you. But we can Google things, like Leaflet arrow which leads you directly to Leaflet.PolylineDecorator.

How to change the position randomly?

var imgOut = function(){
var outImg = Math.floor(Math.random()*slideRandom.length);
document.getElementById("random").src = imgRandom[outImg];
var outSlide = slideRandom[outImg];
outSlide();
var wr = Math.floor(Math.random()*imgRandom.length);
var btl = Math.floor(Math.random()*bottle.length);
document.getElementById("bottle2").src = bottle[outImg];
document.getElementById("bottle1").src = bottle[btl];
document.getElementById("bottle3").src = bottle[wr];
/* try below but doesn't work or syntax error occured*/
var position= ['bottle[outImg]','bottle[btl]','bottle[wr]'];
var pos = Math.floor(Math.random()*position.length);
var pos1 = position[pos];
pos1();
}
what I'm try to do is
with different arrays to get different each images in different random position.
I've done different images to get but with three different arrays to put in random position doesn't work. what have I done wrong? or how to change above code?
I don't understand your requirements exactly, but consider this code:
var setImage = function(id, src) {
document.getElementById(id).src = src;
};
var chooseOne = function(array) {
return array[Math.floor(Math.random()*array.length)];
};
var setRandomImages = function() {
setImage("bottle1", chooseOne(bottle));
setImage("bottle2", chooseOne(bottle));
setImage("bottle3", chooseOne(bottle));
};
If the array bottle is a list of URLs, this will do something, though I cannot guarantee it will do what you want.
var position= ['bottle[outImg]()','bottle[btl]()','bottle[wr]()'];
var pos = Math.floor(Math.random()*position.length);
var pos1 = position[pos];
//pos1();
eval( pos1 );
// or
(new Function("return pos1"))();

How to get concotenate value with string to get the value from variable

Please check the script below.
Dynamic form, so the script also dynamic, I have to calculate when the form data changes. during this i am getting some problem.
am getting the value from the variable Final_price1, Final_price2 .....,Final_price7, Final_price8 and then am calculating the total of those.
During this calculation, am concatenating the following concat("Final_price",i); to get the values of the above. This concatenated correctly, but the above variables values are not coming. I dont know why the values are not getting there. So check the script and update me.
function assign_body()
{
var a_7= document.getElementById("option[280]").value;
var spl_7 = a_7.split("_");
//alert(spl);
var cr_7 = spl_7[1];
var operator3_7 = cr_7.split("[");
var symbol7 = operator3_7[0];
var dtt_7 = operator3_7[1];
var myarr_7 = dtt_7.split("$");
var symbol_st_7 = myarr_7[1];
//alert(symbol_st);
//alert(symbol_s);
//var symbol_a = symbol_s.split("(");
//var symbol = symbol_a[1];
//alert(symbol);
var split_value_7 = myarr_7[1];
//alert(split_value);
var final_value_7 =symbol_st_7.split(".");
var Final_price7 =final_value_7[0];
var a_8= document.getElementById("option[281]").value;
var spl_8 = a_8.split("_");
//alert(spl);
var cr_8 = spl_8[1];
var operator3_8 = cr_8.split("[");
var symbol8 = operator3_8[0];
var dtt_8 = operator3_8[1];
var myarr_8 = dtt_8.split("$");
var symbol_st_8 = myarr_8[1];
//alert(symbol_st);
//alert(symbol_s);
//var symbol_a = symbol_s.split("(");
//var symbol = symbol_a[1];
//alert(symbol);
var split_value_8 = myarr_8[1];
//alert(split_value);
var final_value_8 =symbol_st_8.split(".");
var Final_price8 =final_value_8[0];
var j=8;
var total_amount=0;
for(var i=1; i<=j; i++)
{
final_prices=concat("Final_price",i);
alert(final_prices);
symbol_prices=concat("symbol",i);
alert(symbol_prices);
if(isNumber(final_prices)){
alert("number");
/*if(symbol_prices =='+') {
alert("plus");
var total_amount+=parseInt(original_prices)+parseInt(final_prices);
calculated_price_element.innerHTML=total_amount;
alert(total_amount);
} else if(symbol_prices =='-') {
alert("minus");
var total_amount+=parseInt(original_prices)-parseInt(final_prices);
calculated_price_element.innerHTML=total_amount;
alert(total_amount);
}*/
//alert('test');
}
}
}

Categories