Xiaofan Liang March 13th, 2024

Learning Objectives

By the end of this practical lab you will be able to:

CHEATSHEETS! You are encouraged to download RStudio Cheatsheets. You can find them on RStudio website here, or a comprehensive list (more than what has been listed) here. For example, here you can find base R syntax, dplyr, ggplot2, sf.

Functions Tasks
getbb(). [osmdata] Retrieve bounding box by coordinates or place names.
opq() [osmdata] Build an Overpass query based on bounding box and osm features
add_osm_feature() [osmdata] Add a feature to an Overpass query
add_osm_features() [osmdata] Alternative version of add_osm_feature for creating single queries with multiple features.
osmdata_sf() [osmdata] Return an OSM Overpass query as an osmdata object in sf format
addTiles() [leaflet] Add a tile layer (basemap) to the map
addPolygons() [leaflet] Add polygons to the map
addPolylines() [leaflet] Add lines to the map
addCircleMarkers() [leaflet] Add circle markers to the map

For Python submission (in ipynb format), make sure your Python code replicate ALL the R code in the Lab (and if it is difficult to replicate exactly, at least cover all the learning objectives). The recommended approach is to copy each heading and write your python code below. You may reference OSMnx and Pyrosm library in Python for OSM-related analysis and Folium for visualization with leaflet capacity.

Setting environment, installing and loading libraries

The two new libraries in this lab are osmdata and leaflet.

osmdata is an R package for downloading and using data from OpenStreetMap (OSM).

Leaflet is an open-source JavaScript library for interactive maps. The R package leaflet makes it easy to create maps from R.

#replace my path with yours to the Lab 5 folder 
setwd("/Users/xiaofanliang/Dropbox (University of Michigan)/UM_Teaching/URP535_Urban_Informatics/Lab/Lab10/")

#install.packages('tidyverse')
library(tidyverse)
#install.packages('tmap') 
library(tmap)
#install.packages('tmap') 
library(osmdata)
#install.packages('leaflet') 
library(leaflet)

Retrieve OSM data on UMich North Campus

OSM data has three geometry: Node (which can be POI but also a node that forms the geometry of a polygon), Way (polygons, such as buildings), and Relation (a collection of nodes, ways, and relations geometry, such as a bus line). In this lab, we will mostly be working with Node and Way.

The code below intends to retrieve buildings in Ann Arbor area. In general, there are two steps for downloading OSM data: 1) determine the bounding box for data download, 2) tell OSM what features (e.g., amenities? roads? buildings?) you want to download and convert the queried data into sf format. Let’s dive in.

Step 1: Determine the Bounding Box

An OSM query starts with a bounding box. You can input a place name as a character string. This function getbb() uses the free Nominatim API provided by OpenStreetMap to find the bounding box (bb) associated with place names. It is recommended to double check the returned bounding box, because many places in the world may have the same name! The function opq() stands for OverPass Query, which helps you format your R code into queries that Overpass API can take in. Thus, when you print out q, what you see are the meta data fed into the Overpass Query.

getbb("Ann Arbor US")
##         min       max
## x -83.79957 -83.67581
## y  42.22267  42.32389
getbb("University of Michigan US")
##         min       max
## x -83.75022 -83.66497
## y  42.24223  42.31251
q <- opq(bbox = getbb("University of Michigan US"))
q
## $bbox
## [1] "42.242226,-83.7502236,42.3125148,-83.6649743"
## 
## $prefix
## [1] "[out:xml][timeout:25];\n(\n"
## 
## $suffix
## [1] ");\n(._;>;);\nout body;"
## 
## $features
## NULL
## 
## $osm_types
## [1] "node"     "way"      "relation"
## 
## attr(,"class")
## [1] "list"           "overpass_query"
## attr(,"nodes_only")
## [1] FALSE

You can also input four coordinates in the form of c(xmin, ymin, xmax, ymax) to determine the bounding box. You can get xmin and ymin coordinates by clicking the bottom left corner of the intended area and xmax and ymax coordinates by clicking the top right corner of the intended area in the Google Maps. In this case, since we are working with North Campus, which is not a well-defined place name in OSM, we will use bounding box to retrieve OSM data instead.

