0

When I run the script in Google Earth Engine it doesn't center the map in the coordinates (11.87, 45.40) and it doesn't zoom. If it continues to run at a certain point it works and it centers the map and zooms to the right point. I don't understand what the problem is.

This is the screenshot of when it doesn't work:

This is the screenshot of when it works:

Here my code:

//
// IMPORT NORTHEN ITALIAN REGIONS

//var ROI = ee.FeatureCollection("projects/ee-robertoolorenzo/assets/po-valley-regions");
// Temporary ROI
var ROI = ee.FeatureCollection("FAO/GAUL_SIMPLIFIED_500m/2015/level2")
        .filter(ee.Filter.eq('ADM2_NAME', 'Padova'));

//
/////////// BASE MAP \\\\\\\\\\\

// Sentinel 2 as a Base Map

function maskS2clouds(image) {
  var qa = image.select('QA60');

  // Bits 10 and 11 are clouds and cirrus, respectively.
  var cloudBitMask = 1 << 10;
  var cirrusBitMask = 1 << 11;

  // Both flags should be set to zero, indicating clear conditions.
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0)
      .and(qa.bitwiseAnd(cirrusBitMask).eq(0));

  return image.updateMask(mask).divide(10000);
}

var S2basemap = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
                  .filterDate('2020-01-01', '2020-06-30')
                  // Pre-filter to get less cloudy granules.
                  .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',20))
                  .filterBounds(ROI)
                  .map(maskS2clouds)
                  .map(addGrayscale)
                  .median();

// Write a function that convert image in grayscale
function addGrayscale(image) {
  var grayscale = image.select('B4', 'B3', 'B2').reduce(ee.Reducer.mean()).rename('grayscale');
  return image.addBands(grayscale);
}

var visualization = {
  min: 0.0,
  max: 0.3,
  bands: ['grayscale'],
};


//
/////////// MASK CLOUDS FUNCTION LANDSAT \\\\\\\\\\\

// Function to Mask Clouds and Cloud Shadows in Landsat 8 Imagery
function cloudMask(image) {
  // Define cloud shadow and cloud bitmasks (Bits 3 and 5)
  var cloudShadowBitmask = (1 << 3);
  var cloudBitmask = (1 << 5);
  // Select the Quality Assessment (QA) band for pixel quality information
  var qa = image.select('QA_PIXEL');
  // Create a binary mask to identify clear conditions (both cloud and cloud shadow bits set to 0)
  var mask = qa.bitwiseAnd(cloudShadowBitmask).eq(0)
                .and(qa.bitwiseAnd(cloudBitmask).eq(0));
  // Update the original image, masking out cloud and cloud shadow-affected pixels
  return image.updateMask(mask);
}


//
/////////// SCALING FACTORS' FUNCTION LANDSAT \\\\\\\\\\\

// Scaling factors' function for LANDSAT 8.
function applyScaleFactorsL8(image) {
  var opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2);
  var thermalBands = image.select('ST_B.*').multiply(0.00341802).add(149.0);
  return image.addBands(opticalBands, null, true)
              .addBands(thermalBands, null, true);
}

// Scaling factors' function for LANDSAT 5.
function applyScaleFactorsL5(image) {
  var opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2);
  var thermalBand = image.select('ST_B6').multiply(0.00341802).add(149.0);
  return image.addBands(opticalBands, null, true)
              .addBands(thermalBand, null, true);
}


//
/////////// LST FUNCTION LANDSAT \\\\\\\\\\\

// Write a function that computes LST for an image and adds it as a band
function addLSTL8(image) {
  var lst = image.select('ST_B10').subtract(273.15).rename('lst');
  return image.addBands(lst);
}

// Write a function that computes LST for an image and adds it as a band
function addLSTL5(image) {
  var lst = image.select('ST_B6').subtract(273.15).rename('lst');
  return image.addBands(lst);
}


//
/////////// IMPORT AND FILTER LANDSAT COLLETION \\\\\\\\\\\

