Xiaofan Liang Created in 2024; Updated in 2026

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

For Python users, 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

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

#replace my path with yours to the Lab 5 folder 
#setwd("/Users/xfliang/University of Michigan Dropbox/Xiaofan Liang/UM_Teaching/URP535_Urban_Informatics/W26/Lab/Lab8/")

#install.packages('tidyverse')
library(tidyverse)
#install.packages('tmap') 
library(tmap)
#install.packages('sf') 
library(sf)
#install.packages('tmap') 
library(osmdata)
#install.packages('rsconnect')
library(rsconnect)

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"

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"

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 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:*"
# you need to input a specific key to see all associated tags 
# expand tags in R Environment to see all tags associated with highway
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 3490 points
##             $osm_lines : 'sf' Simple Features Collection with 6 linestrings
##          $osm_polygons : 'sf' Simple Features Collection with 379 polygons
##        $osm_multilines : NULL
##     $osm_multipolygons : 'sf' Simple Features Collection with 11 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. Additionally, sometimes polygons drawn from OSM could have minor errors (e.g., not closing correctly). If you retrieve the geometry but somehow have it shown on the map, you can use st_make_valid() from sf pacakge to fix those geometries.

# retrieve the polygons and only print the first six rows / features 
building_polygons <- building$osm_polygons %>% st_make_valid()
head(building_polygons)
## Simple feature collection with 6 features and 83 fields
## Geometry type: POLYGON
## Dimension:     XY
## Bounding box:  xmin: -83.71816 ymin: 42.29071 xmax: -83.7129 ymax: 42.29378
## Geodetic CRS:  WGS 84
##            osm_id                           name abandoned access addr:city
## 82245561 82245561               Pierpont Commons      <NA>   <NA> Ann Arbor
## 82246736 82246736 Bob and Betty Beyster Building      <NA>   <NA> Ann Arbor
## 82246737 82246737          Walgreen Drama Center      <NA>   <NA> Ann Arbor
## 82246798 82246798        Herbert H. Dow Building      <NA>   <NA> Ann Arbor
## 82249123 82249123  Ann and Robert H. Lurie Tower      <NA>   <NA>      <NA>
## 82249280 82249280           G. G. Brown Building      <NA>   <NA> Ann Arbor
##          addr:housenumber addr:postcode addr:state         addr:street
## 82245561             2101         48109         MI Bonisteel Boulevard
## 82246736             2260         48109         MI      Hayward Street
## 82246737             1226         48109         MI       Murfin Avenue
## 82246798             2300          <NA>         MI      Hayward Street
## 82249123             <NA>          <NA>       <NA>                <NA>
## 82249280             2350          <NA>         MI      Hayward Street
##                        alt_name          amenity  atm brand brand:wikidata
## 82245561                   <NA> community_centre <NA>  <NA>           <NA>
## 82246736                   <NA>             <NA> <NA>  <NA>           <NA>
## 82246737                   <NA>      arts_centre <NA>  <NA>           <NA>
## 82246798                   <NA>             <NA> <NA>  <NA>           <NA>
## 82249123                   <NA>             <NA> <NA>  <NA>           <NA>
## 82249280 G. G. Brown Laboratory             <NA> <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 university            <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> 2024-05-05         <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.
##          diet:non-halal drive_through email  fax fixme fuel:diesel
## 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>
##          fuel:octane_87 fuel:octane_89 fuel:octane_93 height
## 82245561           <NA>           <NA>           <NA>   <NA>
## 82246736           <NA>           <NA>           <NA>   <NA>
## 82246737           <NA>           <NA>           <NA>   <NA>
## 82246798           <NA>           <NA>           <NA>   <NA>
## 82249123           <NA>           <NA>           <NA>   50.3
## 82249280           <NA>           <NA>           <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>
##          indoor landuse laundry_service layer level loc_name man_made max_level
## 82245561   <NA>    <NA>            <NA>  <NA>  <NA>     <NA>     <NA>      <NA>
## 82246736   <NA>    <NA>            <NA>  <NA>  <NA>     <NA>     <NA>      <NA>
## 82246737   <NA>    <NA>            <NA>  <NA>  <NA>     <NA>     <NA>      <NA>
## 82246798   <NA>    <NA>            <NA>  <NA>  <NA>     <NA>     <NA>      <NA>
## 82249123   <NA>    <NA>            <NA>  <NA>  <NA>     <NA>    tower      <NA>
## 82249280   <NA>    <NA>            <NA>  <NA>  <NA>     <NA>     <NA>      <NA>
##          min_level            name:zh note:ja official_name old_name
## 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>
##                                 opening_hours opening_hours:drive_through
## 82245561 Mo-Fr 07:00-24:00; Sa,Su 08:00-24:00                        <NA>
## 82246736            Mo-Fr 07:00-19:00; PH off                        <NA>
## 82246737                                 <NA>                        <NA>
## 82246798            Mo-Fr 07:00-19:00; PH off                        <NA>
## 82249123                                 <NA>                        <NA>
## 82249280            Mo-Fr 07:00-18:00; PH off                        <NA>
##                        operator operator:type outdoor_seating parking
## 82245561                   <NA>          <NA>            <NA>    <NA>
## 82246736 University of Michigan          <NA>            <NA>    <NA>
## 82246737                   <NA>          <NA>            <NA>    <NA>
## 82246798 University of Michigan          <NA>            <NA>    <NA>
## 82249123 University of Michigan          <NA>            <NA>    <NA>
## 82249280 University of Michigan          <NA>            <NA>    <NA>
##          payment:apple_pay payment:contactless payment:google_pay phone
## 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:method plant:output:electricity plant:output:hot_water
## 82245561         <NA>                     <NA>                   <NA>
## 82246736         <NA>                     <NA>                   <NA>
## 82246737         <NA>                     <NA>                   <NA>
## 82246798         <NA>                     <NA>                   <NA>
## 82249123         <NA>                     <NA>                   <NA>
## 82249280         <NA>                     <NA>                   <NA>
##          plant:source power  ref ref:US:EIA religion residential roof:levels
## 82245561         <NA>  <NA> <NA>       <NA>     <NA>        <NA>        <NA>
## 82246736         <NA>  <NA> <NA>       <NA>     <NA>        <NA>        <NA>
## 82246737         <NA>  <NA> <NA>       <NA>     <NA>        <NA>           0
## 82246798         <NA>  <NA> <NA>       <NA>     <NA>        <NA>           2
## 82249123         <NA>  <NA> <NA>       <NA>     <NA>        <NA>        <NA>
## 82249280         <NA>  <NA> <NA>       <NA>     <NA>        <NA>        <NA>
##          roof:shape self_service shelter shop short_name smoking source
## 82245561       flat         <NA>    <NA> <NA>       <NA>    <NA>   <NA>
## 82246736       <NA>         <NA>    <NA> <NA>        BBB    <NA>   <NA>
## 82246737       flat         <NA>    <NA> <NA>        WDC    <NA>   <NA>
## 82246798       flat         <NA>    <NA> <NA>        DOW    <NA>   <NA>
## 82249123       <NA>         <NA>    <NA> <NA>       <NA>    <NA>   <NA>
## 82249280       flat         <NA>    <NA> <NA>        GGB    <NA>   <NA>
##          start_date supervised surface takeaway tower:construction tower:type
## 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>              tower bell_tower
## 82249280       <NA>       <NA>    <NA>     <NA>               <NA>       <NA>
##          website wikidata      wikipedia                       geometry
## 82245561    <NA>     <NA>           <NA> POLYGON ((-83.71793 42.2910...
## 82246736    <NA>     <NA>           <NA> POLYGON ((-83.71579 42.2929...
## 82246737    <NA>     <NA>           <NA> POLYGON ((-83.71705 42.2921...
## 82246798    <NA>     <NA>           <NA> POLYGON ((-83.71577 42.2932...
## 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 100 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 bus_bay change:lanes check_date:surface covered crossing
## 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>
##         crossing:island crossing:markings crossing:signals    cycleway
## 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>              <NA>             <NA> shared_lane
##         cycleway:both cycleway:both:lane cycleway:left cycleway:right
## 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>               <NA>          <NA>           <NA>
##         description direction fixme flashing_lights foot footway garden:type
## 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>
##         golf golf_cart handrail handrail:center handrail:left handrail:right
## 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>
##         height      highway horse incline indoor informal lane_markings lanes
## 8720530   <NA> unclassified  <NA>    <NA>   <NA>     <NA>          <NA>     2
## 8720537   <NA>     tertiary  <NA>    <NA>   <NA>     <NA>          <NA>     2
## 8721309   <NA>      service  <NA>    <NA>   <NA>     <NA>            no  <NA>
## 8721314   <NA> unclassified  <NA>    <NA>   <NA>     <NA>          <NA>     3
## 8721728   <NA>      service  <NA>    <NA>   <NA>     <NA>          <NA>  <NA>
## 8722056   <NA>     tertiary  <NA>    <NA>   <NA>     <NA>          <NA>     2
##         lanes:backward lanes:both_ways lanes:forward layer leisure level  lit
## 8720530           <NA>            <NA>          <NA>  <NA>    <NA>  <NA>  yes
## 8720537           <NA>            <NA>          <NA>  <NA>    <NA>  <NA>  yes
## 8721309           <NA>            <NA>          <NA>  <NA>    <NA>  <NA> <NA>
## 8721314              2            <NA>             1  <NA>    <NA>  <NA> <NA>
## 8721728           <NA>            <NA>          <NA>  <NA>    <NA>  <NA> <NA>
## 8722056           <NA>            <NA>          <NA>  <NA>    <NA>  <NA>  yes
##         maxspeed maxspeed:type motor_vehicle name:signed name_1 noname note
## 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   25 mph          <NA>          <NA>        <NA>   <NA>   <NA> <NA>
##         oneway operator parking:left parking:left:orientation parking:right
## 8720530   <NA>     <NA>         <NA>                     <NA>          <NA>
## 8720537    yes     <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>
##         parking:right:orientation ramp ramp:bicycle ramp:wheelchair segregated
## 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>
##         service shoulder sidewalk sidewalk:left sidewalk:right source
## 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>
##         source:name source:name:date source:surface source:width start_date
## 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>
##         step_count steps surface tactile_paving tiger:cfcc  tiger:county
## 8720530       <NA>  <NA> asphalt           <NA>        A41 Washtenaw, MI
## 8720537       <NA>  <NA> asphalt           <NA>        A41 Washtenaw, MI
## 8721309       <NA>  <NA> asphalt           <NA>        A41 Washtenaw, MI
## 8721314       <NA>  <NA> asphalt           <NA>        A41 Washtenaw, MI
## 8721728       <NA>  <NA>    <NA>           <NA>        A74 Washtenaw, MI
## 8722056       <NA>  <NA> asphalt           <NA>        A41 Washtenaw, MI
##         tiger:name_base tiger:name_base_1 tiger:name_direction_prefix
## 8720530            Beal              <NA>                        <NA>
## 8720537       Bonisteel              <NA>                        <NA>
## 8721309            <NA>              <NA>                        <NA>
## 8721314            <NA>              <NA>                        <NA>
## 8721728            <NA>              <NA>                        <NA>
## 8722056         Hubbard              <NA>                        <NA>
##         tiger:name_type tiger:name_type_1 tiger:reviewed tiger:zip_left
## 8720530             Ave              <NA>             no          48105
## 8720537            Blvd              <NA>             no          48105
## 8721309            <NA>              <NA>             no           <NA>
## 8721314            <NA>              <NA>             no           <NA>
## 8721728            <NA>              <NA>             no           <NA>
## 8722056            <NA>              <NA>           <NA>          48109
##         tiger:zip_left_1 tiger:zip_right tiger:zip_right_1 tunnel turn:lanes
## 8720530             <NA>           48105              <NA>   <NA>       <NA>
## 8720537            48109           48105             48109   <NA>       <NA>
## 8721309             <NA>            <NA>              <NA>   <NA>       <NA>
## 8721314             <NA>            <NA>              <NA>   <NA>       <NA>
## 8721728             <NA>            <NA>              <NA>   <NA>       <NA>
## 8722056            48105           48109             48105   <NA>       <NA>
##         turn:lanes:backward turn:lanes:both_ways turn:lanes:forward wheelchair
## 8720530                <NA>                 <NA>               <NA>       <NA>
## 8720537                <NA>                 <NA>               <NA>       <NA>
## 8721309                <NA>                 <NA>               <NA>       <NA>
## 8721314          left|right                 <NA>               <NA>       <NA>
## 8721728                <NA>                 <NA>               <NA>       <NA>
## 8722056                <NA>                 <NA>               <NA>       <NA>
##         width                       geometry
## 8720530  <NA> LINESTRING (-83.7127 42.300...
## 8720537  <NA> LINESTRING (-83.71297 42.29...
## 8721309  <NA> LINESTRING (-83.7127 42.299...
## 8721314  <NA> LINESTRING (-83.70726 42.30...
## 8721728  <NA> LINESTRING (-83.70956 42.28...
## 8722056  <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 23 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -83.72297 ymin: 42.29094 xmax: -83.71781 ymax: 42.29838
## Geodetic CRS:  WGS 84
##                osm_id           name addr:city addr:housenumber addr:postcode
## 3024930581 3024930581           <NA>      <NA>             <NA>          <NA>
## 3024930582 3024930582           <NA>      <NA>             <NA>          <NA>
## 3024930583 3024930583           <NA>      <NA>             <NA>          <NA>
## 3024930584 3024930584           <NA>      <NA>             <NA>          <NA>
## 3062442003 3062442003 Fireside Roast      <NA>             <NA>          <NA>
## 3062453855 3062453855   Nagomi Sushi Ann Arbor             1754         48105
##            addr:state   addr:street addr:unit    amenity brand brand:wikidata
## 3024930581       <NA>          <NA>      <NA>       <NA>  <NA>           <NA>
## 3024930582       <NA>          <NA>      <NA>       <NA>  <NA>           <NA>
## 3024930583       <NA>          <NA>      <NA>       <NA>  <NA>           <NA>
## 3024930584       <NA>          <NA>      <NA>       <NA>  <NA>           <NA>
## 3062442003       <NA>          <NA>      <NA>       cafe  <NA>           <NA>
## 3062453855       <NA> Plymouth Road      <NA> restaurant  <NA>           <NA>
##            check_date              cuisine delivery door internet_access
## 3024930581       <NA>                 <NA>     <NA> <NA>            <NA>
## 3024930582       <NA>                 <NA>     <NA> <NA>            <NA>
## 3024930583       <NA>                 <NA>     <NA> <NA>            <NA>
## 3024930584       <NA>                 <NA>     <NA> <NA>            <NA>
## 3062442003       <NA> sandwich;coffee_shop     <NA> <NA>            <NA>
## 3062453855       <NA>             japanese     <NA> <NA>            <NA>
##            internet_access:fee level
## 3024930581                <NA>  <NA>
## 3024930582                <NA>  <NA>
## 3024930583                <NA>  <NA>
## 3024930584                <NA>  <NA>
## 3062442003                <NA>   0.5
## 3062453855                <NA>  <NA>
##                                                 opening_hours payment:mcard
## 3024930581                                               <NA>          <NA>
## 3024930582                                               <NA>          <NA>
## 3024930583                                               <NA>          <NA>
## 3024930584                                               <NA>          <NA>
## 3062442003                                               <NA>           yes
## 3062453855 Mo-Th 11:00-22:00;Fr,Sa 11:00-22:30;Su 12:00-22:00          <NA>
##                      phone takeaway              website
## 3024930581            <NA>     <NA>                 <NA>
## 3024930582            <NA>     <NA>                 <NA>
## 3024930583            <NA>     <NA>                 <NA>
## 3024930584            <NA>     <NA>                 <NA>
## 3062442003            <NA>     <NA>                 <NA>
## 3062453855 +1 734 761 5800     <NA> http://nagomia2.com/
##                              geometry
## 3024930581 POINT (-83.72099 42.29838)
## 3024930582 POINT (-83.72099 42.29828)
## 3024930583 POINT (-83.72071 42.29828)
## 3024930584 POINT (-83.72071 42.29838)
## 3062442003 POINT (-83.71781 42.29094)
## 3062453855 POINT (-83.72297 42.29795)

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.5.

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!

