Introduction to package mapsapi

Michael Dorman

2019-09-07

Introduction

The mapsapi package provides an interface to the Google Maps APIs, currently three of them -

Functions mp_directions, mp_matrix and mp_geocode are used to access the APIs. They return an xml_document object (package xml2) with the response contents.

Installation

The CRAN version can be installed with -

install.packages("mapsapi")

The development version can be installed using devtools -

install.packages("devtools")
devtools::install_github("michaeldorman/mapsapi")

And loaded with library -

library(mapsapi)

Directions

The following expression queries the Directions API for driving directions from Tel-Aviv and Haifa. Note that locations can be specified as a coordinate pair, a textual address or an sf spatial object.

doc = mp_directions(
  origin = c(34.81127, 31.89277),
  destination = "Haifa",
  alternatives = TRUE
)

Or using the sample response data included in the packages -

library(xml2)
doc = as_xml_document(response_directions_driving)

Given the response object, we can use mp_get_routes to create a spatial layer of route lines -

r = mp_get_routes(doc)

Here is the resulting object -

r
## Simple feature collection with 2 features and 11 fields
## geometry type:  LINESTRING
## dimension:      XY
## bbox:           xmin: 34.76389 ymin: 31.88796 xmax: 35.10844 ymax: 32.7944
## epsg (SRID):    4326
## proj4string:    +proj=longlat +datum=WGS84 +no_defs
##     alternative_id leg_id                   summary distance_m
## 1-1              1      1 Yitzhak Rabin Hwy/Route 6     125960
## 2-1              2      1         Hwy 2/Kvish HaHof     121014
##     distance_text duration_s  duration_text duration_in_traffic_s
## 1-1        126 km       5382 1 hour 30 mins                    NA
## 2-1        121 km       5484 1 hour 31 mins                    NA
##     duration_in_traffic_text departure_time arrival_time
## 1-1                       NA           <NA>         <NA>
## 2-1                       NA           <NA>         <NA>
##                           geometry
## 1-1 LINESTRING (34.81144 31.892...
## 2-1 LINESTRING (34.81144 31.892...

And a visualization using leaflet -

library(leaflet)
pal = colorFactor(palette = "Dark2", domain = r$alternative_id)
leaflet() %>% 
  addProviderTiles("CartoDB.DarkMatter") %>%
  addPolylines(data = r, opacity = 1, weight = 7, color = ~pal(alternative_id))

Separate segments can be extracted from the same response using mp_get_segments -

seg = mp_get_segments(doc)

Here are the first six features of the resulting object -

head(seg)
## Simple feature collection with 6 features and 12 fields
## geometry type:  LINESTRING
## dimension:      XY
## bbox:           xmin: 34.80859 ymin: 31.88963 xmax: 34.82019 ymax: 31.89275
## epsg (SRID):    4326
## proj4string:    +proj=longlat +datum=WGS84 +no_defs
##       alternative_id leg_id segment_id                   summary
## 1-1-1              1      1          1 Yitzhak Rabin Hwy/Route 6
## 1-1-2              1      1          2 Yitzhak Rabin Hwy/Route 6
## 1-1-3              1      1          3 Yitzhak Rabin Hwy/Route 6
## 1-1-4              1      1          4 Yitzhak Rabin Hwy/Route 6
## 1-1-5              1      1          5 Yitzhak Rabin Hwy/Route 6
## 1-1-6              1      1          6 Yitzhak Rabin Hwy/Route 6
##       travel_mode
## 1-1-1     driving
## 1-1-2     driving
## 1-1-3     driving
## 1-1-4     driving
## 1-1-5     driving
## 1-1-6     driving
##                                                               instructions
## 1-1-1 Head <b>southwest</b> on <b>Bnei Moshe St</b> toward <b>Negba St</b>
## 1-1-2                                Turn <b>left</b> onto <b>Negba St</b>
## 1-1-3                    Turn <b>left</b> onto <b>Rachel Hirshenzon St</b>
## 1-1-4                                         Continue onto <b>Ezra St</b>
## 1-1-5                                    Continue onto <b>Ha-Hagana St</b>
## 1-1-6                       Slight <b>right</b> toward <b>Ha-Hagana St</b>
##       distance_m distance_text duration_s duration_text departure_time
## 1-1-1        322        0.3 km         70         1 min           <NA>
## 1-1-2        180        0.2 km         42         1 min           <NA>
## 1-1-3        325        0.3 km         82         1 min           <NA>
## 1-1-4        512        0.5 km        126        2 mins           <NA>
## 1-1-5        214        0.2 km         54         1 min           <NA>
## 1-1-6         18          18 m          4         1 min           <NA>
##       arrival_time                       geometry
## 1-1-1         <NA> LINESTRING (34.81144 31.892...
## 1-1-2         <NA> LINESTRING (34.80859 31.890...
## 1-1-3         <NA> LINESTRING (34.80968 31.889...
## 1-1-4         <NA> LINESTRING (34.81256 31.891...
## 1-1-5         <NA> LINESTRING (34.81783 31.892...
## 1-1-6         <NA> LINESTRING (34.82004 31.892...

