Search code examples
rggplot2ggmap

get_googlemap: I need to calculate the bounds of a map given center and zoom level


I get the map using get_googlemap

location <- c(lon = -87.67946, lat = 41.86242)
map <- ggmap(get_googlemap(center = location, zoom = 11), extent = "device")

Once I have a ggmap, I want to learn what are the exact boundaries of my map to further use it for creating a heatmap from data with coordinates.

Please, help me calculate the bounds of a map given center and zoom level.

I tried looking for answer in ?get_googlemap and ?ggmap documentations but so far no luck.


Solution

  • The data member of the object map contains lat and lon columns that specify the bounds:

    library(ggmap)
    
    location <- c(lon = -87.67946, lat = 41.86242)
    map <- ggmap(get_googlemap(center = location, zoom = 11), extent = "device")
    
    range(map$data$lon)
    #> [1] -87.89884 -87.45939
    
    range(map$data$lat)
    #> [1] 41.69831 42.02560
    

    To demonstrate this is right, let's plot a red rectangle around our map using these numbers:

    map +
      annotate("rect", xmin = min(map$data$lon), xmax = max(map$data$lon),
               ymin = min(map$data$lat), ymax = max(map$data$lat), fill = NA,
               color = "red", linewidth = 3)
    

    enter image description here

    Or if you want to create a grid over the map,

    map + 
      geom_hline(yintercept = seq(min(map$data$lat), max(map$data$lat), len = 10)) +
      geom_vline(xintercept = seq(min(map$data$lon), max(map$data$lon), len = 10)) 
    

    enter image description here

    Created on 2023-07-15 with reprex v2.0.2