I am trying to create a map with spatial data plotted on top. I am following the example using ggmap and then adding the New Zealand coastline using geom_sf. I have two problems:
- The projection of map_data(nz) doesn't match the projection of ggmap and so the coastline is not aligned to the map, even though both are in WGS84 lon, lat.
- When I try to apply coord_sf(xlim, ylim) to the plot I get a st_cast.POINT error:
The reprex requires a google key I'm afraid. The method in this post doesn't work for me
library(sf)
library(dplyr)
library(ggmap)
nz <- map_data("nz") %>%
st_as_sf(coords = c("long", "lat"), remove = FALSE, crs = st_crs(4326)) %>%
group_by(group) %>%
summarise(
region = region[1],
do_union = FALSE
) %>%
st_cast("LINESTRING") %>%
ungroup()
gkey <- readLines("sjrw_google_key.dat")
register_google(key = gkey)
basemap <- get_map(location = c(lon = 175.5, lat = -38),
zoom = 8,
maptype = 'terrain-background',
source = 'stamen')
attr(basemap, "bb")
#> ll.lat ll.lon ur.lat ur.lon
#> bottom -39.37417 173.7449 -36.604 177.2606
ggmap(basemap) +
geom_sf(data = nz, inherit.aes = FALSE) +
coord_sf(crs = st_crs(4326)) +
coord_sf(xlim = c(174.5, 176.5), ylim = c(-39.2, -36.6))
#> Coordinate system already present. Adding new coordinate system, which will replace the existing one.
# Error in st_cast.POINT(x[[1]], to, ...) :
# cannot create MULTILINESTRING from POINT
Created on 2021-10-21 by the reprex package (v2.0.1)