R: Error in get_map()/get_googlemap() from ggmap

mrsquid picture mrsquid · Jan 25, 2019 · Viewed 7.7k times · Source

I am trying to use GGmap to create a plot of vehicle car crashes by state. The map will have dots which are sized based on the number of car crashes in the state.

In particular I am trying to recreate the usa-plot shown in the visualizing clusters section of this blog post.

However, whenever I try to create the map I get this error.

Error in aperm.default(map, c(2, 1, 3)) : 
  invalid first argument, must be an array

I have setup the Google API and see that it is recieving hits. I have also enabled it and have the key.

In addition I have installed GGmap from the github account using this command:

devtools::install_github("dkahle/ggmap", ref = "tidyup", force=TRUE)

since the CRAN one isn't updated.

I have restarted and quit R several times as well but the error persists.

Even if I just simply run:

get_map()

it still results in the error:

Error in aperm.default(map, c(2, 1, 3)) : 
      invalid first argument, must be an array

Below is my code, it is similar to the code in the blog post:

mydata$State <- as.character(mydata$State)
mydata$MV.Number = as.numeric(mydata$MV.Number)
mydata = mydata[mydata$State != "Alaska", ]
mydata = mydata[mydata$State != "Hawaii", ]
devtools::install_github("dkahle/ggmap", ref = "tidyup", force=TRUE)
library(ggmap)
ggmap::register_google(key = "...") #my key is here
for (i in 1:nrow(mydata)) {
  latlon = geocode(mydata[i,1])
  mydata$lon[i] = as.numeric(latlon[1])
  mydata$lat[i] = as.numeric(latlon[2])
}
mv_num_collisions = data.frame(mydata$MV.Number, mydata$lon, mydata$lat)

colnames(mv_num_collisions) = c('collisions','lon','lat')
usa_center = as.numeric(geocode("United States"))


USAMap = ggmap(get_googlemap(center=usa_center, scale=2, zoom=4), 
extent="normal")
USAMap + 
   geom_point(aes(x=lon, y=lat), data=mv_num_collisions, col="orange", 
alpha=0.4, size=mv_num_collisions$collisions*circle_scale_amt) +  
   scale_size_continuous(range=range(mv_num_collisions$collisions))

I expect the map to output like this

But I cannot seem to get passed this error.

If anyone can help that would be great.

Please let me know if you need any more information.

Thank you.

Answer

Roger-123 picture Roger-123 · May 21, 2019

This error is due to the google key not having the appropriate API activity enabled for that key.

Go into the google API console and enable the API "Maps Static API" and it should work for you.

EDIT: Jan 2020 - I was doing some similar work and found that a similar API was failing because billing information had to be added to the project in the Google Cloud console before it would work.