Quick way to capture polygons and add them to a PostGIS data base from an R session

The session has to be running interactively. This does not work directly from a markdown document, for obvious reasons. However the code will work as a script.

First connect to a data base and load in a section of interest. For example a watershed.

library(RPostgreSQL)
library(sf)
library(mapedit)
library(mapview)


conn <- dbConnect("PostgreSQL", host = "postgis", dbname = "clima2" ,
                    user = "docker", password = "docker")

cuenca<-st_read(conn, query= "select * from cuenca")

Now just run this code using mapedit to open up an interactive editor in RStudio. The polygons that are drawn will be saved on exiting.

## Must run in an R session
d <- mapview(cuenca) %>% editMap()

Now load the results to the data base.

## Must run in an R session

test<-d$finished
dbSendQuery(conn, "drop table test")
st_write(test,conn,update=True)
## Show the results have been saved in the database

test<- st_read(conn, query= "select * from test")
mapview(test) + mapview(cuenca)

This would be handy to do in shiny, but I’ve not worked out how as yet.

Disconnect

dbDisconnect(conn)
## [1] TRUE