37

I am trying to plot my coordinates using R. I have tried already to follow different post (R: Plot grouped coordinates on world map ; Plotting coordinates of multiple points at google map in R) but I am not having much success with my data.

I am trying to achieve a flat map of the world with my gps coordinate as colored dots (each area a specific color):

area         lat    long
Agullhas    -38,31  40,96
Polar       -57,59  76,51
Tasmanian   -39,47  108,93

library(RgoogleMaps)
lat <- c(-38.31, -35.50) #define our map's ylim
lon <- c(40.96,37.50) #define our map's xlim
center = c(mean(lat), mean(lon))  #tell what point to center on
zoom <- 2 #zoom: 1 = furthest out (entire globe), larger numbers = closer in
terrmap <- GetMap(center=center, zoom=zoom, maptype= "satallite", destfile = "satallite.png")

problem that now I don't know how to add my points and I will like one color for each region.

Could anyone help me going forward with it?

the other option I have tried is :

library(maps)
library(mapdata)
library(maptools)
map(database= "world", ylim=c(-38.31, -35.5), xlim=c(40.96, 37.5), col="grey80", fill=TRUE, projection="gilbert", orientation= c(90,0,225))
lon <- c(-38.31, -35.5)  #fake longitude vector
lat <- c(40.96, 37.5)  #fake latitude vector
coord <- mapproject(lon, lat, proj="gilbert", orientation=c(90, 0, 225))  #convert points to projected lat/long
points(coord, pch=20, cex=1.2, col="red")  #plot converted points

but the coordinates ends in a wrong position and I am not sure why

Hope someone can help

Jaap
  • 81,064
  • 34
  • 182
  • 193
flacchy
  • 511
  • 1
  • 6
  • 9
  • getting this error so the points don't show in map Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=-47.5275,57.9675&zoom=2&size=%20640x640&maptype=terrain&sensor=false Google Maps API Terms of Service : http://developers.google.com/maps/terms " am I missing something? – flacchy Apr 17 '14 at 12:25
  • today is working :) the only problem now is that if I modify the zoom to fit all the points in the same plot using a zoom of 2 the satellite map disappear and I see only a grey plot with lat and long. mapgilbert <- get_map(location = c(lon = mean(df$lon), lat = mean(df$lat)), zoom = 2, maptype = "satellite", scale = 2) – flacchy Apr 22 '14 at 06:18
  • I don't know why, bor some reason you can't use zoom levels 1 & 2. Maybe [this question & answers](http://stackoverflow.com/questions/11201997/world-map-with-ggmap) give you a possible solution. – Jaap Apr 24 '14 at 14:36

4 Answers4

55

As an alternative to RgoogleMaps, you can also use the combination ggplot2 with ggmap.

With this code:

# loading the required packages
library(ggplot2)
library(ggmap)

# creating a sample data.frame with your lat/lon points
lon <- c(-38.31,-35.5)
lat <- c(40.96, 37.5)
df <- as.data.frame(cbind(lon,lat))

# getting the map
mapgilbert <- get_map(location = c(lon = mean(df$lon), lat = mean(df$lat)), zoom = 4,
                      maptype = "satellite", scale = 2)

# plotting the map with some points on it
ggmap(mapgilbert) +
  geom_point(data = df, aes(x = lon, y = lat, fill = "red", alpha = 0.8), size = 5, shape = 21) +
  guides(fill=FALSE, alpha=FALSE, size=FALSE)

you get this result: enter image description here

Jaap
  • 81,064
  • 34
  • 182
  • 193
  • 2
    I am not sure if is a problem with my R version I am keep getting this error: Error in download.file(url, destfile = destfile, quiet = !messaging, mode = "wb") : impossible open URL 'http://maps.googleapis.com/maps/api/staticmap?center=39.23,-36.905&zoom=4&size=%20640x640&scale=%202&maptype=satellite&sensor=false' Also: Warning message: In download.file(url, destfile = destfile, quiet = !messaging, mode = "wb") : impossible to open: status HTTP '403 Forbidden' can you tell me what is wrong??? I am using the same commands... – flacchy Apr 21 '14 at 06:50
  • Maybe you could include the result of `sessionInfo()` in your post? I'm using R 3.0.2 (and RStudio) with `ggplot2 0.9.3.1` and `ggmap 2.3` – Jaap Apr 21 '14 at 10:38
  • R version 2.15.3 (2013-03-01) Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit) – flacchy Apr 22 '14 at 06:19
  • It gives me a url just fine, unfortunately I have to cut/paste that into a browser manually to see the map. That url is missing the dots and the labels on the outside – demongolem Nov 05 '15 at 21:19
  • @demongolem the code is running fine for me, what did you try? – Jaap Nov 06 '15 at 09:15
  • @Jaap Sorry my mistake. When sourcing, I forgot to use a print statement. – demongolem Nov 06 '15 at 12:55
  • 1
    @Jaap looks great! Unfortunately no longer works with ggmap 2.6 (Error: GeomRasterAnn was built with an incompatible version of ggproto. Please reinstall the package that provides this extension.) – mitchus Oct 17 '17 at 15:54
  • @mitchus When I run the code in my answer with *ggplot2 2.2.1* and *ggmap 2.6.1* it runs fine & gives me the same plot. Maybe something else is going on? – Jaap Oct 17 '17 at 18:38
  • 5
    Google Map Requires API Key – Suat Atan PhD Aug 23 '19 at 12:58
