AWRA banner
Advancing Water Resources Research and Management

Symposium on Water Resources and the World Wide Web
Seattle, Washington, December 5-9, 1999

Java code to find the data point nearest the cursor

public int get_nearest_index(int x, int y) {
 //get the data nearest the mouse, if any
  //first check x,y
   int index = get_data_pointer(x,y);
  if(index == -1) {
  //then check concentric rings out to a radius of max_search.
  //this method ensures that the nearest point will be found first
  int max_search = 4;
  distance_loop: for (int d1 = 1;d1 <=max_search;d1++) {
    int d2 =0;
    int sign=1;
    int d2_inc=1;
    this_ring: while(true) {
        //Debug.println("dx "+  d1+", dy "+  d2);
        if((index = get_data_pointer(x+d1,y+d2)) != -1) {
           break distance_loop;
        }
        //Debug.println("dx "+ -d1+", dy "+ -d2);
        if((index = get_data_pointer(x-d1,y-d2)) != -1) {
           break distance_loop;
        }
        if(Math.abs(d1) != Math.abs(d2)) {
            //Debug.println("dx "+  d2+", dy "+  d1);
            if((index = get_data_pointer(x+d2,y+d1)) != -1) {
               break distance_loop;
            }
            //Debug.println("dx "+ -d2+", dy "+ -d1);
            if((index = get_data_pointer(x-d2,y-d1)) != -1) {
               break distance_loop;
            }
        }
        if(d2 == -d1) {
            break this_ring;
        }
        d2 += sign*d2_inc;
        d2_inc++;
        sign = -sign;
    }
  }
  }
  return index;
}

AWRA
Symposium TOC AWRA Home page

Maintainer: AWRA Webserver Team
Copyright © 1999 American Water Resources Association