I am a great fan of package tmap for visualizing spatial data in R. One less known, but very interesting and useful, feature of the package is the option to add custom icons on map.

This has obvious implications for showing points of interest - such as placing a corporate logo to mark branches or other places of physical presence.

In this example I will be combining the powers of tmap package and Google, or rather package ggmap (which uses Google Maps Geocoding API as a backend for its geocode() function). In a sort of Halloween spirit I will be placing an image of a bat to mark a set of semi-random locations in Prague.

To make the map prettier and easier to read I am including the shape of river Vltava and a distance marker.

The custom icon is defined by calling tmap_icons() with the file name of the bat icon (in this case local, but it could be an url linking to an image on internet as well). It is then passed to the shape argument of the tm_symbols() call.

On a side note: I was pleasantly surprised by the robustness of Google geocoding API. It is able to (correctly) geocode not only well defined street names, but also rather broadly defined points of interest.

The full code to generate the map:


cityMap <- obce_polygony[obce_polygony$NAZ_OBEC == 'Praha', ] # Prague city borders

bbox <- st_bbox(cityMap) %>%
  st_as_sfc() # out with the old, in with the sf!
vltava <- reky[reky$NAZEV == 'Vltava', ] # The city looks better with its river drawn
vltava <- st_intersection(vltava, bbox) # just the part flowing through the city

mista <- c('úřad městské části praha 11', 'kramářova vila', 'Babická 2329, Praha 4') 
# a vector of names of POIs to be vizualized

POI <- geocode(mista, output = "latlon") %>% # let Google sweat!
 st_as_sf(coords = c("lon", "lat"), crs = 4326) # make the points of interest feel spatial!

icon <- tmap_icons('2017-11-11-netopejr.png')
# png file of the icon to be drawn; can be local or remote (url)

tm_plot <- tm_shape(cityMap, height = 1.3, relative = T) + tm_borders("grey30", lwd = 1.5, lty = 'dotdash') +
  tm_shape(vltava) + tm_lines(col = 'steelblue', lwd = 2.5) +
  tm_shape(POI) + tm_symbols(shape = icon, size = 0.7, border.lwd = NA) +
  tm_style_white("Prague Haunted Places", frame = F, fontfamily = "Roboto", title.size = 2) +
  tm_scale_bar(color.dark = "grey30")