Xiaofan Liang Created in 2024; Updated in 2025

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/W25/Lab/Lab8/")
setwd("/Users/Lingxiao/University of Michigan Dropbox/Du Lingxiao/W25/Lab/Lab8")

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

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 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 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 3258 points
##             $osm_lines : 'sf' Simple Features Collection with 4 linestrings
##          $osm_polygons : 'sf' Simple Features Collection with 374 polygons
##        $osm_multilines : NULL
##     $osm_multipolygons : 'sf' Simple Features Collection with 10 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 69 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> 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.
##          drive_through email height
## 82245561          <NA>  <NA>   <NA>
## 82246736          <NA>  <NA>   <NA>
## 82246737          <NA>  <NA>   <NA>
## 82246798          <NA>  <NA>   <NA>
## 82249123          <NA>  <NA>   50.3
## 82249280          <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>
##          internet_access landuse laundry_service layer loc_name man_made
## 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>    tower
## 82249280            <NA>    <NA>            <NA>  <NA>     <NA>     <NA>
##          max_level min_level            name:zh note official_name old_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      <NA>      <NA>           卢琳钟楼 <NA>          <NA>     <NA>
## 82249280      <NA>      <NA>         环境工程系 <NA>          <NA>     <NA>
##                                 opening_hours               operator
## 82245561 Mo-Fr 07:00-24:00; Sa,Su 08:00-24:00                   <NA>
## 82246736            Mo-Fr 07:00-19:00; PH off University of Michigan
## 82246737                                 <NA>                   <NA>
## 82246798            Mo-Fr 07:00-19:00; PH off University of Michigan
## 82249123                                 <NA> University of Michigan
## 82249280            Mo-Fr 07:00-18:00; PH off University of Michigan
##          outdoor_seating parking payment:apple_pay payment:contactless
## 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>
##          payment:google_pay 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.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.29308...

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 86 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 centre_turn_lane 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 flashing_lights foot footway garden:type golf
## 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_cart handrail handrail:center handrail:left handrail:right height
## 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>
##              highway horse incline indoor informal lanes lanes:backward
## 8720530 unclassified  <NA>    <NA>   <NA>     <NA>     2           <NA>
## 8720537     tertiary  <NA>    <NA>   <NA>     <NA>     2           <NA>
## 8721309      service  <NA>    <NA>   <NA>     <NA>  <NA>           <NA>
## 8721314 unclassified  <NA>    <NA>   <NA>     <NA>     3              2
## 8721728      service  <NA>    <NA>   <NA>     <NA>  <NA>           <NA>
## 8722056     tertiary  <NA>    <NA>   <NA>     <NA>     2           <NA>
##         lanes:both_ways lanes:forward layer leisure level  lit maxspeed
## 8720530            <NA>          <NA>  <NA>    <NA>  <NA>  yes     <NA>
## 8720537            <NA>          <NA>  <NA>    <NA>  <NA>  yes     <NA>
## 8721309            <NA>          <NA>  <NA>    <NA>  <NA> <NA>     <NA>
## 8721314            <NA>             1  <NA>    <NA>  <NA> <NA>     <NA>
## 8721728            <NA>          <NA>  <NA>    <NA>  <NA> <NA>     <NA>
## 8722056            <NA>          <NA>  <NA>    <NA>  <NA> <NA>     <NA>
##         maxspeed:type name_1 noname note oneway operator parking:right ramp
## 8720530          <NA>   <NA>   <NA> <NA>   <NA>     <NA>          <NA> <NA>
## 8720537          <NA>   <NA>   <NA> <NA>    yes     <NA>          <NA> <NA>
## 8721309          <NA>   <NA>   <NA> <NA>   <NA>     <NA>          <NA> <NA>
## 8721314          <NA>   <NA>   <NA> <NA>   <NA>     <NA>          <NA> <NA>
## 8721728          <NA>   <NA>   <NA> <NA>   <NA>     <NA>          <NA> <NA>
## 8722056          <NA>   <NA>   <NA> <NA>   <NA>     <NA>          <NA> <NA>
##         ramp:wheelchair segregated service shoulder sidewalk sidewalk:left
## 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>
##         sidewalk:right start_date step_count steps surface tactile_paving
## 8720530           <NA>       <NA>       <NA>  <NA>    <NA>           <NA>
## 8720537           <NA>       <NA>       <NA>  <NA> asphalt           <NA>
## 8721309           <NA>       <NA>       <NA>  <NA>    <NA>           <NA>
## 8721314           <NA>       <NA>       <NA>  <NA> asphalt           <NA>
## 8721728           <NA>       <NA>       <NA>  <NA>    <NA>           <NA>
## 8722056           <NA>       <NA>       <NA>  <NA> asphalt           <NA>
##         tiger:cfcc  tiger:county tiger:name_base tiger:name_base_1
## 8720530        A41 Washtenaw, MI            Beal              <NA>
## 8720537        A41 Washtenaw, MI       Bonisteel              <NA>
## 8721309        A41 Washtenaw, MI            <NA>              <NA>
## 8721314        A41 Washtenaw, MI            <NA>              <NA>
## 8721728        A74 Washtenaw, MI            <NA>              <NA>
## 8722056        A41 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 23 fields
## Geometry type: POINT
## Dimension:     XY
## Bounding box:  xmin: -83.723 ymin: 42.29094 xmax: -83.71781 ymax: 42.29875
## Geodetic CRS:  WGS 84
##                osm_id           name addr:city addr:housenumber addr:postcode
## 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>
## 3077164773 3077164773  Marco's Pizza      <NA>             <NA>          <NA>
## 3077164775 3077164775   Bagel Fragel      <NA>             <NA>          <NA>
##            addr:state   addr:street addr:unit    amenity         brand
## 3062442003       <NA>          <NA>      <NA>       cafe          <NA>
## 3062453855       <NA> Plymouth Road      <NA> restaurant          <NA>
## 3064374713       <NA> Plymouth Road      <NA> restaurant          <NA>
## 3065601646       <NA>          <NA>      <NA>       cafe          <NA>
## 3077164773       <NA>          <NA>      <NA> restaurant Marco's Pizza
## 3077164775       <NA>          <NA>      <NA>       cafe          <NA>
##            brand:wikidata check_date              cuisine delivery door
## 3062442003           <NA>       <NA> sandwich;coffee_shop     <NA> <NA>
## 3062453855           <NA>       <NA>             japanese     <NA> <NA>
## 3064374713           <NA>       <NA>       japanese;sushi     <NA> <NA>
## 3065601646           <NA>       <NA>       sandwich;pizza     <NA> <NA>
## 3077164773       Q6757382       <NA>                pizza     <NA> <NA>
## 3077164775           <NA>       <NA>                 <NA>     <NA> <NA>
##            internet_access internet_access:fee level
## 3062442003            <NA>                <NA>   0.5
## 3062453855            <NA>                <NA>  <NA>
## 3064374713            <NA>                <NA>  <NA>
## 3065601646            <NA>                <NA>  <NA>
## 3077164773            <NA>                <NA>  <NA>
## 3077164775            <NA>                <NA>  <NA>
##                                                                opening_hours
## 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
## 3077164773                                                              <NA>
## 3077164775                                                              <NA>
##            payment:mcard           phone takeaway                    website
## 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>
## 3077164773          <NA>            <NA>     <NA>                       <NA>
## 3077164775          <NA>            <NA>     <NA>                       <NA>
##                              geometry
## 3062442003 POINT (-83.71781 42.29094)
## 3062453855 POINT (-83.72297 42.29795)
## 3064374713 POINT (-83.72164 42.29875)
## 3065601646 POINT (-83.72127 42.29364)
## 3077164773     POINT (-83.723 42.298)
## 3077164775 POINT (-83.72287 42.29783)

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 mode set to "view".
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'))
## 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)
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(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'))

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