# [R-sig-Geo] closest points between 2 polygons

Bastien.Ferland-Raymond at mrn.gouv.qc.ca Bastien.Ferland-Raymond at mrn.gouv.qc.ca
Thu Apr 18 14:39:15 CEST 2013

```Hello,

I don't have a clear solution for your problem, but I'll try to give you ideas to where to look that may help you.  If I understand well your problem, the difficulty comes from the fact that you have two POLYGONS and that you are looking for the COORDINATES.

You could transform your polygons in polylines with something like:

####
polygon2polyline <- function(poly.shape) {                                                          # On donne un object de classe SpatialPolygonsDataFrame
coo <- lapply((slot(poly.shape,"polygons")),function(xx) lapply(xx at Polygons, slot, "coords"))       # Sort les coordonnées des polygones
IDs <- sapply(slot(poly.shape, "polygons"), slot, "ID")                                             # Sort les IDs des polygons

shape.line <- vector(mode="list",length=length(coo))                                                # boucle qui crée la liste de Lines.  Pourrait être changé par un Lapply si on trouve le moyen de gérer les IDs
for (i in 1:length(coo)){
shape.line[[i]] <- Lines(lapply(coo[[i]], Line),ID=IDs[i])
}
shape <- SpatialLinesDataFrame(SpatialLines(shape.line,proj4string = CRS(proj4string(poly.shape))), data=poly.shape at data)  # Crée la nouvelle shape de lignes
shape                                                                                               # sort un object de classe SpatialLinesDataFrame
}
####

Than, using polylines may help with some functions like:  dist2line() from the geosphere package.  There is also some homemade function that do a similar task available at: http://geotux.tuxfamily.org/index.php/en/geo-blogs/item/296-snapping-points-to-lines-in-r

However, both of those functions require a line and a point...   You have two lines.  Maybe you can modify them?

Another idea, which would not give you the real answer but close and requires tons of computing power so it may not help you much is to use the costDistance() function of gdistance.

1) you transform both your polygons to lines,
2) you select one of the polygon,
3) you rasterize it, finer is better,
4) you calculate the costDistance from this raster,
5) you superpose the second polygons on the costDistance raster,
6) you identify every cell from the raster that touches the line of the second polygon,
7) you identify the cell with the minimum distance.  The coordinates from the second polygon that is the closest to the first polygon is there.
8) inverse the process or use the functions proposed before to identify the closest point from the first polygon.

As I said, it's very complicated for what should be a simple task, however it's the best I can think of right now.

Good luck,

Bastien Ferland-Raymond

```