getIdFromCoords <- function(coords,stations=NULL,N=1){ # Ensure coords is a numeric vector of length 2 (latitude and longitude) if (!is.numeric(coords) || length(coords) != 2) { stop("coords must be a numeric vector of length 2 (latitude, longitude)") } # Load stations data if not provided if (is.null(stations)) { stations <- getStations() # Further check to ensure stations is a data.frame and has required columns if (!is.data.frame(stations) || !all(c("Latitude", "Longitude", "Id_station") %in% names(stations))) { stop("stations must be a data frame with at least 'Latitude', 'Longitude', and 'Id_station' columns") } } if(is.null(stations))stations=getStations() # Calculate Euclidean distances and find the closest station station.alldist <- dist(rbind(coords, cbind(stations$Latitude, stations$Longitude))) closestIndexes <- order(as.matrix(station.alldist)[1, -1]) # Return the ID of the closest station return(stations[closestIndexes[1:N],]) }