I am creating a map for sacramento city with a layer indicating the landuse and restricted to utility service area. I need to add a background map to make it more recognizable. Here is the map I am plotting
` Parcel_map<-
ggplot()+
geom_sf(data = Parcel, aes(fill = Land_Use), color = NA) +
geom_sf(data = Water_Boundary, fill = NA, color = "blue") +
scale_fill_viridis_c()+
labs(title = "Heatmap of Start of Tracking Period (2025 for all others)", fill = "Year_dum") +
labs(fill=" Meter Installation")+
theme_minimal()`
I have tried multiple ways to add google map as a background. One the way is following:
`myLocation <- c(-121.6, 38.4, -121.35, 38.7)
myMap <- get_map(location=myLocation, source="google", maptype="terrain", crop=FALSE)
ggmap(myMap)
`
However the final map is not getting produced using and throwing error.
> GParcel_map_Strt_dt_dm <-
+ ggmap(myMap)+
+ geom_sf(data = Parcel_Strt_dt, aes(fill = Year_dum), color = NA) +
+ geom_sf(data = Water_Boundary, fill = NA, color = "blue") +
+ scale_fill_viridis_c()+
+ labs(title = "Heatmap of Start of Tracking Period (2025 for all others)", fill = "Year_dum") +
+ labs(fill=" Meter Installation") +
+ coord_sf(datum = NA,
+ xlim = c(bbox['xmin'], bbox['xmax']),
+ ylim = c(bbox['ymin'], bbox['ymax'])) +
+ theme_minimal()
Coordinate system already present. Adding new coordinate system, which will replace the existing one.
> GParcel_map_Strt_dt_dm
Error in geom_sf():
! Problem while computing aesthetics.
ℹ Error occurred in the 4th layer.
Caused by error:
! object 'lon' not found
Run rlang::last_trace() to see where the error occurred.
I simply need a background map for my current map which look like following.

I've encountered a similar problem before, and if I remember correctly the error can be resolved by adding
inherit.aes = FALSEinside each call togeom_sf(). As the warning message indicates, there's already a coordinate system present frommyMap. Google returns the basemap as a raster layer in the EPSG: 3857 or "Google PseudoMercator" projection, whereas your othersfobjects are likely in a different CRS like EPGS: 4326 or WGS 84 (you can check withsf::st_crs(Parcel_Strt_dt), for instance).I found this StackOverflow post helpful when encountering this error, you might as well: How to put a geom_sf produced map on top of a ggmap produced raster.