Create Mile Points from a LINESTRING or MULTILINESTRING in R

Here is an R function that takes a LINESTRING or touching MULTILINESTRING and returns a series of points along the line string at each mile, much like the β€œtombstone” mile markers along an expressway. This is helpful for making maps when you want to plot distance for hikers or drivers looking at their odometer of their car. It has the option to β€œreverse” the linestring so you can have the points going the opposite direction of the linestring, such as south to north. The code can be modified for quarter mile points or however you find useful.

01library(tidyverse)
02library(sf)
03library(units)
04 
05make_milepoint <- \(linestring, reverse = FALSE) {
06  # make sure were using a projected coordinate systm
07  linestring <- st_transform(linestring, 5070)
08   
09  # merge parts together into a multilinestring
10  linestring <- linestring %>% group_by() %>% summarise()
11   
12  # if multiline string, then attempt to join together
13  # this will raise an exception if the linestring is not contiguous
14  if (st_geometry_type(linestring) == 'MULTILINESTRING')
15    linestring <- st_line_merge(linestring )
16   
17  # reverse the string if we want to
18  # go from the other end
19  if (reverse)
20    linestring <- st_reverse(linestring)
21   
22  # length of string in miles
23  linestring.distance = st_length(linestring) %>% set_units('mi') %>%
24    drop_units()
25   
26  # percent of string equals each mile including start and end
27  linestring.sample.percent <- seq(0, 1, 1/linestring.distance) %>% c(1)
28   
29  # sample line string, convert multi-points to points, convert to sf
30  # add a column listing the mile-points, round to two digits
31  st_line_sample(linestring, sample = linestring.sample.percent) %>%
32    st_cast('POINT') %>%
33    st_as_sf() %>%
34    mutate(
35      mile = round(linestring.sample.percent * linestring.distance, digits = 2))
36}

Here is an example of the 1 mile points it outputs along Piseco-Powley Road.

And here is a static (paper) map I created using this code plus adding coordinates and elevation for this hiking map.

Soda Range Trail

Leave a Reply

Your email address will not be published. Required fields are marked *