Find latitude/longitude centroid coordinates for countries, polygonal regions, or groups of points using countryCentroids.R.
Run the complete country workflow:
Rscript countryCentroids.RPrints first rows of centroids.out, which contains the Natural Earth country code, country name, and centroid latitude/longitude in decimal degrees.
Source the script, load polygonal regions into a terra SpatVector, and call calculate_polygon_centroids(). Returned data frame preserve region attributes and add lat and lon.
source("countryCentroids.R")
regions <- vect("regions.geojson")
region_centroids <- calculate_polygon_centroids(regions)region_centroids.R demonstrates how to create a GeoJSON polygon for a sub-country region. Replace the example longitude/latitude boundary coordinates with the region's boundary, then run:
Rscript region_centroids.RCreates example-region.geojson and prints its centroid. The coordinates use WGS 84 (EPSG:4326), are specified as longitude then latitude, and form the region boundary in order. Script closes the polygon automatically.
example_region_coordinates <- rbind(
c(151.10, -33.95),
c(151.30, -33.95),
c(151.30, -33.75),
c(151.10, -33.75)
)
create_region_geojson(
region_name = "Example region",
coordinates = example_region_coordinates,
output_path = "example-region.geojson"
)Pass a longitude/latitude SpatVector of point geometries to calculate_point_centroid(). It returns one latitude/longitude pair using a spherical mean, including for groups that cross the antimeridian.
source("countryCentroids.R")
points <- vect(
data.frame(lon = c(151.21, 144.96, 153.03), lat = c(-33.87, -37.81, -27.47)),
geom = c("lon", "lat"),
crs = "EPSG:4326"
)
point_centroid <- calculate_point_centroid(points)