2

I want to calculate a min cost path from a start point to a end point. Because the GEE has not provide the function, I have to code it by myself. The first step is to get the start and end point from the map by Map.Onclick function. How can I pass these points into the function for calculating min cost path?

function MinCostPath (){   
  var points = selectPoints.getValue();//wrong code here
  print(points); 
}

var selectPoints = ui.Select({
  items:['Start point', 'End point'], 
  
  placeholder: 'Choose input start or end point...',
  
  onChange: function(key) {
    print("The point needed to be clicked on the map is:" + key);
    
    Map.style().set('cursor', 'crosshair');
  
    Map.onClick(function(coords) {
      var point = ee.Geometry.Point(coords.lon, coords.lat);
      print(point);
      
      var dot = ui.Map.Layer(point, {color: 'FF0000'},key);
    
      Map.layers().add(dot);
    
      Map.unlisten();
    });
  },
  });

var pathBtn = ui.Button({
  label: 'Caculating min cost path...',
  onClick: MinCostPath
});

var panel = ui.Panel([selectPoints,pathBtn]);
panel.style().set({
  width: '250px',
  position: 'bottom-left'
});

Map.add(panel);

1 Answer 1

1

You can keep track of the selected points in a global variable:

var startPointKey = 'Start point'
var endPointKey = 'End point'
var selectedPoints = {}

function minCostPath() {   
  var startPoint = selectedPoints[startPointKey]
  var endPoint = selectedPoints[endPointKey]
  print('minCostPath', startPoint, endPoint)
}

var selectPoints = ui.Select({
  items:[startPointKey, endPointKey], 
  placeholder: 'Choose input start or end point...',
  onChange: function(key) {
    print("The point needed to be clicked on the map is:" + key);
    Map.style().set('cursor', 'crosshair');
  
    Map.onClick(function(coords) {
      var point = ee.Geometry.Point(coords.lon, coords.lat);
      print(point);
      selectedPoints[key] = point
      if (Object.keys(selectedPoints).length === 2) {
        pathBtn.setDisabled(false) // Enable when there are two points selected
      }a
      
      var dot = ui.Map.Layer(point, {color: 'FF0000'},key);
      Map.layers().add(dot);
      Map.unlisten();
    });
  },
  });

var pathBtn = ui.Button({
  label: 'Caculating min cost path...',
  onClick: minCostPath,
  disabled: true // Keep disabled until there are two points selected
});

var panel = ui.Panel([selectPoints,pathBtn]);
panel.style().set({
  width: '250px',
  position: 'bottom-left'
});

Map.add(panel);

https://code.earthengine.google.com/390262b9baa019b959c42748020457ee

1
  • Thank you very much for your instruction! Commented Oct 2, 2021 at 1:55

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.