# these coordinates are roughly the bottom left and top right corner of UM North Campus. 
q <- opq(bbox = c(-83.725706, 42.287305, -83.704518, 42.302508))
q
## $bbox
## [1] "42.287305,-83.725706,42.302508,-83.704518"
## 
## $prefix
## [1] "[out:xml][timeout:25];\n(\n"
## 
## $suffix
## [1] ");\n(._;>;);\nout body;"
## 
## $features
## NULL
## 
## $osm_types
## [1] "node"     "way"      "relation"
## 
## attr(,"class")
## [1] "list"           "overpass_query"
## attr(,"nodes_only")
## [1] FALSE

Step 2: Add OSM Features and Convert to sf objects

Next, we need to tell OSM what data we want to retrieve. OSM features are stored in key-value (or key-tag/feature-value) pairs. For instance, to retrieve data on restaurants, then you need to put key='amenity' and value='restaurant'.

How do you find out what key-value pairs are available on OSM? - Go to OSM Wiki Map Features Page. This covers most commonly used key-value pairs, but is not exhuastive. It also provides definition of each key-value pair. - Use available_features() and available_tags() functions in osmdata(). This uses the same info as the Map Features Page above. - Google specific interests with OSM Wiki (e.g., search “restaurant in OSM” will return you this page) - You may also use TagInfo to find out how many incidents exist for each key-tag pair. If the incidents are low, then this key-tag pair may not be useful for your analysis, or this key-tag pair is only used in a specific local context.

# expand features in R Environment to see all entries 
features <- available_features()
head(features)
## [1] "4wd_only"  "abandoned" "abutters"  "access"    "addr"      "addr:city"
# you need to input a specific key to see all associated tags 
# expand tags in R Environment to see all tags associated with amenity
tags <- available_tags("highway")
head(tags)
## # A tibble: 6 × 2
##   Key     Value       
##   <chr>   <chr>       
## 1 highway bridleway   
## 2 highway bus_guideway
## 3 highway bus_stop    
## 4 highway busway      
## 5 highway construction
## 6 highway corridor

Let’s show how to withdraw buildings first. The key-value pair for withdrawing all buildings is key="building". Without specifying the value argument, osmdata defaults to withdraw ALL values under the key. osmdata_sf() returns an OSM Overpass query as an osmdata object in sf format. Other formats are available through osmdata_xml(), osmdata_data_frame(), etc. For instance, if you are not planning to map the OSM data, osmdata_data_frame() may be a better format for simple data wrangling.

building <- opq(bbox = c(-83.725706, 42.287305, -83.704518, 42.302508)) %>% 
  add_osm_feature(key = 'building') %>%
  osmdata_sf()

building
## Object of class 'osmdata' with:
##                  $bbox : 42.287305,-83.725706,42.302508,-83.704518
##         $overpass_call : The call submitted to the overpass API
##                  $meta : metadata including timestamp and version numbers
##            $osm_points : 'sf' Simple Features Collection with 2999 points
##             $osm_lines : NULL
##          $osm_polygons : 'sf' Simple Features Collection with 342 polygons
##        $osm_multilines : NULL
##     $osm_multipolygons : 'sf' Simple Features Collection with 8 multipolygons

The output of building shows the meta data. You can see that there are data under both the osm_points and osm_polygons metadata. It is possible that someone mapped buildings labeled the nodes that form the building polygons as buildings. We want to disregard that and go for osm_polygons instead.

