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

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.

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.

Make sure to enable billing. You don't have to restrict api, but make sure all the api's you need are enabled. if you want to search location names, you'll need geocoding api in addition to static maps. ggmap from CRAN is OK now (don't need github version).

it´s necessary confirm your credit card in Google API, with this, your API key is activated and you can use ggmap normally

Related

openmap NullPointerException Error in osmtile could not obtain tile

I am trying to plot a small rectangle of a map:
library(OpenStreetMap)
upper_left <- c(47.413, 8.551);
lower_right <- c(47.417, 8.556);
map_osm <- openmap(upper_left, lower_right, type = 'osm' );
plot(map_osm );
When I run that, the openmap function gives me the error Error in osmtile(x%%nX, y, zoom, type) : could not obtain tile: 540 298 10.
The documentation of OpenStreetMap seems to indicate that I need to add an API key. However, I am not sure how exactly I would do that (because I use type='osm', not type = url) and I am also unclear where I'd get such an API key from.
The java.lang.NullPointerException and the following R-error (Error in osmtile(...)) seem to come from an older version of OpenStreetMap.
By updating OpenStreetMap to the latest version (0.3.4 currently), the error disappears and the example code of OP should work as it is, without needing an API key.
The accepted answer is not adequate as the error can occur even with the most recent package version.
Sometimes if a particular area is not available in a specific style, you get an error similar to the one mentioned above independent of the package version. The solution would be to try the function with a different style. This is mentioned in the following blog post
As an example, the following modification may solve the issue:
library(OpenStreetMap)
upper_left <- c(47.413, 8.551);
lower_right <- c(47.417, 8.556);
map_osm <- openmap(upper_left, lower_right, type = 'opencyclemap');
plot(map_osm)

Unable to fetch maps with dismo gmap()

I am trying to follow a tutorial found here:
https://data.cdrc.ac.uk/tutorial/aa5491c9-cbac-4026-97c9-f9168462f4ac/4b026153-2953-4173-ab44-b24b2fb559fd
Note: the tutorial requires a free login to access
The step I am stuck at in the tutorial is this code:
library(raster)
library(dismo)
google.map <- gmap("Camden, London", type = "satellite")
I am having trouble getting dismo::gmap() to work. Every time I run it, I get
REQUEST_DENIED:Camden,London
Error in dismo::gmap("Camden, London", type = "satellite") : location not found
The same error pops up when I point it at any other location. Can anyone help?
Try reviewing the following:
Google now requires an API key.
See ?register_google for details.
?register_google

Rcrawler package: ContentScraper Error

i've a problem with ContentScraper function of Rcrawler package. I would like to extract from this site some information about time and airports of arrival and departure and also the price: (I took inspiration fom this site)
MY_Data=ContentScraper(CssPatterns = c(".leg",".price"), ManyPerPattern = T, Url = "http://www.skyscanner.it/trasporti/voli/rome/lond/180201?adults=1&children=0&adultsv2=1&childrenv2=&infants=0&cabinclass=economy&rtn=0&preferdirects=false&outboundaltsenabled=false&inboundaltsenabled=false&ref=day-view#results")
but i get this error:
Error in LinkExtractor(url = Ur, encod = encod) : object 'Extlinks' not found
I had a look to LinkExtractor function but i have no ideas of why it doesn't find Extlinks since it should be created by the function itself. Isn't it?
Someone could help me?
Thank You!
This website doesn't allow scraping. This may be one reason why your example doesn't work. You can try in this web. I also recommend you to try rvest package which is easier to use.
I have tried the same request using Rcrawler+phantomjs web driver but no result, There is some sort of javascript protection against unreal sessions,
br<-run_browser()
MY_Data<-ContentScraper(CssPatterns = c(".leg",".price"), ManyPerPattern = T, Url = "https://www.skyscanner.it/trasporti/voli/rome/lond/?adults=1&children=0&adultsv2=1&childrenv2=&infants=0&cabinclass=economy&rtn=0&preferdirects=false&outboundaltsenabled=false&inboundaltsenabled=false&ref=day-view&oym=1903&selectedoday=01", browser = br, RenderingDelay = 5)
I retrieved the session Screenshot, and I can confirm that the javascript which load results is stuck .
Using Rselenium+ chrome headless (with gpu enabled) I got robot check page. (see images)
As a result the only hope to get data legitimately is to use their API
Rcrawler creator

acs package in R: Cannot download dataset, error message is inscrutable

