1
#' HERE Geocoder API: Autosuggest
2
#'
3
#' Completes addresses using the HERE 'Geocoder Autosuggest' API.
4
#'
5
#' @references
6
#' \href{https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-autosuggest-brief.html}{HERE Geocoder API: Autosuggest}
7
#'
8
#' @param address character, address text to propose suggestions.
9
#' @param results numeric, maximum number of suggestions (Valid range: 1 and 100).
10
#' @param url_only boolean, only return the generated URLs (\code{default = FALSE})?
11
#'
12
#' @return
13
#' A \code{data.frame} object, containing the suggestions for the input addresses.
14
#' @export
15
#'
16
#' @examples
17
#' # Provide an API Key for a HERE project
18
#' set_key("<YOUR API KEY>")
19
#'
20
#' suggestions <- autosuggest(address = poi$city, url_only = TRUE)
21
autosuggest <- function(address, results = 5, url_only = FALSE) {
22

23
  # Check addresses
24 1
  .check_addresses(address)
25 1
  .check_numeric_range(results, 1, 100)
26 1
  .check_boolean(url_only)
27

28
  # Add API key
29 1
  url <- .add_key(
30 1
    url = "https://revgeocode.search.hereapi.com/v1/autosuggest?"
31
  )
32

33
  # Add address
34 1
  url = paste0(
35 1
    url,
36 1
    "&q=",
37 1
    address
38
  )
39

40
  # Add bbox containing the world
41 1
  url = paste0(
42 1
    url,
43 1
    "&in=bbox:-180,-90,180,90"
44
  )
45

46
  # Add max results
47 1
  url = paste0(
48 1
    url,
49 1
    "&limit=",
50 1
    results
51
  )
52

53
  # Return urls if chosen
54 0
  if (url_only) return(url)
55

56
  # Request and get content
57 1
  data <- .get_content(
58 1
    url = url
59
  )
60 0
  if (length(data) == 0) return(NULL)
61

62
  # Extract information
63 1
  suggestion <- .extract_suggestions(data)
64

65
  # Return data.frame
66 1
  if (nrow(suggestion) > 0) {
67 1
    rownames(suggestion) <- NULL
68 1
    return(as.data.frame(suggestion))
69
  } else {
70 0
    return(NULL)
71
  }
72
}
73

74
.extract_suggestions <- function(data) {
75 1
  template <- data.table::data.table(
76 1
    id = numeric(),
77 1
    rank = numeric(),
78 1
    suggestion = character(),
79 1
    type = character()
80
  )
81 1
  ids <- .get_ids(data)
82 1
  count <- 0
83 1
  result <- data.table::rbindlist(
84 1
    append(list(template),
85 1
           lapply(data, function(con) {
86 1
             count <<- count + 1
87 1
             df <- jsonlite::fromJSON(con)
88 0
             if (length(nrow(df$items)) == 0) return(NULL)
89 1
             data.table::data.table(
90 1
               id = ids[count],
91 1
               rank = seq(1, nrow(df$items)),
92 1
               suggestion = df$items$title,
93 1
               type = df$items$resultType
94
             )
95
           })
96 1
    ), fill = TRUE)
97 1
  result
98
}

Read our documentation on viewing source code .

Loading