# retrieve the polygons and only print the first six rows / features 
building_polygons <- building$osm_polygons
head(building_polygons)
## Simple feature collection with 6 features and 65 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -83.71816 ymin: 42.29071 xmax: -83.7129 ymax: 42.29377
## Geodetic CRS:  WGS 84
##            osm_id                           name access addr:city
## 82245561 82245561               Pierpont Commons   <NA> Ann Arbor
## 82246736 82246736 Bob and Betty Beyster Building   <NA> Ann Arbor
## 82246737 82246737          Walgreen Drama Center   <NA> Ann Arbor
## 82246798 82246798        Herbert H. Dow Building   <NA> Ann Arbor
## 82249123 82249123  Ann and Robert H. Lurie Tower   <NA>      <NA>
## 82249280 82249280           G. G. Brown Building   <NA> Ann Arbor
##          addr:housenumber addr:postcode addr:state         addr:street
## 82245561             2101         48109       <NA> Bonisteel Boulevard
## 82246736             2260         48109         MI      Hayward Street
## 82246737             1226         48109       <NA>       Murfin Avenue
## 82246798             2300          <NA>         MI      Hayward Street
## 82249123             <NA>          <NA>       <NA>                <NA>
## 82249280             2350          <NA>         MI      Hayward Street
##                        alt_name          amenity brand brand:wikidata
## 82245561                   <NA> community_centre  <NA>           <NA>
## 82246736                   <NA>             <NA>  <NA>           <NA>
## 82246737                   <NA>      arts_centre  <NA>           <NA>
## 82246798                   <NA>             <NA>  <NA>           <NA>
## 82249123                   <NA>             <NA>  <NA>           <NA>
## 82249280 G. G. Brown Laboratory             <NA>  <NA>           <NA>
##            building building:levels building:levels:underground
## 82245561 university               2                        <NA>
## 82246736 university               4                        <NA>
## 82246737 university               3                        <NA>
## 82246798 university               3                        <NA>
## 82249123        yes            <NA>                        <NA>
## 82249280 university               3                        <NA>
##          building:material building:part check_date construction cuisine
## 82245561              <NA>          <NA>       <NA>         <NA>    <NA>
## 82246736              <NA>          <NA>       <NA>         <NA>    <NA>
## 82246737              <NA>          <NA>       <NA>         <NA>    <NA>
## 82246798             brick          <NA>       <NA>         <NA>    <NA>
## 82249123              <NA>          <NA>       <NA>         <NA>    <NA>
## 82249280              <NA>          <NA>       <NA>         <NA>    <NA>
##                                                                                                                       description
## 82245561                                                                                                                     <NA>
## 82246736                                              This building is occupied by the Computer Science & Engineering Department.
## 82246737                                                                                                                     <NA>
## 82246798                                             This building is occupied by the Materials Science & Engineering Department.
## 82249123                                                                                                                     <NA>
## 82249280 This building is occupied by the Mechanical Engineering Department and the Civil & Environmental Engineering Department.
##          email height
## 82245561  <NA>   <NA>
## 82246736  <NA>   <NA>
## 82246737  <NA>   <NA>
## 82246798  <NA>   <NA>
## 82249123  <NA>   50.3
## 82249280  <NA>   <NA>
##                                                                                                image
## 82245561                                                                                        <NA>
## 82246736 https://cse.engin.umich.edu/wp-content/uploads/sites/3/2021/12/beyster-2021-09-1536x778.jpg
## 82246737                                                                                        <NA>
## 82246798                                                                                        <NA>
## 82249123                                                                                        <NA>
## 82249280                                                                                        <NA>
##          internet_access landuse laundry_service layer leisure loc_name
## 82245561            <NA>    <NA>            <NA>  <NA>    <NA>     <NA>
## 82246736            <NA>    <NA>            <NA>  <NA>    <NA>     <NA>
## 82246737            <NA>    <NA>            <NA>  <NA>    <NA>     <NA>
## 82246798            <NA>    <NA>            <NA>  <NA>    <NA>     <NA>
## 82249123            <NA>    <NA>            <NA>  <NA>    <NA>     <NA>
## 82249280            <NA>    <NA>            <NA>  <NA>    <NA>     <NA>
##          man_made max_level min_level            name:zh note official_name
## 82245561     <NA>      <NA>      <NA>     皮尔朋特公共楼 <NA>          <NA>
## 82246736     <NA>      <NA>      <NA> 鲍勃和贝蒂贝斯特楼 <NA>          <NA>
## 82246737     <NA>      <NA>      <NA>   沃尔格林表演中心 <NA>          <NA>
## 82246798     <NA>      <NA>      <NA>       大分子工程系 <NA>          <NA>
## 82249123    tower      <NA>      <NA>           卢琳钟楼 <NA>          <NA>
## 82249280     <NA>      <NA>      <NA>         环境工程系 <NA>          <NA>
##          old_name                        opening_hours               operator
## 82245561     <NA> Mo-Fr 07:00-24:00; Sa,Su 08:00-24:00                   <NA>
## 82246736     <NA>            Mo-Fr 07:00-19:00; PH off University of Michigan
## 82246737     <NA>                                 <NA>                   <NA>
## 82246798     <NA>            Mo-Fr 07:00-19:00; PH off University of Michigan
## 82249123     <NA>                                 <NA> University of Michigan
## 82249280     <NA>            Mo-Fr 07:00-18:00; PH off University of Michigan
##          parking phone plant:method plant:output:electricity
## 82245561    <NA>  <NA>         <NA>                     <NA>
## 82246736    <NA>  <NA>         <NA>                     <NA>
## 82246737    <NA>  <NA>         <NA>                     <NA>
## 82246798    <NA>  <NA>         <NA>                     <NA>
## 82249123    <NA>  <NA>         <NA>                     <NA>
## 82249280    <NA>  <NA>         <NA>                     <NA>
##          plant:output:hot_water plant:source power  ref ref:US:EIA religion
## 82245561                   <NA>         <NA>  <NA> <NA>       <NA>     <NA>
## 82246736                   <NA>         <NA>  <NA> <NA>       <NA>     <NA>
## 82246737                   <NA>         <NA>  <NA> <NA>       <NA>     <NA>
## 82246798                   <NA>         <NA>  <NA> <NA>       <NA>     <NA>
## 82249123                   <NA>         <NA>  <NA> <NA>       <NA>     <NA>
## 82249280                   <NA>         <NA>  <NA> <NA>       <NA>     <NA>
##          roof:levels roof:shape self_service shelter shop short_name source
## 82245561        <NA>       flat         <NA>    <NA> <NA>       <NA>   <NA>
## 82246736        <NA>       <NA>         <NA>    <NA> <NA>        BBB   <NA>
## 82246737           0       flat         <NA>    <NA> <NA>        WDC   <NA>
## 82246798           2       flat         <NA>    <NA> <NA>        DOW   <NA>
## 82249123        <NA>       <NA>         <NA>    <NA> <NA>       <NA>   <NA>
## 82249280        <NA>       flat         <NA>    <NA> <NA>        GGB   <NA>
##          start_date supervised takeaway tower:construction tower:type website
## 82245561       <NA>       <NA>     <NA>               <NA>       <NA>    <NA>
## 82246736       <NA>       <NA>     <NA>               <NA>       <NA>    <NA>
## 82246737       <NA>       <NA>     <NA>               <NA>       <NA>    <NA>
## 82246798       <NA>       <NA>     <NA>               <NA>       <NA>    <NA>
## 82249123       <NA>       <NA>     <NA>              tower bell_tower    <NA>
## 82249280       <NA>       <NA>     <NA>               <NA>       <NA>    <NA>
##          wheelchair wikidata      wikipedia                       geometry
## 82245561       <NA>     <NA>           <NA> POLYGON ((-83.71785 42.2910...
## 82246736       <NA>     <NA>           <NA> POLYGON ((-83.71579 42.2929...
## 82246737       <NA>     <NA>           <NA> POLYGON ((-83.71677 42.2921...
## 82246798       <NA>     <NA>           <NA> POLYGON ((-83.71577 42.2933...
## 82249123       <NA> Q6704939 en:Lurie Tower POLYGON ((-83.71627 42.2920...
## 82249280       <NA>     <NA>           <NA> POLYGON ((-83.7129 42.29296...