In View mode, in both the viewer panel and web map, the gray building might not show up, maybe it’s a compatibility issues with tmap4. But when you switch to Plot mode or view the HTML file, you’ll see it turned gray successfully.

tmap_mode('view')
## ℹ tmap modes "plot" - "view"
## ℹ toggle with `tmap::ttm()`
map <- tm_shape(roads_lines) + 
  tm_lines(col='black') + 
  tm_shape(building_polygons) + 
  tm_polygons(fill='darkgrey') + 
  tm_shape(amenity_point) + 
  tm_symbols(size=0.5, fill='red', fill_alpha=0.5, 
             # determine variable that should show on hover 
             hover = 'name',
             # determine variables that should show on click 
             popup.vars=c('Name: ' = 'name', 'Amenity: ' = 'amenity'))
map
## Registered S3 method overwritten by 'jsonify':
##   method     from    
##   print.json jsonlite

You can toggle the stack icon (under the zoom signs) and choose the OpenStreetMap layer to see how the data align with OSM. Only a subset of restaurants have name attributes (missing data attribute is common in OpenStreetMap). Thus if you hover the nodes that don’t have the name attribute (which is the variable for hover argument), nothing will show up.

Publishing tmap interactive map to RPub

You can also publish your tmap 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)

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')
map <- tm_shape(roads_lines) + 
  tm_lines(col='black') + 
  tm_shape(building_polygons) + 
  tm_polygons(fill='darkgrey') + 
  tm_shape(amenity_point) + 
  tm_symbols(size=0.5, fill='red', fill_alpha=0.5, 
             # determine variable that should show on hover 
             hover = 'name',
             # determine variables that should show on click 
             popup.vars=c('Name: ' = 'name', 'Amenity: ' = 'amenity'))

