The ggmap
R package provides a convenient way to download and plot Google satellite imagery. However, the function ggmap::get_map()
requires the selection of a Google zoom level in order to retrieve map tiles. The a priori selection of zoom level seems to effectively prevent the application of ggmap
programmatically. Others have had similar frustrations.
For example, using a dataset in the examples provided in the ggmap::get_map()
documentation and zoom level 8, you get a map that includes a lot of area beyond the bounding box that was supplied to ggmap::get_map()
.
library(ggplot2)
library(ggmap)
data(zips)
zips$area <- NULL # data has two columns named the same
zips.bbox <- c(left = min(zips$lon),
bottom = min(zips$lat),
right = max(zips$lon),
top = max(zips$lat))
class(zips.bbox) <- "bbox"
gg.map <- get_map(location = zips.bbox,
maptype = "satellite",
zoom = 8)
ggmap(gg.map) +
geom_polygon(aes(x = lon, y = lat, group = plotOrder),
data = zips,
colour = "white",
fill = "red",
alpha = .2)
But then if we do the same thing but with zoom level 10 to try to get a tighter fit, we way overshoot and ggmap::get_map()
does not bring in sufficient tiles at that zoom level to cover the entire bounding box.
gg.map <- get_map(location = zips.bbox,
maptype = "satellite",
zoom = 10)
ggmap(gg.map) +
geom_polygon(aes(x = lon, y = lat, group = plotOrder),
data = zips,
colour = "white",
fill = "red",
alpha = .2)
Is there a way to get the correct amount (i.e that exactly matches the supplied bounding box) of satellite image brought in on-the-fly without the user guessing the zoom level?
I can think of some ways to, based on the known size of Google tiles at various zoom levels, to come up with a way to auto-detect the highest zoom level that encompasses the whole area of interest. But even that is only going to get you so far, as that zoom level may include a ton of imagery outside of the area of interest. And that also forces you to use lower zoom levels (and therefor lower resolution image tiles) than you may want to. The ideal approach would allow specification of whatever zoom level you wanted and would ensure that all of the necessary tiles were downloaded to cover the entire area of interest.