I am trying to construct a polygon using four latitude-longitude coordinates. However, the polygon does not get constructed as desired. The polygon lining is constructed way far than the lat-long points. I used the following code:
library(sf)
library(data.table)
library(dplyr)
library(tmap)
library(tmaptools)
lng1<- -158.04968046414533
lat1<- 21.67388250944907
lng2<- -158.0410973950371
lat2<- 21.684211388913273
lng3<- -158.0455176756356
lat3<- 21.669296090216402
lng4<- -158.0350892466561
lat4<- 21.679266380720016
latlong<- data.table(long= c(lng1, lng2, lng3, lng4), lat= c(lat1, lat2, lat3, lat4))
latlong_sf <- st_as_sf(latlong, coords = c("long", "lat"), crs = 4326)
conv_hawaii<- sf::st_simplify(st_buffer(st_convex_hull(st_union(st_geometry(latlong_sf))), dist = 25000), dTolerance = 5000)
#visulaization details
tm_shape(conv_hawaii)+
tm_borders(col = "gray", lwd = 1)
tmap_mode("view")
#> tmap mode set to interactive viewing
tm_shape(latlong_sf, bbox = bb(conv_hawaii, ext = 1))+
tm_dots(size = 0.5, alpha = 0.5)+
tm_shape(conv_hawaii)+
tm_borders(col = "gray", lwd = 2)+
tm_layout(frame = FALSE, title = "hawaii area",
title.size = 1.5, title.position = c(0.85, "bottom"))
What exactly are you trying to achieve? Polygon constructed from 4 points (full stop) or polygon from 4 points, buffered by 25 kilometers with its geometry simplified?
If the first point, which seems likely from the way your question is formulated, then you have some pieces of code superfluous.
Consider this piece of code; what it does it that it omits calls for sf::st_buffer()
and sf::st_simplify()
, with the union and convex hull left in place.
library(dplyr)
library(tmap)
library(tmaptools)
library(data.table)
library(sf)
lng1<- -158.04968046414533
lat1<- 21.67388250944907
lng2<- -158.0410973950371
lat2<- 21.684211388913273
lng3<- -158.0455176756356
lat3<- 21.669296090216402
lng4<- -158.0350892466561
lat4<- 21.679266380720016
latlong<- data.table(long= c(lng1, lng2, lng3, lng4), lat= c(lat1, lat2, lat3, lat4))
latlong_sf <- st_as_sf(latlong, coords = c("long", "lat"), crs = 4326)
conv_hawaii<- st_convex_hull(st_union(st_geometry(latlong_sf)))
#visulaization details
tm_shape(conv_hawaii)+
tm_borders(col = "gray", lwd = 1)
tmap_mode("view")
#> tmap mode set to interactive viewing
tm_shape(latlong_sf, bbox = bb(conv_hawaii, ext = 1))+
tm_dots(size = 0.5, alpha = 0.5)+
tm_shape(conv_hawaii)+
tm_borders(col = "gray", lwd = 2)+
tm_layout(frame = FALSE, title = "hawaii area",
title.size = 1.5, title.position = c(0.85, "bottom"))