Let’s find the latitude and longitude for a couple of places.
addresses<- tibble(address=c("Smith College", "2 Tyler Ct, Northampton, MA 01060", "Holyoke Community College")) |>
geocode(address, method="osm") |>
mutate(name = c("Smith College","McConnell Hall","Holyoke Community College"))
addresses
# A tibble: 3 × 4
address lat long name
<chr> <dbl> <dbl> <chr>
1 Smith College 42.3 -72.6 Smith College
2 2 Tyler Ct, Northampton, MA 01060 42.3 -72.6 McConnell Hall
3 Holyoke Community College 42.2 -72.7 Holyoke Community College
Let’s plot those with ggplot.
Not very exciting. We’ll add it it in a moment.
Let’s build a map of Massachusetts with the map_data() function
# map_data comes from ggplot2
ma_counties <- map_data("county", "massachusetts") |>
select( long, lat, group, id = subregion)
head(ma_counties)
long lat group id
1 -70.67435 41.73997 1 barnstable
2 -70.53683 41.79727 1 barnstable
3 -70.53683 41.79727 1 barnstable
4 -70.51392 41.78008 1 barnstable
5 -70.47954 41.75716 1 barnstable
6 -70.41078 41.73425 1 barnstable
Notice there are a lot of points for barnstable. Those are the vertices of a polygon. Let’s draw the polygon with the points.
Coordinate Reference Systems (CRS) - Is the type of map projection employed To get a 3D Earth to a 2D surface.
Which one will coord_sf default to?
Let’s grab just Massachusetts cities from the data frame us.cities.
# us.cities comes from the maps package
ma_cities <- us.cities |>
filter(country.etc =="MA") |>
select(name, long, lat)
head(ma_cities)
name long lat
1 Andover MA -71.14 42.65
2 Arlington MA -71.16 42.42
3 Attleboro MA -71.30 41.93
4 Barnstable Town MA -70.30 41.70
5 Beverly MA -70.84 42.56
6 Billerica MA -71.26 42.56
Plot MA cities onto our county map. Then clean up our map.
Often times map data is saved as a shape file.
The US government has shape files here.