15

Another option is using the leaflet package (as suggested here). Unlike Google Maps it does not require any API key.

install.packages(c("leaflet", "sp"))
library(sp)
library(leaflet)
df <- data.frame(longitude = runif(10, -97.365268, -97.356546), 
                 latitude = runif(10, 32.706071, 32.712210))

coordinates(df) <- ~longitude+latitude
leaflet(df) %>% addMarkers() %>% addTiles()

Plot 10 random points in vicinity of TCU

bonna
  • 1,575
  • 2
  • 17
  • 31
  • How would you add a variable to the marker? i.e. size of marker related to population. – adm Mar 28 '20 at 00:50
  • Instead of `addMarkers()` use `addCircleMarkers(radius = population)` as [described in the manual](https://rstudio.github.io/leaflet/markers.html) – bonna Apr 03 '20 at 11:03
4

An other alternative, is the plotGoogleMaps package which allows to plot in a navigator, allowing to zoom in and out etc. You can then make a screenshot of your picture to save it (though remember google maps are legally supposed to be used for the internet).

 library("plotGoogleMaps")
 lat <- c(-38.31, -35.50) #define our map's ylim
 lon <- c(40.96,37.50) #define our map's xlim

 # make your coordinates a data frame 
 coords <- as.data.frame(cbind(lon=lon,lat=lat))

 # make it a spatial object by defining its coordinates in a reference system
 coordinates(coords) <- ~lat+lon 

 # you also need a reference system, the following should be a fine default
 proj4string(coords) <- CRS("+init=epsg:4326")
 # Note: it is a short for: 
 CRS("+init=epsg:4326")
 > CRS arguments:
 >  +init=epsg:4326 +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 

 # then just plot
 a <- plotGoogleMaps(coords)
 # here `a <-` avoids that you get flooded by the html version of what you plot 

And you get : enter image description here

cmbarbu
  • 4,354
  • 25
  • 45
1

Here is a solution using only Rgooglemaps, as requested by the user.

# get map (from askers OP, except changed map type = "Satallite" to type = "Satellite")
library(RgoogleMaps)
lat <- c(-38.31, -35.50) #define our map's ylim
lon <- c(40.96,37.50) #define our map's xlim
center = c(mean(lat), mean(lon))  #tell what point to center on
zoom <- 2 #zoom: 1 = furthest out (entire globe), larger numbers = closer in
terrmap <- GetMap(center=center, zoom=zoom, type= "satellite", destfile = "satellite.png")

# plot points and save image
lat <- c(-38.31, -57.59, -39.47)
lon <- c(40.96, 76.51, 108.93)
png('map.png')
PlotOnStaticMap(terrmap, lat = lat, lon = lon, pch = 20, col = c('red', 'blue', 'green'))
dev.off()

enter image description here

sebdalgarno
  • 2,929
  • 12
  • 28