GRASS Programmer's Manual  6.4.2(2012)
gis/line_dist.c
Go to the documentation of this file.
00001 #include <grass/gis.h>
00002 /* compute square of distance of point (x,y) to line segment (x1,y1 - x2,y2) */
00003 
00004 #define ZERO(x) x < tolerance && x > -tolerance
00005 #define TOLERANCE 1.0e-10
00006 static double tolerance = TOLERANCE;
00007 
00008 int G_set_distance_to_line_tolerance(double t)
00009 {
00010     if (t <= 0.0)
00011         t = TOLERANCE;
00012     tolerance = t;
00013 
00014     return 0;
00015 }
00016 
00017 double G_distance2_point_to_line(double x, double y,    /* point */
00018                                  double x1, double y1, double x2, double y2)
00019 {                               /* line segment */
00020     double dx, dy, t;
00021 
00022     dx = x2 - x1;
00023     dy = y2 - y1;
00024 
00025     if (ZERO(dx) && ZERO(dy)) { /* line is degenerate */
00026         dx = x1 - x;
00027         dy = y1 - y;
00028         return dx * dx + dy * dy;       /* compute distance x,y to x1,y1 */
00029     }
00030 
00031     t = (dx * (x - x1) + dy * (y - y1)) / (dx * dx + dy * dy);
00032 
00033     if (t < 0.0) {              /* go to x1,y1 */
00034         dx = x - x1;
00035         dy = y - y1;
00036     }
00037     else if (t > 1.0) {         /* go to x2,y2 */
00038         dx = x - x2;
00039         dy = y - y2;
00040     }
00041     else {                      /* go t from x1,y1 towards x2,y2 */
00042 
00043         dx = x - (dx * t + x1);
00044         dy = y - (dy * t + y1);
00045     }
00046     return dx * dx + dy * dy;
00047 }
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines