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.

library(tidyverse)
library(sf)
library(units)

make_milepoint <- \(linestring, reverse = FALSE) {
  # make sure were using a projected coordinate systm
  linestring <- st_transform(linestring, 5070)
  
  # merge parts together into a multilinestring
  linestring <- linestring %>% group_by() %>% summarise()
  
  # if multiline string, then attempt to join together
  # this will raise an exception if the linestring is not contiguous 
  if (st_geometry_type(linestring) == 'MULTILINESTRING')
    linestring <- st_line_merge(linestring )
  
  # reverse the string if we want to 
  # go from the other end
  if (reverse) 
    linestring <- st_reverse(linestring)
  
  # length of string in miles
  linestring.distance = st_length(linestring) %>% set_units('mi') %>% 
    drop_units()
  
  # percent of string equals each mile including start and end
  linestring.sample.percent <- seq(0, 1, 1/linestring.distance) %>% c(1)
  
  # sample line string, convert multi-points to points, convert to sf
  # add a column listing the mile-points, round to two digits
  st_line_sample(linestring, sample = linestring.sample.percent) %>%
    st_cast('POINT') %>%
    st_as_sf() %>%
    mutate(
      mile = round(linestring.sample.percent * linestring.distance, digits = 2))
}

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 *