map

When your ideal map pops up in the Viewer window (after all the adjustments), simply go to the Publish icon (looks like a blue eye) 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 HTML and then the RPubs option. 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. 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 8 Quiz.

Alternatively, if you don’t want to click buttons (or it somehow fails), you can use the following code to publish the map.

# save the interative map as a HTML export 
html_file <- "Lab8_interactive_map.html"
tmap_save(map, html_file)
## Interactive map saved to /Users/sdw/Desktop/MURP2/GSI URP 535/week8/Lab8 (2)/Lab8_interactive_map.html
# For a NEW document use id = NULL. To UPDATE an existing one, set id = "your_doc_id".
rpubsUpload(
  title = "Lab 8: UM North Campus OSM Map",
  contentFile = normalizePath(html_file),
  originalDoc = NULL,
  id = NULL
)
## $id
## [1] "https://api.rpubs.com/api/v1/document/1402022/263f23e227144feb950d82c04d595fde"
## 
## $continueUrl
## [1] "http://rpubs.com/publish/claim/1402022/76a4ade2d7de4b959991ecee199f0a8b"

This code should return two URL, one is ID and the other is continueURL. Copy the continueURL to browser to log into your RPub account and type in a domain name for your published web map.

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! We will show more advanced interactive web map techniques in the next lab.