Now you can see the output is similar to the sf objects we have been working with and we can map them in tmap interactive view.

Next, we would like to retrieve roads. Roads are called highway key in OSM, which do not mean actual highway in reality. Here we retrieve all the roads.

roads <- opq(bbox = c(-83.725706, 42.287305, -83.704518, 42.302508)) %>% 
  add_osm_feature(key = 'highway') %>%
  osmdata_sf()

roads_lines <- roads$osm_lines
head(roads_lines)
## Simple feature collection with 6 features and 79 fields
## Geometry type: LINESTRING
## Dimension:     XY
## Bounding box:  xmin: -83.71808 ymin: 42.28764 xmax: -83.70726 ymax: 42.30253
## Geodetic CRS:  WGS 84
##          osm_id                name access       alt_name area barrier bicycle
## 8720530 8720530         Beal Avenue   <NA>           <NA> <NA>    <NA>    <NA>
## 8720537 8720537 Bonisteel Boulevard   <NA>           <NA> <NA>    <NA>    <NA>
## 8721309 8721309                <NA>   <NA>           <NA> <NA>    <NA>    <NA>
## 8721314 8721314                <NA>   <NA>           <NA> <NA>    <NA>    <NA>
## 8721728 8721728                <NA>   <NA>           <NA> <NA>    <NA>    <NA>
## 8722056 8722056        Hubbard Road   <NA> Hubbard Avenue <NA>    <NA>    <NA>
##         bridge centre_turn_lane covered crossing crossing:island
## 8720530   <NA>             <NA>    <NA>     <NA>            <NA>
## 8720537   <NA>             <NA>    <NA>     <NA>            <NA>
## 8721309   <NA>             <NA>    <NA>     <NA>            <NA>
## 8721314   <NA>             <NA>    <NA>     <NA>            <NA>
## 8721728   <NA>             <NA>    <NA>     <NA>            <NA>
## 8722056   <NA>             <NA>    <NA>     <NA>            <NA>
##         crossing:markings    cycleway cycleway:both cycleway:both:lane
## 8720530              <NA>        <NA>          <NA>               <NA>
## 8720537              <NA>        <NA>          <NA>               <NA>
## 8721309              <NA>        <NA>          <NA>               <NA>
## 8721314              <NA>        <NA>          <NA>               <NA>
## 8721728              <NA>        <NA>          <NA>               <NA>
## 8722056              <NA> shared_lane          <NA>               <NA>
##         cycleway:left cycleway:right description direction flashing_lights foot
## 8720530          <NA>           <NA>        <NA>      <NA>            <NA> <NA>
## 8720537          <NA>           <NA>        <NA>      <NA>            <NA> <NA>
## 8721309          <NA>           <NA>        <NA>      <NA>            <NA> <NA>
## 8721314          <NA>           <NA>        <NA>      <NA>            <NA> <NA>
## 8721728          <NA>           <NA>        <NA>      <NA>            <NA> <NA>
## 8722056          <NA>           <NA>        <NA>      <NA>            <NA> <NA>
##         footway garden:type golf golf_cart handrail handrail:center
## 8720530    <NA>        <NA> <NA>      <NA>     <NA>            <NA>
## 8720537    <NA>        <NA> <NA>      <NA>     <NA>            <NA>
## 8721309    <NA>        <NA> <NA>      <NA>     <NA>            <NA>
## 8721314    <NA>        <NA> <NA>      <NA>     <NA>            <NA>
## 8721728    <NA>        <NA> <NA>      <NA>     <NA>            <NA>
## 8722056    <NA>        <NA> <NA>      <NA>     <NA>            <NA>
##         handrail:left handrail:right height     highway horse incline indoor
## 8720530          <NA>           <NA>   <NA> residential  <NA>    <NA>   <NA>
## 8720537          <NA>           <NA>   <NA> residential  <NA>    <NA>   <NA>
## 8721309          <NA>           <NA>   <NA>     service  <NA>    <NA>   <NA>
## 8721314          <NA>           <NA>   <NA>     service  <NA>    <NA>   <NA>
## 8721728          <NA>           <NA>   <NA>     service  <NA>    <NA>   <NA>
## 8722056          <NA>           <NA>   <NA> residential  <NA>    <NA>   <NA>
##         informal lanes lanes:backward lanes:both_ways lanes:forward layer
## 8720530     <NA>     2           <NA>            <NA>          <NA>  <NA>
## 8720537     <NA>     2           <NA>            <NA>          <NA>  <NA>
## 8721309     <NA>  <NA>           <NA>            <NA>          <NA>  <NA>
## 8721314     <NA>     3              2            <NA>             1  <NA>
## 8721728     <NA>  <NA>           <NA>            <NA>          <NA>  <NA>
## 8722056     <NA>     2           <NA>            <NA>          <NA>  <NA>
##         leisure level  lit maxspeed maxspeed:type name_1 noname note oneway
## 8720530    <NA>  <NA> <NA>     <NA>          <NA>   <NA>   <NA> <NA>   <NA>
## 8720537    <NA>  <NA>  yes     <NA>          <NA>   <NA>   <NA> <NA>    yes
## 8721309    <NA>  <NA> <NA>     <NA>          <NA>   <NA>   <NA> <NA>   <NA>
## 8721314    <NA>  <NA> <NA>     <NA>          <NA>   <NA>   <NA> <NA>   <NA>
## 8721728    <NA>  <NA> <NA>     <NA>          <NA>   <NA>   <NA> <NA>   <NA>
## 8722056    <NA>  <NA> <NA>     <NA>          <NA>   <NA>   <NA> <NA>   <NA>
##         operator parking:right ramp segregated service shoulder sidewalk
## 8720530     <NA>          <NA> <NA>       <NA>    <NA>     <NA>     <NA>
## 8720537     <NA>          <NA> <NA>       <NA>    <NA>     <NA>     <NA>
## 8721309     <NA>          <NA> <NA>       <NA>    <NA>     <NA>     <NA>
## 8721314     <NA>          <NA> <NA>       <NA>    <NA>     <NA>     <NA>
## 8721728     <NA>          <NA> <NA>       <NA>    <NA>     <NA>     <NA>
## 8722056     <NA>          <NA> <NA>       <NA>    <NA>     <NA>     <NA>
##         sidewalk:left sidewalk:right step_count surface tiger:cfcc
## 8720530          <NA>           <NA>       <NA>    <NA>        A41
## 8720537          <NA>           <NA>       <NA> asphalt        A41
## 8721309          <NA>           <NA>       <NA>    <NA>        A41
## 8721314          <NA>           <NA>       <NA> asphalt        A41
## 8721728          <NA>           <NA>       <NA>    <NA>        A74
## 8722056          <NA>           <NA>       <NA>    <NA>        A41
##          tiger:county tiger:name_base tiger:name_base_1
## 8720530 Washtenaw, MI            Beal              <NA>
## 8720537 Washtenaw, MI       Bonisteel              <NA>
## 8721309 Washtenaw, MI            <NA>              <NA>
## 8721314 Washtenaw, MI            <NA>              <NA>
## 8721728 Washtenaw, MI            <NA>              <NA>
## 8722056 Washtenaw, MI         Hubbard              <NA>
##         tiger:name_direction_prefix tiger:name_type tiger:name_type_1
## 8720530                        <NA>             Ave              <NA>
## 8720537                        <NA>            Blvd              <NA>
## 8721309                        <NA>            <NA>              <NA>
## 8721314                        <NA>            <NA>              <NA>
## 8721728                        <NA>            <NA>              <NA>
## 8722056                        <NA>            <NA>              <NA>
##         tiger:reviewed tiger:zip_left tiger:zip_left_1 tiger:zip_right
## 8720530             no          48105             <NA>           48105
## 8720537             no          48105            48109           48105
## 8721309             no           <NA>             <NA>            <NA>
## 8721314             no           <NA>             <NA>            <NA>
## 8721728             no           <NA>             <NA>            <NA>
## 8722056           <NA>          48109            48105           48109
##         tiger:zip_right_1 tunnel turn:lanes turn:lanes:backward
## 8720530              <NA>   <NA>       <NA>                <NA>
## 8720537             48109   <NA>       <NA>                <NA>
## 8721309              <NA>   <NA>       <NA>                <NA>
## 8721314              <NA>   <NA>       <NA>          left|right
## 8721728              <NA>   <NA>       <NA>                <NA>
## 8722056             48105   <NA>       <NA>                <NA>
##         turn:lanes:forward wheelchair width                       geometry
## 8720530               <NA>       <NA>  <NA> LINESTRING (-83.7127 42.300...
## 8720537               <NA>       <NA>  <NA> LINESTRING (-83.71297 42.29...
## 8721309               <NA>       <NA>  <NA> LINESTRING (-83.7127 42.299...
## 8721314               <NA>       <NA>  <NA> LINESTRING (-83.70726 42.30...
## 8721728               <NA>       <NA>  <NA> LINESTRING (-83.70956 42.28...
## 8722056               <NA>       <NA>  <NA> LINESTRING (-83.71408 42.29...

