---
title: "Geocoding & Search API"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Geocoding & Search API}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(hereR)
library(sf)

if (requireNamespace("mapview", quietly = TRUE)) {
  mapview::mapviewOptions(fgb = FALSE)
}

address <- poi$city
geocoded <- hereR:::example$geocode
suggestions <- hereR:::example$autosuggest
reverse_geocoded <- hereR:::example$reverse_geocode
```

Autosuggest and geocode addresses or reverse geocode POIs using the 'HERE Geocoding & Search' API.

## Geocode addresses

In order to geocode addresses, the function `geocode()` is used. The requests are sent asynchronously, which means that every geocoded address is counting as one request. The addresses have to be of type `character`:

```{r print_addresses, eval=TRUE, echo=TRUE, out.width='100%'}
head(address, 3)
```

Geocode the character vector containing the addresses:

```{r geocode, eval=FALSE}
geocoded <- geocode(address)
```

The return value is an `sf` object containing `POINT` geometries of the addresses:

```{r head_geocoded, eval=TRUE, echo=TRUE, out.width='100%'}
head(geocoded, 3)
```

Not found addresses are deleted from the result. This means that the `sf` object may contain fewer rows than the original number of addresses. The column `"id"` matches the order of the the input addresses. Using the `"id"` column a corresponding `data.frame` `"df"` with the addresses to geocode could be joined to the coordinates after geocoding.

```{r join_geocoded, eval=FALSE, echo=TRUE, out.width='100%'}
df <- data.frame(
  company = c("Schweizerische Bundesbahnen SBB", "Bahnhof AG", "Deutsche Bahn AG"),
  address = c("Wylerstrasse 123, 3000 Bern 65", "not_an_address", "Potsdamer Platz 2, 10785 Berlin"),
  stringsAsFactors = FALSE
)
locs <- geocode(df$address)
geocoded_sfdf <- st_as_sf(data.frame(locs, df[locs$id, ]))
```

Print the geocoded addresses on an interactive leaflet map:

```{r map_geocoded, eval=FALSE, out.width='100%'}
if (requireNamespace("mapview", quietly = TRUE)) {
  mapview::mapview(geocoded,
    label = geocoded$address,
    col.regions = "red",
    map.types = c("Esri.WorldTopoMap"),
    legend = FALSE,
    homebutton = FALSE
  )
}
```

**Note:** Setting `alternatives = TRUE` will also return alternative locations in the same order as received from the API (`rank` column).

Instead of free-text address searches, there is also an option to specify qualified
queries using the keys `"country"`, `"state"`, `"county"`, `"city"`, `"district"`, `"street"`,
`"houseNumber"` or `"postalCode"`:

```{r qq_geocoded, eval=FALSE, out.width='100%'}
qq <- list(
  list(
    country = "Germany",
    city = "Berlin",
    street = "Friedrichstr"
  ),
  list(
    country = "Switzerland",
    city = "Zurich",
    street = "Hardstrasse"
  )
)
geocoded_qq <- geocode(qq)
```

## Autosuggestions

The autosuggestion endpoint of the Geocoding & Search API can be accessed using the `autosuggest()` function. The `results` parameter defines the maximum number of suggestions that should be requested for each input address.

```{r autocomplete, eval=FALSE}
suggestions <- autosuggest(address, results = 3)
```

The return value is a `data.frame` containing autocomplete suggestions for the addresses. The variable `id` matches the index of the initial address vector, which was used as input and `order` stores the rank of the suggestion.

```{r results_autocomplete, eval=TRUE, echo=TRUE, out.width='100%'}
results <- data.frame(
  input = address[suggestions$id],
  id = suggestions$id,
  rank = suggestions$rank,
  suggestion = suggestions$suggestion
)
```

```{r table_results, eval=TRUE, echo=FALSE, out.width='100%', fig.align='center', screenshot.force=FALSE}
knitr::kable(head(results), format = "html")
```

## Reverse geocode POIs

The reverse geocoding feature of the Geocoding & Search API can be accessed using the `reverse_geocode()` function. The function allows to retrieve addresses near POIs.

```{r reverse_geocode, eval=FALSE, echo=TRUE, out.width='100%'}
reverse_geocoded <- reverse_geocode(poi = poi, results = 3)
```

The function returns an `sf` object, containing the suggested addresses or landmark names of the reverse geocoded POIs. The coordinates are different from the initially provided POIs since they represent the locations of the suggested addresses or landmarks.

```{r map_reverse_geocode, eval=FALSE, echo=TRUE, out.width='100%'}
if (requireNamespace("mapview", quietly = TRUE)) {
  m <-
    mapview::mapview(poi,
      alpha.region = 0, col.region = "transparent",
      label = poi$city, cex = 30, layer.name = "POIs",
      map.types = c("Esri.WorldTopoMap"), homebutton = FALSE
    ) +
    mapview::mapview(reverse_geocoded,
      col.region = "red", alpha = 0,
      label = reverse_geocoded$label, layer.name = "Adresses",
      homebutton = FALSE
    )
  m
}
```

If no addresses or landmarks are found near a POI, `NULL` for this POI is returned. In this case the rows corresponding to this particular POI are missing and merging the POIs by row is not possible. However, in the returned `sf` object, the column `"id"` matches the rows of the input POIs. The `"id"` column can be used to join the original POIs.

## API Reference

- [Geocoding & Search: Autosuggest](https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-autosuggest-brief.html)
- [Geocoding & Search: Geocode](https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-geocode-brief.html)
- [Geocoding & Search: Reverse Geocode](https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/endpoint-reverse-geocode-brief.html)
