# directlabels - utility.function - Positioning Method - project.onto.segments

Given a point and a set of line segments representing a convex or alpha hull, calculate the closest point on the segments.

```project.onto.segments <- function
### Given a point and a set of line segments representing a convex or
### alpha hull, calculate the closest point on the segments.
(m,
### m is 1 row, a center of a point cloud, we need to find the
### distance to the closest point on each segment of the convex
### hull.
h,
### Data frame describing the line segments of the convex or alpha
### hull.
debug=FALSE,
...
### ignored
){
h\$s <- (h\$y2-h\$y1)/(h\$x2-h\$x1)
## the closest point on the line formed by expanding this line
## segment (this expression is calculated by finding the minimum
## of the distance function).
h\$xstar <- (m\$x + m\$y*h\$s + h\$x1*h\$s^2 - h\$s*h\$y1)/(h\$s^2+1)
h\$minval <- apply(cbind(h\$x1,h\$x2),1,min)
h\$maxval <- apply(cbind(h\$x1,h\$x2),1,max)
## xopt is the closest point on the line segment
h\$xopt <- ifelse(h\$xstar<h\$minval,h\$minval,
ifelse(h\$xstar>h\$maxval,h\$maxval,h\$xstar))
h\$yopt <- h\$s*(h\$xopt-h\$x1)+h\$y1
## distance to each point on line segment from the center
h\$d <- (m\$x-h\$xopt)^2+(m\$y-h\$yopt)^2
i <- which.min(h\$d)
result <- with(h[i,],data.frame(x=xopt,y=yopt))
if(debug){
grid.segments(m\$x,m\$y,result\$x,result\$y,default.units="cm")
}
result
}
```
 Please contact Toby Dylan Hocking if you are using directlabels or have ideas to contribute, thanks! Documentation website generated from source code version 2014.1.27 (svn revision 675) using inlinedocs. validate