This example below shows how to retrieve multiple features (amenities) at once. You can retrieve features under the same geometry (e.g., point, line, polygon) in one file through add_osm_features() function. Note that it has an additional s as compared with the add_osm_feature() function above.

amenity <- opq(bbox = c(-83.725706, 42.287305, -83.704518, 42.302508)) %>% 
  add_osm_features(features = c(
    "amenity" = "restaurant",
    "amenity" = "cafe"
  )) %>% 
  osmdata_sf()

amenity_point <- amenity$osm_points
head(amenity_point)
## Simple feature collection with 6 features and 19 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -83.72297 ymin: 42.29088 xmax: -83.71584 ymax: 42.29875
## Geodetic CRS:  WGS 84
##                osm_id           name addr:city addr:housenumber addr:postcode
## 3062442001 3062442001  Fireside Café      <NA>             <NA>          <NA>
## 3062442003 3062442003 Fireside Roast      <NA>             <NA>          <NA>
## 3062453855 3062453855   Nagomi Sushi Ann Arbor             1754         48105
## 3064374713 3064374713          Saica Ann Arbor             1733         48105
## 3065601646 3065601646     Blue Apple      <NA>             <NA>          <NA>
## 3072665433 3072665433      Mujo Cafe      <NA>             <NA>          <NA>
##            addr:state   addr:street addr:unit    amenity brand brand:wikidata
## 3062442001       <NA>          <NA>      <NA> restaurant  <NA>           <NA>
## 3062442003       <NA>          <NA>      <NA>       cafe  <NA>           <NA>
## 3062453855       <NA> Plymouth Road      <NA> restaurant  <NA>           <NA>
## 3064374713       <NA> Plymouth Road      <NA> restaurant  <NA>           <NA>
## 3065601646       <NA>          <NA>      <NA>       cafe  <NA>           <NA>
## 3072665433       <NA>          <NA>      <NA>       cafe  <NA>           <NA>
##            check_date              cuisine delivery
## 3062442001       <NA>                 <NA>     <NA>
## 3062442003       <NA> sandwich;coffee_shop     <NA>
## 3062453855       <NA>             japanese     <NA>
## 3064374713       <NA>       japanese;sushi     <NA>
## 3065601646       <NA>       sandwich;pizza     <NA>
## 3072665433 2023-07-26             sandwich     <NA>
##                                                                opening_hours
## 3062442001                                                 Mo-Fr 09:00-17:00
## 3062442003                                                              <NA>
## 3062453855                Mo-Th 11:00-22:00;Fr,Sa 11:00-22:30;Su 12:00-22:00
## 3064374713                 Mo-Fr 11:00-22:00; Sa 12:00-22:00; Su 12:00-21:00
## 3065601646 Mo-Th 07:00-01:00; Fr 07:00-23:00; Sa 09:00-23:00; Su 09:00-01:00
## 3072665433         Mo-Th 07:00-02:00; Fr 07:00-18:00; Sa off; Su 12:00-02:00
##            payment:mcard           phone takeaway                    website
## 3062442001           yes            <NA>     <NA>                       <NA>
## 3062442003           yes            <NA>     <NA>                       <NA>
## 3062453855          <NA> +1 734 761 5800     <NA>       http://nagomia2.com/
## 3064374713          <NA> +1 734 769 1212     <NA> http://www.saicasushi.com/
## 3065601646           yes            <NA>     <NA>                       <NA>
## 3072665433          <NA>            <NA>     <NA>                       <NA>
##                              geometry
## 3062442001 POINT (-83.71765 42.29092)
## 3062442003  POINT (-83.7177 42.29088)
## 3062453855 POINT (-83.72297 42.29795)
## 3064374713 POINT (-83.72164 42.29875)
## 3065601646 POINT (-83.72127 42.29364)
## 3072665433 POINT (-83.71584 42.29149)

