I found a fairly simple example of how to do this but I cant get it to work for me. I\'m pretty new to R
library(rgdal)
xy <- cbind(c(118, 119), c(10, 50
Regarding the example, the default UTM Zone for the given coordinates is 50. It is not advised to project coordinates into far away zones. You can check the conversion using the NCAT tool from NOAA.
The code below uses the sf
package for doing the conversion.
library(sf)
library(tidyverse)
# Coordinate examples with expected UTM values
coord_sample <- data.frame(
"Northing" = c(1105578.589, 5540547.370),
"Easting" = c(609600.773, 643329.124),
"Latitude" = c(10, 50),
"Longitude" = c(118, 119))
#' 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
LatLonToUTMEPSGCode <- function(lat, lon) {
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)
}
sf_sample <- sf::st_as_sf(coord_sample, coords = c("Longitude", "Latitude"),
crs = 4326)
sf_sample %>%
do(cbind(., st_coordinates(.))) %>%
mutate(EPSG = LatLonToUTMEPSGCode(lat = Y, lon = X)) %>%
group_by(EPSG) %>%
do(cbind(as.data.frame(.) %>% select(Northing, Easting),
st_coordinates(st_transform(., crs = head(.$EPSG, 1))))) %>%
ungroup()
You can check the conversion by comparing with the expected values:
# A tibble: 2 x 5
EPSG Northing Easting X Y
1 32650 1105579 609601 609601 1105579
2 32650 5540547 643329 643329 5540547