And a visualization -

pal = colorFactor(
  palette = sample(colors(), length(unique(seg$segment_id))), 
  domain = seg$segment_id
  )
leaflet(seg) %>% 
  addProviderTiles("CartoDB.DarkMatter") %>%
  addPolylines(opacity = 1, weight = 7, color = ~pal(segment_id), popup = ~instructions)

Distance Matrix

The following expression queries the Distance Matrix API to obtain a matrix of driving distance and duration between all combinations of three locations: Tel-Aviv, Jerusalem and Beer-Sheva.

locations = c("Tel-Aviv", "Jerusalem", "Beer-Sheva")
doc = mp_matrix(
  origins = locations,
  destinations = locations
)

Or using the sample response data included in the packages -

doc = as_xml_document(response_matrix)

The mp_get_matrix function can then be used to process the XML reposne into a matrix. Possible values of the matrix include -

m = mp_get_matrix(doc, value = "distance_m")
colnames(m) = locations
rownames(m) = locations
m
##            Tel-Aviv Jerusalem Beer-Sheva
## Tel-Aviv          0     66532     111641
## Jerusalem     67009         0     120608
## Beer-Sheva   109723    106299          0

Geocode

The following expression queries the Directions API for geocoding a single address.

doc = mp_geocode(addresses = "Tel-Aviv")

Or using the sample response data included in the packages -

library(xml2)
doc = list("Tel-Aviv" = as_xml_document(response_geocode))

Given the response object, we can use mp_get_points to create a spatial layer of geocoded point locations -

pnt = mp_get_points(doc)
pnt
## Simple feature collection with 1 feature and 5 fields
## geometry type:  POINT
## dimension:      XY
## bbox:           xmin: 34.78177 ymin: 32.0853 xmax: 34.78177 ymax: 32.0853
## epsg (SRID):    4326
## proj4string:    +proj=longlat +datum=WGS84 +no_defs
##   id status  address        address_google location_type
## 1  1     OK Tel-Aviv Tel Aviv-Yafo, Israel   APPROXIMATE
##                        pnt
## 1 POINT (34.78177 32.0853)

Here is a visualization using leaflet -

leaflet() %>% 
  addProviderTiles("CartoDB.DarkMatter") %>%
  addCircleMarkers(data = pnt)

Or the bounds -

bounds = mp_get_bounds(doc)
bounds
## Simple feature collection with 1 feature and 3 fields
## geometry type:  POLYGON
## dimension:      XY
## bbox:           xmin: 34.74252 ymin: 32.02925 xmax: 34.85198 ymax: 32.14661
## epsg (SRID):    4326
## proj4string:    +proj=longlat +datum=WGS84 +no_defs
##   status  address        address_google                       geometry
## 1     OK Tel-Aviv Tel Aviv-Yafo, Israel POLYGON ((34.74252 32.02925...

And a visualization using leaflet -

leaflet() %>% 
  addProviderTiles("CartoDB.DarkMatter") %>%  
  addPolygons(data = bounds)