ggmap and Google Earth not giving same position (R) - r

I'm currently trying to plot the position of some weather stations in Switzerland. Using pretty standard code with ggmap and geom_point.
register_google(key = "YOUR KEY")
map <- get_map(location='Bern', zoom=12, maptype = "terrain", color = "color")
ggmap(map) + geom_point( aes(x=stations_coord$long, y=stations_coord$lat)
, data = stations_coord, colour = "red", size = 3 )
Problem: All values are misplaced in the plot when comparing to Google Earth
Here is an example for the Bern station.
I really don't understand how this is possible. Also there are no threads on this issue anywhere.
Could anyone help me?

The satellite map and terrain maps use different datums. You are comparing a satellite image with a terrain map - those are different maps and are likely to use different datums. The default datum for google earth (the screencap of your web browser) is WGS84. I don't know what the default datum for the terrain map is but it appears to be different.
Try changing 'maptype = "satellite"' and you will get the same lat/long:
map <- get_map(location='Bern', zoom=12, maptype = "satellite", color = "color")
ggmap(map) + geom_point( aes(x=stations_coord$long, y=stations_coord$lat)
, data = stations_coord, colour = "red", size = 3 )
Futher reading on datums: https://en.wikipedia.org/wiki/Geodetic_datum
A side note: accidents happen all the time because of this. Ships reading GPS are using one datum and their charts (maps) are in another datum, so they aren't where they think they are and can crash into stuff. This can also happen with aircraft and in land navigation.
Bottom line: ggmap uses the datums associated with the map that you tell it to look at. You are telling ggmap to look at one type of map (terrain) and comparing it with another type of map (satellite) - probably different datums.

Related

Displaying counts instead of "levels" using stat_density2d