Visualize OSM data

Now we will overlay all the data together and see it on the tmap interactive map! Notice that we added some simple aesthetics, so that roads are colored in light grey, buildings are colored in darkgrey and the border transparency is set to 0 (which essentially removes the border), and amenity points are colored in red with 50% transparency and scaled to size 0.2.

If you hover to the OSM data, the default popup is OSM id, which is the first column in the data. If we publish a web map with OSM data, we would like the pop up to be more informative. The id argument in tm_polygons(), tm_lines(), or tm_symbols() helps set which column should show up on the hovering pop up. The popup.vars argument determines the content for on-click pop up. Try hovering to the point geometry (amenities) and see the hover info and on-click popup have changed!

tmap_mode('view')
## tmap mode set to interactive viewing
tm_shape(roads_lines) + 
  tm_lines(col='black') + 
  tm_shape(building_polygons) + 
  tm_polygons(col='darkgrey') + 
  tm_shape(amenity_point) + 
  tm_symbols(size=0.2, col='red', alpha=0.5, 
             # determine variable that should show on hover 
             id = 'name',
             # determine variables that should show on click 
             popup.vars=c('Name: ' = 'name', 'Amenity: ' = 'amenity'))

You can toggle the stack icon (under the zoom signs) and choose the OpenStreetMap layer to see how the data align with OSM.

