[GRASSLIST:3871] Re: distance between polygons

Glynn Clements glynn.clements at virgin.net
Wed Jun 12 10:39:40 EDT 2002


Johannes B|hler wrote:

> > That won't necessarily produce the correct answer. The shortest
> > distance could be between a vertex of one polygon and a point on an
> > edge of the other polygon.
> 
> you are right. I need the shortest distance between a vertex and an 
> edgepoint. is there a solution for this?

The following function[1] computes the square of the shortest distance
between a point and a line segment (which is either the distance to
the line, or the distance to one of the endpoints).

[1] from src/libes/vect32/diglib/line_dist.c

double dig_distance2_point_to_line (
    double x,double y,         /* point */
    double x1,double y1,double x2,double y2)	/* line segment */
{
    register double dx,dy;
    double t;

    dx = x2 - x1;
    dy = y2 - y1;

    if (ZERO(dx) && ZERO(dy)) /* line is degenerate */
    {
	dx = x1 - x;
	dy = y1 - y;
	return dx*dx + dy*dy;	/* compute distance x,y to x1,y1 */
    }

    t = (dx * (x - x1) + dy * (y - y1)) / (dx * dx + dy * dy);

    if (t < 0.0)		/* go to x1,y1 */
	t = 0.0;
    else if (t > 1.0)		/* go to x2,y2 */
	t = 1.0;

/* go t from x1,y1 towards x2,y2 */
    dx = dx * t + x1 - x;
    dy = dy * t + y1 - y;

    return dx*dx + dy*dy;
}

-- 
Glynn Clements <glynn.clements at virgin.net>



More information about the grass-user mailing list