The problem you have is that you can not get the latitude and longitude, let's see:
address <- 'Universidad de Zaragoza, Zaragoza, España'
unizar <- geocode(address)
This in console throws the following message
Information from URL:
link
Warning messages: 1: In readLines (connect, warn = FALSE): can not
open URL
' link ':
HTTP status was '400 Bad Request' 2: In geocode (address):
geocoding failed for "University of Zaragoza, Zaragoza, Spain". if accompanied by 500 Internal Server Error with using dsk, try
google.
If we go directly to the link ( link ) through a browser we will get a more descriptive error:
{
"error_message" : "Invalid request. One of the input parameters contains a non-UTF-8 string.",
"results" : [],
"status" : "INVALID_REQUEST"
}
That is, the address we want to search is not well coded, certain characters (probably the ñ) do not have a code utf-8
suitable. To solve this we can use enc2utf8()
:
address <- enc2utf8('Universidad de Zaragoza, Zaragoza, España')
and now yes, everything that follows:
unizar <- geocode(address)
if (!any(is.na(unizar))) {
map.unizar <- get_map( location = as.numeric(unizar),
color = "color",
maptype = "roadmap",
scale = 2,
zoom = 16)
ggmap(map.unizar) + geom_point(aes(x = lon, y = lat),
data = unizar, colour = 'red',
size = 4)
} else {
stop("No hemos podido recuperar la coordenadas")
}
I added a control to know if we could correctly recover latitude and longitude, Google can "banearte" at some point if you make many inquiries and it should be controlled.
The result:
If you want the full map of Spain you can modify the zoom level, remember also that if you already have the latitude and longitude, you do not need to call geocode()
:
puntos <- data.frame(lon=c(-3.391830, -3.530613, -3.205903, -3.137145, -0.9015065),
lat=c(39.595520, 40.225155, 40.320294, 40.345348, 41.64206),
nom=c('Aranjuez', 'San Martin de la vega', 'Ruta de las vegas',
'Mondejar', 'Universidad de Zaragoza, Zaragoza, España')
)
map.unizar <- get_map( location = puntos[1,-3],
color = "color",
maptype = "roadmap",
scale = 2,
zoom = 6)
ggmap(map.unizar) + geom_point(aes(x = lon, y = lat),
data = puntos, colour = 'red',
size = 2)
The Result:
If still the result does not convince you, I suggest you take a look at LeafLet , that offers you a dynamic, very configurable and attractive visualization:
library(leaflet)
library(magrittr)
puntos <- data.frame(lon=c(-3.391830, -3.530613, -3.205903, -3.137145, -0.9015065),
lat=c(39.595520, 40.225155, 40.320294, 40.345348, 41.64206),
nom=c('Aranjuez', 'San Martin de la vega', 'Ruta de las vegas',
'Mondejar', 'Universidad de Zaragoza, Zaragoza, España')
)
leaflet(data = puntos) %>%
addTiles() %>%
setView(lng = puntos$lon[1], lat = puntos$lat[1] , zoom = 6) %>%
addMarkers(~lon, ~lat, popup = ~as.character(nom), label = ~as.character(nom))
Example exported to an image: