在R中使用osmplotr和OpenStreetmap绘制海域

时间:2019-07-20 11:48:44

标签: r gis openstreetmap osmplotr

我正在尝试通过CRAN上的osmplotr包使用Openstreetmap来绘制海岸线并使海蓝色。由于海不是多边形,因此我尝试使用osm_line2poly()将线变成多边形。但是,下面的最小可重现示例给出以下错误:

Error in osm_line2poly(bar, bbox = mybbox) : 
  obj must be class 'sf' with fields of class 'sfc_LINESTRING'

似乎在说对象的类型不正确,但是如果我执行class(bar),则会导致:

[1] "sf"         "data.frame"

因此该类看起来确实确实是sf。任何指针,我都会很高兴。

代码紧随其后。

require(OpenStreetMap)
require(osmplotr)
require(osmdata)

# Define the bounding box
mybbox <- get_bbox (c(-4.9339, 52.0602, -4.7422, 51.9654))
# Get the coastline
dat_Z <- extract_osm_objects (key = 'natural', value = 'coastline', bbox = mybbox)
# Define the base map and its color
map <- osm_basemap (bbox = mybbox, bg = 'white')
# Add the coastline to the map
map <- add_osm_objects (map, dat_Z, col = 'gray40')
# And plot
print_osm_map (map)
# We want to color the sea (in the top-left quadrant) blue. In the docs:
# https://ropensci.github.io/osmplotr/reference/osm_line2poly.html
# ...it says 
# "Converts sf::sfc_LINSTRING objects to polygons by connecting end points 
# around the given bounding box. This is particularly useful for plotting water 
# and land delineated by coastlines. Coastlines in OpenStreetMap are lines, not
# polygons, and so there is no directly way to plot ocean water distinct from
# land. This function enables that by connecting the end points of coastline 
# LINESTRING objects to form closed polygons."

bar <- extract_osm_objects(mybbox, key = 'natural', value = 'coastline', 
                           return_type = 'polygon', sf = TRUE, geom_only = FALSE)

foo <- osm_line2poly(bar, bbox = mybbox)

输出: coastline using osmplotr

1 个答案:

答案 0 :(得分:1)

在软件包作者解决osm_line2poly之前,我认为您可以使用以下代码来绘制海域。这不是真正解决您的问题的方法,因为它使用不同的方法来绘制海域图,但也许就足够了。

# packages
library(osmdata)
#> Data (c) OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
library(tmap)
library(tmaptools)

# download from OSM coastline line for your bounding box
coastline_data <- opq(c(-4.9339, 52.0602, -4.7422, 51.9654)) %>% 
  add_osm_feature(key = 'natural', value = 'coastline') %>% 
  osmdata_sf()

# create the LINESTRING sf (i.e. the coastline) and the POLYGONS sf (i.e. the
# islands)
coastline <- coastline_data$osm_lines
islands <- coastline_data$osm_polygons

# download from OSM the tiles/raster data of the bounding box where the
# coastlines are
background_data <- read_osm(sf::st_bbox(coastline))

# plot
tm_shape(background_data) + 
  tm_rgb() + 
tm_shape(coastline_data$osm_lines) + 
  tm_lines() + 
tm_shape(coastline_data$osm_polygons) + 
  tm_polygons() + 
  tm_scale_bar() + 
  tm_compass(type = "8star", position = c("left", "top"))

reprex package(v0.3.0)

创建于2019-07-21