[GIS] Waypoints with coordinates in R

coordinateslinepointr

I have a SpatialLineDataFrame with 20 observations of 4 variables (in WGS84). I want to create waypoints every 10 meters. Every waypoint will has the x y coordinates. I tried to do it manually like:

point_first=SpatialPoints(cbind(x,y)) 

for the first point, but there are many points I want to do, so it is not possible to do it that way. I think I need a loop but I don't know how to do it in order to have the coordinates for every waypoint.

Is there any command that I should use?

Best Answer

There is a nice tutorial on segmentation of spatial lines which you can find here, and you could make use of CreateSegment to achieve your goal. But first of all, let's create some sample data.

## german borders
library(rgdal)
library(rworldmap)

data(countriesCoarse)
spy_germany <- subset(countriesCoarse, GEOUNIT == "Germany")

## polygons to lines
sln_germany <- as(spy_germany, "SpatialLinesDataFrame")

Since you'd like to work with meters rather than degrees, reproject the data (e.g. to UTM) and extract the coordinates which we will require later on as input for CreateSegment.

## reprojection (utm-32n) and extraction of coordinates
sln_germany_utm <- spTransform(sln_germany, CRS("+init=epsg:32632"))
mat_germany_crd <- coordinates(sln_germany_utm)[[1]][[1]]

Next, let's create a sequence representing the desired segmentation. rgeos::gLength comes in quite handy for that. I chose segments of 100 km in length.

## border length and sequence of segments (100,000 m = 100 km)
library(rgeos)
num_len <- gLength(sln_germany_utm)

int_len_seq <- seq(0, num_len, 100000)

You can now loop over this sequence and extract the start and end coordinate of each single segment.

## loop over segments of 100 km
source("CreateSegment.R")

ls_crd_seg <- lapply(2:length(int_len_seq), function(i) {

  # extract coordinates of current line segment
  mat_segment <- CreateSegment(mat_germany_crd, 
                               from = int_len_seq[i-1], to = int_len_seq[i])

  # end coordinate
  crd_out <- matrix(mat_segment[nrow(mat_segment), ], ncol = 2)

  # during the first iteration, also return the start coordinate
  if (i == 2) {
    crd_start <- matrix(mat_segment[1, ], ncol = 2)
    crd_out <- rbind(crd_start, crd_out)
  } 

  return(crd_out)
})

Finally, rbind the coordinates and assign the projection of our initial shapefile. That's it!

## coordinates to SpatialPoints
crd_seg <- do.call("rbind", ls_crd_seg)
spt_seg <- SpatialPoints(crd_seg)
proj4string(spt_seg) <- proj4string(sln_germany_utm)

## visualize
plot(sln_germany_utm, lwd = 1.5)
points(spt_seg)

segmented_borders