5.11 Lab: Connect to Google Geocoding API

Constructing a REST API call:

From R, use httr package to make GET request:

library(httr)
# Write out url
GET("https://maps.googleapis.com/maps/api/geocode/json?address=budapest")
# or use query argument (normally linked with &)
GET("https://maps.googleapis.com/maps/api/geocode/json",
query=list(address="budapest"))
  • You can type URLs into your browser to test them

We’ll have to use an API key to run this query. The api key need to be generate on the Google Cloud platform (under credentials). Before it might be necessary to register an app/oauth.

library(httr)

api_key <- "####"

# See also ?GET
GET("https://maps.googleapis.com/maps/api/geocode/json",
query=list(address = "budapest", 
           key = api_key))

# Alternative
GET("https://maps.googleapis.com/maps/api/geocode/json?address=budapest&key=####")


GET("https://maps.googleapis.com/maps/api/geocode/json",
query=list(address="Universty of Mannheim", 
           key = api_key))

r <- GET("https://maps.googleapis.com/maps/api/geocode/json",
query=list(address="49.487225,8.45767", 
           key = api_key))

# There are packages in R to geocode!
http_type(r) # check response type
class(r) # check object class

# Content printed as text
writeLines(content(r, type = "text")) # Inspect & printout content

# Content as list
content(r)
content(r, as = "parsed")
# Search what you need:
# Q: How can I access list elements?

# List content
str(content(r), max.level = 3) # show structure & limit levels
# extract list parts
list_part <- rlist::list.select(content(r)$results, formatted_address, place_id)
rlist::list.stack(list_part)


 # parse content w. jasonlight
library(jsonlite)
fromJSON(content(r, type = "text"))
fromJSON(content(r, type = "text"))$results$formatted_address




# XML
library(XML)
library(xml2)
r <- GET("https://maps.googleapis.com/maps/api/geocode/xml",
query=list(address="49.487225,8.45767", 
           key = api_key))
content(r)
read_xml(r)
xmlParse(r)

xmlToList(xmlParse(r))$result$formatted_address # extract address


# etc.