I am trying to use the acs package in R to download Census data for a basic map, but I am unable to download the data and I'm receiving a confusing error message.
My code is as follows:
#Including all packages here in case this is somehow the issue
install.packages(c("choroplethr", "choroplethrMaps", "tidycensus", "tigris", "leaflet", "acs", "sf"))
library(choroplethr)
library(choroplethrMaps)
library(tidycensus)
library(tigris)
library(leaflet)
library(acs)
library(sf)
library(tidyverse)
api.key.install("my_api_key")
SD_geo <- geo.make(state="CA", county = 73, tract = "*", block.group = "*")
median_income <- acs.fetch(endyear = 2015, span = 5, geography = SD_geo, table.number = "B19013", col.names="pretty")
Everything appears to work until the final command, when I receive the following error message:
trying URL 'http://web.mit.edu/eglenn/www/acs/acs-variables/acs_5yr_2015_var.xml.gz'
Content type 'application/xml' length 735879 bytes (718 KB)
downloaded 718 KB
Error in if (url.test["statusMessage"] != "OK") { :
missing value where TRUE/FALSE needed
In addition: Warning message:
In (function (endyear, span = 5, dataset = "acs", keyword, table.name, :
XML variable lookup tables for this request
seem to be missing from ' https://api.census.gov/data/2015/acs5/variables.xml ';
temporarily downloading and using archived copies instead;
since this is *much* slower, recommend running
acs.tables.install()
This is puzzling to me because 1) it appears like something is in fact being downloaded at first? and 2) 'Error in if (url.test["statusMessage"] != "OK") { :
missing value where TRUE/FALSE needed' makes no sense to me. It doesn't align with any of the arguments in the function.
I have tried:
Downloading the tables using acs.tables.install() as recommended in the second half of the error message. Doesn't help.
Changing the endyear and span to be sure that I'm falling within the years of data supported by the API. I seem to be, according to the API documentation. Have also used the package default arguments with no luck.
Using 'variable =' and the code for the variable as found in the official API documentation. This returns only the two lines with the mysterious "Error in if..." message.
Removing colnames = "pretty"
I'm going to just download the datafile as a CSV and read it into R for now, but I'd like to be able to perform this function from the script for future maps. Any information on what's going on here would be appreciated. I am running R version 3.3.2. Also, I'm new to using this package and the API. But I'm following the documentation and can't find evidence that I'm doing anything wrong.
Tutorial I am working off of:
http://zevross.com/blog/2015/10/14/manipulating-and-mapping-us-census-data-in-r-using-the-acs-tigris-and-leaflet-packages-3/#get-the-tabular-data-acs
And documentation of the acs package: http://eglenn.scripts.mit.edu/citystate/wp-content/uploads/2013/02/wpid-working_with_acs_R2.pdf
To follow up on Brandon's comment, version 2.1.1 of the package is now on CRAN, which should resolve this issue.
Your code runs for me. My guess would be that the Census API was temporarily down.
As you loaded tidycensus and you'd like to do some mapping, you might also consider the following code:
library(tidycensus)
census_api_key("your key here") # use `install = TRUE` to install the key
options(tigris_use_cache = TRUE) # optional - to cache the Census shapefile
median_income <- get_acs(geography = "block group",
variables = "B19013_001",
state = "CA", county = "San Diego",
geometry = TRUE)
This will get you the data you need, along with feature geometry for mapping, as a tidy data frame.
I emailed Ezra Haber Glenn, the author of the package, about this as I was having the same issue. I received a response within 30 minutes and it was after midnight, which I thought was amazing. Long story short, the acs package version 2.1.0 is configured to work with the changes the Census Bureau is making to their API later this summer, and it is currently presenting some problems windows users in the mean time. Ezra is going to be releasing an update with a fix, but in the mean time I reverted back to version 2.0 and it works fine. I'm sure there are a few ways to do this, but I installed the devtools package and ran:
require(devtools)
install_version("acs", version = "2.0", repos = "http://cran.us.r-project.org")
Hope this helps anyone else having a similar issue.

Using Bing option with taRifx.geo in R

I'm attempting to find the coordinates for several cities in Ghana. I've used the geocode function in taRifx.geo with the "google" option and had success, but Google doesn't know where all my cities are.
I'd like to use the Bing service to fill in the coordinates that were missing from my Google list and I'm starting with just one city ("Awutu Breku") to make sure the code works. I run this code, though, and get an error:
> Bkey <- "______________(my key would be here)____"
> Loc5 <- geocode("Awutu Breku", service="bing", BingMapsKey = Bkey,
+ returntype="coordinates")
Error in geocode.default("Awutu Breku", service = "bing", BingMapsKey = Bkey, :
To use Bing, you must save your Bing Maps API key (obtain at http://msdn.microsoft.com/en-us/library/ff428642.aspx) using options(BingMapsKey='mykey').
This error is very confusing since I do include the BingMapsKey argument but the function doesn't seem to be recognizing it.
I've searched quite a bit for an answer to this one and haven't come across anything. I even looked on the github page but couldn't figure out what might be wrong with my code. I feel like I'm missing something simple. Any help would be appreciated!
I needed to do a devtools::install_github("gsk3/taRifx.geo") to be able to use the geocode function and the instructions clearly state that you need to do a:
options(BingMapsKey='ridiculously_long_string')
before calling using the bing option:
geocode("1600 Pennsylvania Ave NW, Washington, DC 20500", service="bing")
## [1] 38.89719 -77.03655

Resources