How to get mapbox style openmap with API key? - r

I'm trying to make a map in R using OpenStreetMap library.
I had no problem using types such as osm, stamen-toner, stamen-terrain and stamen-watercolor, for instance:
map <- openproj(openmap(c(63.47,10.32),c(63.37,10.54),type='osm'),proj=CRS('+init=epsg:32632'))
par(mar=c(0,0,0,0))
plot(map)
works just fine:
I'll add the points over that layer. However, my client wants a map-box type, but when I run
map <- openproj(openmap(c(63.47,10.32),c(63.37,10.54),type='mapbox'),proj=CRS('+init=epsg:32632'))
I get the following error:
failed loading 12/2165/1106 Server returned HTTP response code: 401 for URL: http://api.tiles.mapbox.com/v4/examples.map-zr0njcqy/12/2165/1106.png?access_token=pk.eyJ1IjoidGhlZmVsbCIsImEiOiJjaXN1anNwODEwMWlrMnRvZHBhamRrZjlqIn0.Gf8qLSpZ6yo5yfQhEutFfQ
java.lang.NullPointerException
at edu.cens.spatial.RTileController.getTileValues(RTileController.java:109)
at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at RJavaTools.invokeMethod(RJavaTools.java:386)
Error in osmtile(x%%nX, y, zoom, type) :
could not obtain tile: 2165 1106 12
I know I need an API key. I've created one at MapBox site. But now, how do I get a map of map-box type? The examples given are like
apiKey <- paste0('?access_token=','{my key}')
baseUrl <- 'https://api.mapbox.com/styles/v1/mapbox/satellite-streets-v9/tiles/256/{z}/{x}/{y}'
map <- openproj(openmap(c(63.47,10.32),c(63.37,10.54),type=paste0(baseUrl,apiKey)),proj=CRS('+init=epsg:32632'))
I tried replacing satellite-streets-v9 with mapbox or simply deleting this directory, but it doesn't work. I don't know how to add my API key to the original command openmap(c(63.47,10.32),c(63.37,10.54),type='mapbox'). I couldn't find anything useful on mapbox's website, either.

I had to enter Mapbox Studio, create a default style (similar to the mapbox style I desired), to see on the "Layer overview" window that their default theme is called "Mapbox Streets v8". From there, I guessed that I should use
https://api.mapbox.com/styles/v1/mapbox/streets-v8/tiles/256/{z}/{x}/{y}
as my baseUrl. And it worked!

Related

Obtaining Metadata Information using ee_print function from RGEE

I am using the package RGEE (R wrapper for the Google Earth Engine Python API). The function ee_print() seems to work perfectly for an ImageCollection of just one variable, but seems to fail for ImageCollection with different variables where one needs to select the variable of interest. Any ideas on how to approach this issues with the latter kind of data.
Here's an example code:
GRIDMET = ee$ImageCollection("IDAHO_EPSCOR/GRIDMET")
ee_print(GRIDMET)
Where I get the following error message in return:
Error in strsplit(code, ":") : non-character argument
Have you considered the following approach?
GRIDMET = ee$ImageCollection("IDAHO_EPSCOR/GRIDMET")
print(GRIDMET, type = getOption("rgee.print.option"))
And play with the list of all metadata properties
GRIDMET$propertyNames()$getInfo()# Get a list of all metadata properties
(GRIDMET$get("product_tags")$getInfo()) # you can choose to show a characteristic like "product_tags"

Altering internal data in R package

I'm working on a package (let's call it myPackage) that needs to refer to external data, which is too big to incorporate into the package itself (it's a lot of netCDF files).
Because of this I have an internal PATH variable (which I initiate in /data-raw/, which saves it to sysdata.rda, and I've turned off lazy loading). When asked to get data, any function can then use this PATH to find the data.
I want the user to be able to specify their path, so I wrote a function:
setpath<-function(path){
myPackage:::PATH = path
}
Doing setpath("C:/") doesn't work. I get the error: Error in setpath("C:/") : object 'myPackage' not found.
I've also tried the following alternative function:
setpath<-function(path){
PATH = path
}
This way, the variable myPackage:::PATH never changes.
How should I be doing this? Is internal data read-only?
You can use options(). Create an option with
options(myPackageRepositoryPath = "some/path")
and retrieve it
path <- getOption(myPackageRepositoryPath)
The same way as you set an option, you also can overwrite an option:
setpath<-function(path){
options(myPackageRepositoryPath = path)
}

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)

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

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

Getting Internal Server Error when trying to use Gviz's IdeogramTrack

I posted this on Bioconductor's support page but didn't any answers hence trying here.
I am using the IdeogramTrack function of R/Biocondutor package, Gviz, from my institution's cluster:
IdeogramTrack(genome="mm10",chromosome="chr1")
When I try this from the master node it works fine but when I try this from any other node in the cluster which IO's through the master node, it hangs and eventually I get the error message:
Error: Internal Server Error
I am able to access enter link description here or any other UCSC mirror through these nodes (using traceroute http://genome.ucsc.edu), and can successfully download data from other repositories such as Ensembl, (e.g., using getBM).
Any idea what's wrong?
BTW, any idea which port is IdeogramTrack trying to use?
it sounds like your institution's cluster has issue fetching annotation data from UCSC through Gviz. One suggestion I have is to see if you can manually download mm9 annotation from UCSC; here is a good place to start, by chromosome. Alternatively, you may use a Bioconductor annotation package such as this.
When you have your data.frame with chromosome and chromosomal information (e.g. mapInfo), you could take advantage of GenomicRanges::makeGRangesFromDataFrame to convert the mm9 annotation to a GRanges object, which allows you to make your own IdeogramTrack object. Details on how to make custom IdeogramTrack can be found here.
In general, here is the workflow:
library(GenomicRanges)
library(Gviz)
mm9_annot <- read.table(<file or url with annotation>)
mm9_granges <- makeGRangesFromDataFrame(mm9_annot)
# Alternatively, you may use rtracklayer package
# mm9_granges <- rtracklayer::import(<file or url with annotation>)
my_ideo <- IdeogramTrack(genome="mm9_custom", bands=mm9_granges)
Hope this helps.

Resources