// Landsat8 dataset
var datasetL8 = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2')
    .filter(ee.Filter.or(
            //ee.Filter.date('2020-06-01', '2020-08-31'),
            //ee.Filter.date('2021-06-01', '2021-08-31'),
            //ee.Filter.date('2022-06-01', '2022-08-31'),
            ee.Filter.date('2014-01-01', '2024-01-01'))
          )
    .filterBounds(ROI)
    .filter(ee.Filter.lt('CLOUD_COVER', 20))
    .map(applyScaleFactorsL8)
    .map(cloudMask)
    .map(function(image){return image.clip(ROI)})
    .map(addLSTL8);
    
    
var datasetL5 = ee.ImageCollection('LANDSAT/LT05/C02/T1_L2')
    .filterDate('1985-01-01', '2012-01-01')
    .filterBounds(ROI)
    .filter(ee.Filter.lt('CLOUD_COVER', 20))
    .map(applyScaleFactorsL5)
    .map(cloudMask)
    .map(function(image){return image.clip(ROI)})
    .map(addLSTL5);
    


//
/////////// REDUCING COLLECTION \\\\\\\\\\\

// Reducing datasetL8 for LST median
var LSTreducerL8 = datasetL8
    .select('lst')
    .filter(ee.Filter.date('2023-08-15','2023-08-16'))
    .median()
    .clip(ROI);
    
// Reducing datasetL5 for LST median
var LSTreducerL5 = datasetL5
    .select('lst')
    .filter(ee.Filter.date('1986-08-08','1986-08-10'))
    .median()
    .clip(ROI);


//
/////////// VISUALIZATION PARAMETERS \\\\\\\\\\\

// LSTreducer parameters
var LSTVis =  {
    opacity:0.4,
    bands:['lst'],
    min: 29,
    max: 49,
    palette:['040274', '040281', '0502a3', '0502b8', '0502ce', '0502e6',
    '0602ff', '235cb1', '307ef3', '269db1', '30c8e2', '32d3ef',
    '3be285', '3ff38f', '86e26f', '3ae237', 'b5e22e', 'd6e21f',
    'fff705', 'ffd611', 'ffb613', 'ff8b13', 'ff6e08', 'ff500d',
    'ff0000', 'de0101', 'c21301', 'a71001', '911003']};


//
/////////// UI WIDGETS \\\\\\\\\\\

var mainPanel = ui.Panel({style: {width: '100%', height: '100%'}});
var infoPanel = ui.Panel({
  layout: ui.Panel.Layout.absolute(),
  style: {width: '100%', height: '10%'},
});

// Adding maps and panels
var mapL5 = ui.Map();
mapL5.addLayer(S2basemap, visualization, 'GrayScaleMap');
mapL5.addLayer(LSTreducerL5, LSTVis, 'LST-L5');
mapL5.setControlVisibility(false);
mapL5.setControlVisibility({
  zoomControl: true,
  layerList: true,
});
mapL5.setCenter(11.87, 45.40, 12);

var mapL8 = ui.Map();
mapL8.addLayer(S2basemap, visualization, 'GrayScaleMap');
mapL8.addLayer(LSTreducerL8, LSTVis, 'LST-L8');
mapL8.setControlVisibility(false);
mapL8.setControlVisibility({
  scaleControl: true, 
  layerList: true, 
  mapTypeControl: true,
  fullscreenControl: true,
  drawingToolsControl: true,
});

var panelL5 = ui.Panel({style: {width: '100%', height: '40%'}});
var titleL5 = ui.Label('Land Surface Temperature');
var chartPanelL5 = ui.Panel();
panelL5.add(titleL5);
panelL5.add(chartPanelL5);

var panelL8 = ui.Panel({style: {width: '100%', height: '40%'}});
var titleL8 = ui.Label('Land Surface Temperature');
var chartPanelL8 = ui.Panel();
panelL8.add(titleL8);
panelL8.add(chartPanelL8);

var linker = ui.Map.Linker([mapL5, mapL8]);

// Define a UI widget and add it to the map.
var panelSx = ui.Panel({style: {width: '50%', height: '100%'}});
panelSx.add(mapL5);
panelSx.add(panelL5);