Interactive Map through leaflet (Optional)

Leaflet is a more versatile web map R package, but it cannot switch between static and interactive map mode like tmap. Thus, if you are only interested in web map, leaflet may be a better option. The Leaflet Documentation (click on the dropdown menu saying “Articles”) has a series of tutorials on how to use leaflet in R.

Let’s reproduce the interactive map above with leaflet syntax.

library(leaflet)

leaflet() %>% addTiles() %>% 
  addPolylines(data = roads_lines, color='black', weight = 2) %>% 
  addPolygons(data = building_polygons, color="darkgrey") %>% 
  addCircleMarkers(data = amenity_point, color="red", label=amenity_point$name)

You may notice in the tmap interactive map above that when you zoom in, the node size did not change, which makes it difficult to exam areas with clustered nodes. leaflet allows dynamic rescaling of node size based on the zoom level, which is ideal if you have a large number of points or polygons.

Publishing tmap interactive map to RPub

You can also publish your tmap and leaflet interactive map to web through your RPub account using the same process. Below is a cleaned version of code from start to end for you to regenenerate the visualization with tmap.

library(tidyverse)
library(osmdata)
library(tmap)
library(leaflet)

building <- opq(bbox = c(-83.725706, 42.287305, -83.704518, 42.302508)) %>% 
  add_osm_feature(key = 'building') %>%
  osmdata_sf()
