Convert sequence of longitude and latitude to polygon via sf in R

前端 未结 4 1607
误落风尘
误落风尘 2020-12-09 12:17

I have five longitude and latitude that form a shape like this.

df <- c(order=1:5,
        lon=c(119.4,119.4,119.4,119.5,119.5), 
        lat=c(-5.192,-5.         


        
4条回答
  •  离开以前
    2020-12-09 12:43

    I saw that this question is coming up in search results, so I thought I'd provide a more flexible method of creating polygons in sf from a series of lat and lon coordinates.

    st_as_sf has an argument coords that will take points given as coordinate columns in a data frame and convert those columns to sf POINT geometries. Then, because sf works well with dplyr, we can st_combine the points into a MULTIPOINT and st_cast to convert to POLYGON. Compared to "manual" construction with st_polygon, this has the advantage that we don't have to think so carefully about closing the ring or about the right level of nested lists to pass to the constructor, and that if we have more than one polygon in a list of coordinates we can use group_by to create all the polygons at once.

    N.B. Technically you can do this with do_union=FALSE inside of summarise, but I think that this syntax is a bit clearer and more similar to normal summarise.

    df <- data.frame(
      lon = c(119.4, 119.4, 119.4, 119.5, 119.5),
      lat = c(-5.192, -5.192, -5.187, -5.187, -5.191)
    )
    library(tidyverse)
    library(sf)
    #> Linking to GEOS 3.6.1, GDAL 2.2.3, proj.4 4.9.3
    polygon <- df %>%
      st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
      summarise(geometry = st_combine(geometry)) %>%
      st_cast("POLYGON")
    polygon
    #> Simple feature collection with 1 feature and 0 fields
    #> geometry type:  POLYGON
    #> dimension:      XY
    #> bbox:           xmin: 119.4 ymin: -5.192 xmax: 119.5 ymax: -5.187
    #> epsg (SRID):    4326
    #> proj4string:    +proj=longlat +datum=WGS84 +no_defs
    #>                         geometry
    #> 1 POLYGON ((119.4 -5.192, 119...
    
    plot(polygon)
    

    Created on 2018-10-05 by the reprex package (v0.2.0).

提交回复
热议问题