Skip to content

Instantly share code, notes, and snippets.

@jrosell
Created March 27, 2025 12:26
Show Gist options
  • Save jrosell/cb3d2492b5dc9c52663c65f96965dabf to your computer and use it in GitHub Desktop.
Save jrosell/cb3d2492b5dc9c52663c65f96965dabf to your computer and use it in GitHub Desktop.
An example service using R API to obtain the country from latitude and longitude coordinates.
# plumber::plumb("country_from_coordinates_api.R")$run(port = 8000)
library(plumber)
library(httr2)
library(rlang)
#* @serializer html
#* @get /
function() {
html_content <- '<!DOCTYPE html>
<html>
<head>
<title>Country Lookup</title>
</head>
<body>
<h1>Country Lookup by Coordinates</h1>
<div id="result"></div>
<script>
function lookupCountry(lat, lng) {
var error = 0;
document.getElementById("result").innerHTML = "Loading..."
fetch(`/countryCode?lat=${lat}&lng=${lng}`)
.then(response => response.json())
.then(data => {
console.log(data)
if(data.status == 0){
document.getElementById("result").innerHTML =
`Country: ${data.countryName} (${data.countryCode})`;
} else {
console.error("Error:", data.message);
document.getElementById("result").innerHTML =
"Error fetching country information";
}
})
.catch(error => {
console.error("Error:", error);
document.getElementById("result").innerHTML =
"Error fetching country information";
});
}
lookupCountry(47.03, 10.2);
</script>
</body>
</html>'
html_content
}
#* @apiTitle GeoNames Country Lookup
#* @param lat Latitude
#* @param lng Longitude
#* @get /countryCode
function(lat, lng) {
# GeoNames API call
tryCatch({
response <- request("http://api.geonames.org/countryCodeJSON") |>
req_url_query(
lat = lat,
lng = lng,
username = "demo",
type = "JSON",
formatted = "true",
style = "full"
) |>
req_perform() |>
resp_body_json()
# Print the response for debugging
print(response)
# Return the country information
list(
message = response$status$message %||% "",
status = response$status$value %||% 0,
countryName = response$countryName %||% "",
countryCode = response$countryCode %||% ""
)
}, error = function(e) {
# Error handling
list(
message = as.character(e),
status = 1,
countryName = "",
countryCode = ""
)
})
}
#* @filter cors
cors <- function(req, res) {
res$setHeader("Access-Control-Allow-Origin", "*")
res$setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
res$setHeader("Access-Control-Allow-Headers", "Content-Type")
plumber::forward()
}
#* @get /favicon.ico
function() {
list(
status = 200,
body = raw(0),
headers = list("Content-Type" = "image/x-icon")
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment