Mapping with R - erynmcfarlane/StatsGenLabProtocols GitHub Wiki

Part 1 basic maps without Google api

This is an example with Toronto roads

#install packages
install.packages(("osmdata"))
install.packages(("tidyverse"))
install.packages("ggmap")
install.packages(("sf"))

library(ggmap)
library(tidyverse)
library(osmdata)
library(sf)

available_features()

available_tags("highway")
roads <-getbb("Toronto ON")%>%
  opq(timeout=3500)%>%
  add_osm_feature(key="highway",value=c("motorway","primary","secondary","tertiary", "residential", "living_street", "unclassified")) %>%
  
  osmdata_sf()

getbb("Toronto ON")


#        min       max
# x -79.63928 -79.11322
# y  43.57961  43.85544

torontomap1<-ggplot()+
  geom_sf(data=roads$osm_lines, inherit.aes = FALSE, color= "black",)+
  coord_sf(xlim = c(-79.63928, -79.11322 ),
           ylim = c(43.57961, 43.85544),
           expand = FALSE)
torontomap1

Part 2 making a map of Toronto using Google

This will provide a basic Toronto map


#insert api code below
api_secret <-"insert code"
register_google(key = api_secret)
Toronto_satellite <- get_map('Toronto', maptype='satellite', source='google', api_key = api_secret)
Toronto_satellite
ggmap(Toronto_satellite)

## different map types such as 'satellite', 'roadmap', 'terrain'

Toronto_2 <- get_map('Toronto', maptype='roadmap', source='google', api_key = api_secret)
Toronto_2
ggmap(Toronto_2)

Part 3 Map with Points

You can also add points to your maps, for example:

#set working directory 
setwd("")
library(ggplot2)
library(ggmap)

#insert api code below
api_secret <-"insert code"
register_google(key = api_secret)

library(readxl)
map.ex <- read_excel("site id example.xlsx")
map.ex


##mapto works
mapto1 <- get_map (location=c(lon=mean(map.ex$Longitude), lat=mean(map.ex$Latitude)), zoom =10, scale=1)
ggmap(mapto1)


#map

dotmap1<- ggmap(mapto1)+geom_point(data=map.ex,aes(x=Longitude,y=Latitude,  fill = "red", alpha = 0.7),
                                 size = 4, shape = 19) +guides(fill=FALSE, alpha=FALSE, size=FALSE)
dotmap1