Search code examples
rplotgeospatialrgooglemaps

Add basemap to SpatialPointDataFrames using R


I want to add a basemap to my plot, which visualizes three SpatialPointDataFrames. I've already tried the maptools as well as RgoogleMaps package, but both don't work in the way, which I want to.
My problem: The SpatialPointDataFrames are not drawn on the GoogleMaps Background map.

A minimal example:

The city.csv with the following example content:

FID,city,POINT_X,POINT_Y
0,New York,-73.996786,40.720813
1,Newark,-74.172237, 40.732196

The R Code:

# Load packages
library(RgoogleMaps)
library(sp)

# load .csv file 
city= read.csv("city.csv", header = TRUE)

# convert to SpatialPointDataFrame
coordinates(city) <- c("POINT_X", "POINT_Y")
proj4string(city) <- CRS("+proj=longlat +datum=WGS84")

# use RgoogleMaps
gc <- geocode('new york, usa')
center <- as.numeric(gc)
ggmap(get_googlemap(center = center, color = 'bw', scale = 4), fullpage = T)
# Plot the city dataset
plot(city, pch = 22, col="black", bg= "yellow", cex = 1.5, add = TRUE)

The result should be a plot with the background map and the two points, but the points are not drawn on the map. Is there a geocoding problem or do I miss anything? Is it possible to combine ggmap and plt functions?

Any help is much appreciated!


Solution

  • Using ggplot2 for this kind of work is much easier, you can add points, polygons, 2densities, etc... to ggmap layers.

    library(RgoogleMaps)
    library(sp)
    library(ggplot2)
    library(ggmap)
    

    P is the SpatialPointsDataFrame object:

    DB <- data.frame(FID=P$FID, city=P$city)
    DB <- cbind(DB, P@coords)
    
    
    DB <- data.frame(FID=c(0,1), city=c("New York", "Newark"),   POINT_X=c(-73.996786,-74.172237), POINT_Y=c(40.720813,40.732196 ))
    gc <- geocode("new york, usa")
    center <- as.numeric(gc)
    G <- ggmap(get_googlemap(center = center, color = 'bw', scale = 4), extent = "device")
    G1 <- G + geom_point(aes(x=POINT_X, y=POINT_Y ),data=DB, color="red", size=5)
    plot(G1)
    

    This is the output:

    enter image description here