R/LatLonToUTMEPSGCode.R

Defines functions LatLonToUTMEPSGCode

Documented in LatLonToUTMEPSGCode

#' UTM zone finder
#'
#' Find UTM EPSG code from Latitude and Longitude coordinates (EPSG 4326 WGS84)
#' (vectorised)
#' Source: https://geocompr.robinlovelace.net/reproj-geo-data.html
#' Source: https://gis.stackexchange.com/questions/13291/computing-utm-zone-from-lat-long-point
#'
#' @param lat The WGS84 latitude as a numeric value
#' @param lon The WGS84 longitude as a numeric value
#' @return A numeric ESPG UTM code
#' @export
#' @examples
#' UTM <- LatLonToUTMEPSGCode(45.33145,-18.33557)
#'
#'
LatLonToUTMEPSGCode <- function(lat, lon) {

  if(!is.numeric(lat)){
    stop("lat is not numeric")
  }

  if(!is.numeric(lon)){
    stop("lon is not numeric")
  }

  if(lat > 90 | lat < -90){
    stop("Latitude is greater than 90 north or less than 90 south ")
  }

  if(lon > 180 | lon < -180){
    stop("Longitude is greater than 180 east or less than 180 west")
  }

  zone_number <- (floor((lon + 180) / 6) %% 60) + 1

  # Special zones for Norway
  cond_32 <- lat >= 56.0 & lat < 64.0 & lon >= 3.0 & lon < 12.0
  zone_number[cond_32] <- 32

  # Special zones for Svalbard
  cond_lat <- lat >= 72.0 & lat < 84.0

  cond_31 <- cond_lat & lon >= 0.0 & lon <  9.0
  zone_number[cond_31] <- 31

  cond_33 <- cond_lat & lon >= 9.0 & lon < 21.0
  zone_number[cond_33] <- 33

  cond_35 <- cond_lat & lon >= 21.0 & lon < 33.0
  zone_number[cond_35] <- 35

  cond_37 <- cond_lat & lon >= 33.0 & lon < 42.0
  zone_number[cond_37] <- 37

  # EPSG code
  utm <- zone_number
  utm[lat > 0] <- utm[lat > 0] + 32600
  utm[lat <= 0] <- utm[lat <= 0] + 32700

  return(utm)
}
HiDef-Aerial-Surveying/HiDEF documentation built on Nov. 21, 2023, 5:54 a.m.