var panelDx = ui.Panel({style: {width: '50%', height: '100%'}});
panelDx.add(mapL8);
panelDx.add(panelL8);

// Create a SplitPanel to hold the adjacent, linked maps.
var splitPanel = ui.SplitPanel({
  firstPanel: panelSx,
  secondPanel: panelDx,
  wipe: false,
  style: {stretch: 'both'}
});

// Display a time-series chart Landsat8
var chartL8 = ui.Chart.image.series({
  imageCollection: datasetL8.select('lst'),
  region: ROI,
  reducer: ee.Reducer.mean(),
  scale: 30,
}).setOptions({
      title: 'LST Time Series L8',
      vAxis: {title: '°C', viewWindow: {min:0, max:50}},
      hAxis: {title: '', format: 'YYYY-MMM'},
      lineWidth: 1,
      pointSize: 2,
      interpolateNulls: true
    });
chartPanelL8.add(chartL8);

// Display a time-series chart Landsat5
var chartL5 = ui.Chart.image.series({
  imageCollection: datasetL5.select('lst'),
  region: ROI,
  reducer: ee.Reducer.mean(),
  scale: 30,
}).setOptions({
      title: 'LST Time Series L5',
      vAxis: {title: '°C', viewWindow: {min:0, max:50}},
      hAxis: {title: '', format: 'YYYY-MMM'},
      lineWidth: 1,
      pointSize: 2,
      interpolateNulls: true
    });
chartPanelL5.add(chartL5);


// Creates a color bar thumbnail image for use in legend from the given color
// palette.
function makeColorBarParams(palette) {
  return {
    bbox: [0, 0, 1, 0.1],
    dimensions: '100x10',
    format: 'png',
    min: 0,
    max: 1,
    palette: palette,
  };
}

// Create the color bar for the legend.
var colorBar = ui.Thumbnail({
  image: ee.Image.pixelLonLat().select(0),
  params: makeColorBarParams(LSTVis.palette),
  style: {width: '200px', margin: '0px 0px', maxHeight: '10px'},
});

// Create a panel with three numbers for the legend.
var legendLabels = ui.Panel({
  widgets: [
    ui.Label(LSTVis.min, {margin: '0px 0px'}),
    ui.Label(
        (LSTVis.max / 2),
        {margin: '0px 0px', textAlign: 'center', width: '170px'}),
    ui.Label(LSTVis.max, {margin: '0px 0px'})
  ],
  layout: ui.Panel.Layout.flow('horizontal')
});

var legendTitle = ui.Label({
  value: 'Map legend: LST (°C)',
  style: {margin: '0px'},
});

var legendPanel = ui.Panel([legendTitle, colorBar, legendLabels]);
legendPanel.style().set('position', 'top-right');
legendPanel.style().set('margin', '-10px');
infoPanel.add(legendPanel);


ui.root.clear();
mainPanel.add(infoPanel);
mainPanel.add(splitPanel);
ui.root.add(mainPanel);

1 Answer 1

0

Rather than centering mapL5 and relying on the linker to center mapL8, try calling setCenter on both maps. That seems to solve the issue. You could also just create them both at the desired center like so:

var mapL5 = ui.Map({lon: 11.87, lat: 45.40, zoom: 12});
var mapL8 = ui.Map({lon: 11.87, lat: 45.40, zoom: 12});

My guess is that the inconsistent centering was caused by a timing issue with the linker. Sometimes it will run in this order and everything works fine:

  1. Map L5 is initialized at the default center.
  2. Map L8 is initialized at the default center.
  3. Map L5 is centered at the correct location, causing the linker to center L8 to it.

If the timing is slightly off however, you would see the unexpected result where both maps are at the default center:

  1. Map L5 is initialized at the default center.
  2. Map L5 is centered to the correct location.
  3. Map L8 is initialized at the default center, causing the linker to center L5 to it.
1
  • it doesn't always work, generally when I start it for the first time it works, if I change some code and press run it doesn't take the position immediately and I have to press run a few times before it gets me the right coordinates Commented Apr 22 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.