building_polygons <- building$osm_polygons

roads <- opq(bbox = c(-83.725706, 42.287305, -83.704518, 42.302508)) %>% 
  add_osm_feature(key = 'highway') %>%
  osmdata_sf()
roads_lines <- roads$osm_lines

amenity <- opq(bbox = c(-83.725706, 42.287305, -83.704518, 42.302508)) %>% 
  add_osm_features(features = c(
    "amenity" = "restaurant",
    "amenity" = "cafe"
  )) %>% 
  osmdata_sf()
amenity_point <- amenity$osm_points

tmap_mode('view')
tm_shape(roads_lines) + 
  tm_lines(col='black') + 
  tm_shape(building_polygons) + 
  tm_polygons(col='darkgrey') + 
  tm_shape(amenity_point) + 
  tm_symbols(size=0.2, col='red', alpha=0.5, 
             # determine variable that should show on hover 
             id = 'name',
             # determine variables that should show on click 
             popup.vars=c('Name: ' = 'name', 'Amenity: ' = 'amenity'))

When your ideal map pops up in the Viewer window (after all the adjustments), simply go to the Publish icon on the top right corner of the viewer (Note: this is important. You should publish through this exact publish icon, rather than other publish icons in the script window). Click Publish and select Publish through RPubs. You may be asked to create an account. It may takes a few minutes for the HTML to be uploaded. You may also be prompted to enter the title and the name of the map. Here is an example output using my account: https://rpubs.com/xiaofanliang/lab10_tmap. Now you have a public, interactive map for sharing!

If you would like to make some editions to the map, simply change the code, and click Repbulish icon on the Viewer window. Once you have published the map, the Publish icon will turn into Republish, and the URL will stay unchanged.

Keep this URL because you will need to submit for Lab 10 Quiz.

Another more technical, but recommended way to publish an interactive map is to export your Rmd file as an HTML, and embed it as a HTML widget and publish on GitHub Pages. As such, you have more room to adjust for aesthetics, and more ownership over your map through your own GitHub account!