My objective is to portray the locations with varying numbers of traffic conflicts in a road intersection. My data consists of all the conflicts that we observed in a given time period at an intersection coded into a .CSV file with the following fields "time of conflict", "TTC" (means Time to Collision), "Lat", "Lon" and "Conflict Type". I figured the best way to do so would be using the 'ggmap+stat_density2d' function in R. I am using the following code:
df = read.csv(filename, header = TRUE)
int.map = get_map(location = c(mean.long, mean.lat), zoom = 20, maptype = "satellite")
int.map = ggmap(int.map, extent ="device", legend = "right")'''
int.map +stat_density2d(data = new_xdf, aes(x, y, fill = ..levels.., alpha = ..levels..),
geom = "polygon")
int.map + scale_fill_gradientn(guide = "colourbar", colours = rev(brewer.pal(7,"Spectral")),
name = "Conflict Density")
The output is a very nice map Safety Heat Map that correctly portrays the conflict hotspots. My problem is that in the legends it gives the values of "levels" automatically calculated by the 'stat_density2d()' function. I tried searching for a way to display, say, the counts of all conflict points inside each level on the legend bar but to no avail.
I did find the below link that handles a similar question, but the problem with that is that it creates a new data frame (new_xdf) with much more points than in the original data. Thus, the counts determined in that program seems to be of no use to me as I want the exact number of conflict points in my original data to be displayed in the legends bar.
How to find points within contours in R?
Thanks in advance.
Edit: Link to a sample data file
https://docs.google.com/spreadsheets/d/11vc3lOhzQ-tgEiAXe-MNw2v3fsAqnadweVrvBdNyNuo/edit?usp=sharing

How to get only street labels with get_googlemap

I´m trying to get only the street labels from Google Maps API using get_googlemap()from the ggmap package. I read Google Static Maps Developer and also this and managed to get rid of the labels of the adminsitrative feature by specifying style = "feature:administrative|visibility:off"
cntr <- c(-71.445, -33.055)
map <- get_googlemap(location = "Chile", center = cntr,
zoom = 13, source = "google",
maptype ="roadmap", color = "bw",
style = "feature:administrative|visibility:off")
mapplot <- ggmap(map)
But I´m still struggling to just get the map with the street labels. Is there a way to do it? or get_googlemap doesn't support that option? I have tried with style = "feature:landscape|visibility:off" but nothing changes, when I use style = "feature:landscape|element:geometry|visibility:off" I get this:

spplot/lattice: objects not drawn/overdrawn

I have a grid and I want to produce a map out of this grid with some map elements (scale, north arrow, etc). I have no problem drawing the grid and the coloring I need, but the additional map elements won't show on the map. I tried putting first=TRUE to the sp.layout argument according to the sp manual, but still no success.
I reproduced the issue with the integrated meuse dataset, so you may just copy&paste that code. I use those package versions: lattice_0.20-33 and sp_1.2-0
library(sp)
library(lattice) # required for trellis.par.set():
trellis.par.set(sp.theme()) # sets color ramp to bpy.colors()
alphaChannelSupported = function() {
!is.na(match(names(dev.cur()), c("pdf")))
}
data(meuse)
coordinates(meuse)=~x+y
data(meuse.riv)
library(gstat, pos = match(paste("package", "sp", sep=":"), search()) + 1)
data(meuse.grid)
coordinates(meuse.grid) = ~x+y
gridded(meuse.grid) = TRUE
v.uk = variogram(log(zinc)~sqrt(dist), meuse)
uk.model = fit.variogram(v.uk, vgm(1, "Exp", 300, 1))
meuse[["ff"]] = factor(meuse[["ffreq"]])
meuse.grid[["ff"]] = factor(meuse.grid[["ffreq"]])
zn.uk = krige(log(zinc)~sqrt(dist), meuse, meuse.grid, model = uk.model)
zn.uk[["se"]] = sqrt(zn.uk[["var1.var"]])
meuse.sr = SpatialPolygons(list(Polygons(list(Polygon(meuse.riv)),"meuse.riv")))
rv = list("sp.polygons", meuse.sr, fill = "lightblue")
sampling = list("sp.points", meuse.riv, color = "black")
scale = list("SpatialPolygonsRescale", layout.scale.bar(),
offset = c(180500,329800), scale = 500, fill=c("transparent","black"), which = 4)
text1 = list("sp.text", c(180500,329900), "0", cex = .5, which = 4)
text2 = list("sp.text", c(181000,329900), "500 m", cex = .5, which = 4)
arrow = list("SpatialPolygonsRescale", layout.north.arrow(),
offset = c(181300,329800),
scale = 400, which = 4)
library(RColorBrewer)
library(lattice)
trellis.par.set(sp.theme())
precip.pal <- colorRampPalette(brewer.pal(7, name="Blues"))
spplot(zn.uk, "var1.pred",
sp.layout = list(rv, sampling, scale, text1, text2),
main = "log(zinc); universal kriging standard errors",
col.regions=precip.pal,
contour=TRUE,
col='black',
pretty=TRUE,
scales=list(draw = TRUE),
labels=TRUE)
And that's how it looks...all naked:
So my questions:
Where is the scale bar, north arrow, etc hiding? Did I miss something? Every example I could find on the internet looks similar to that. On my own dataset I can see the scale bar and north arrow being drawn at first, but as soon as the grid is rendered, it superimposes the additional map elements (except for the scale text, that is shown on the map - not the bar and north arrow for some reason I don't seem to comprehend).
The error message appearing on the map just shows when I try to add the sampling locations sampling = list("sp.points", meuse.riv, color = "black"). Without this entry, the map shows without error, but also without additional map elements. How can I show the sampling points on the map (e.g. in circles whose size depends on the absolute value of this sampling point)?
This bothered me for many, many hours by now and I can't find any solution to this. In Bivand et al's textbook (2013) "Applied Spatial Data Analysis with R" I could read the following entry:
The order of items in the sp.layout argument matters; in principle objects
are drawn in the order they appear. By default, when the object of spplot has
points or lines, sp.layout items are drawn before the points to allow grids
and polygons drawn as a background. For grids and polygons, sp.layout
items are drawn afterwards (so the item will not be overdrawn by the grid
and/or polygon). For grids, adding a list element first = TRUE ensures that
the item is drawn before the grid is drawn (e.g. when filled polygons are added). Transparency may help when combining layers; it is available for the
PDF device and several other devices.
Function sp.theme returns a lattice theme that can be useful for plots
made by spplot; use trellis.par.set(sp.theme()) after a device is opened
or changed to make this effective.
However, also with this additional information I wasn't able to solve this problem. Glad for any hint!
The elements you miss are being drawn in panel four, which does not exist, so are not being drawn. Try removing the which = 4.
meuse.riv in your example is a matrix, which causes the error message, but should be a SpatialPoints object, so create sampling by:
sampling = list("sp.points", SpatialPoints(meuse.riv), color = "black")
When working from examples, my advice is to choose examples as close as possible to what you need, and only change one thing at a time.

R - Add a map layer to geographical mapping

I am trying to map some data in R with the mercator map as a background.
Here is what is I am using, the data points come out fine, but I am not getting the map.
qplot(nt_phi_lambda$longitude, xlab='Longitude',
nt_phi_lambda$latitude, ylab='Latitude',
data=nt_phi_lambda, main='Global Indsutry Break-down',
colour=industry, projection='mercator()', parameters=c(0,0,0))
You need a data.frame with the coordinates of the country boundaries. Just setting projection = 'mercator() does not add a map in mercator projection. See a recent question of mine for an example of how to plot a world map. An example in a few lines of code:
require(maps)
world_map = data.frame(map(plot=FALSE)[c("x","y")])
ggplot(aes(x = x, y = y), data = world_map) + geom_path()
See also the documentation of coord_map.

In R, how to make dots transparent while using scale_size in ggplot2?

This equation leads from my previous question. I want to plot dots that represent total population and so far I used scale_size to make dots' size relative to its total population.
But, I want to make these dots transparent because the dots are covering the map. I am, however, open to other options as long as the message I am trying to send is clear.
# load required packages
library(ggmap)
library(ggplot2)
# query map of Birmingham, AL
al1 <- get_map(location = c(lon = -86.304474, lat = 32.362563), zoom = 11,
source = "osm", maptype = 'terrain')
al1MAP <- ggmap(al1)+ geom_point(data=quote_bmh,
aes(x=IntPtLon, y=IntPtLat, size=TotPop, colour="gold2"),
colour="gold2") + scale_size(range=c(0,15))
To use a uniform transparency, just add alpha = 0.3 to geom_point. alpha can be between 0 and 1, depending on the amount of transparency you want. If you want to make you transparency depend on a variable, just add alpha = var_name to the mapping argument (the aes bit), where var_name is the column name of the variable you want to use for transparency.
Another alternative is to use hollow points, e.g. geom_point(shape = 21). That would make the map directly under the point quite readable while making the edges of the points distinctly visible.
(Unfortunately, my employer blocks the Google API, so I can't post the result)

Resources