import ucar.ma2.Array;
import ucar.nc2.dt.GridCoordSystem;
import ucar.nc2.dt.grid.GridDataset;
import ucar.nc2.dt.grid.GeoGrid;

import java.io.IOException;

/**
 * Demo of how to read a value from a grid given a lat, lon value.
 */
public class ReadByLatLon {
    public static void main (String[] args) {
        String inputFile = "data/max_min_rain70.nc";

        double lat = 11;
        double lon = 78;
        int[] xy = new int[2];

        try (GridDataset gds = GridDataset.open(inputFile)) {
            GeoGrid grid = gds.findGridByName("temp");
            GridCoordSystem gcs = grid.getCoordinateSystem();
            gcs.findXYindexFromLatLon(lat, lon, xy);
            Array valueAtLatLon = grid.readDataSlice(0, 0, xy[1], xy[0]);
            // Print a report
            System.out.format("Requested Variable: %s\n", grid.getFullName());
            System.out.format("Requested Latitude, Longitude: %3.1f, %3.1f\n",lat, lon);
            System.out.format("%s value from closest grid point: %3.1f\n", grid.getFullName(),
                    valueAtLatLon.getFloat(0));
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}
