I am currently developing a small shiny application that uses an interactive map. The idea is very simple: I am trying to plot a handful of points in a map using lat/long coordinates. I cannot use google's API, so I used plotly's scatter plot, specifying a map layout.
This is a generic representation of what I have so far:
fig <- plotly::plot_ly(
data = data,
lat = data$lat,
lon = data$long,
mode = "markers",
marker = list(size = 10),
type = 'scattermapbox',
hovertext = paste0(
paste0("Some info 1: ", data$field1, "\n"),
paste0("Some info 2: ", data$field2, "\n"),
paste0("Some info 3: ", data$field3)
)
)
# specify layout as open street map
fig <- fig %>%
layout(
mapbox = list(
style = 'open-street-map',
zoom = 3,
center = list(lat = -20.72623, lon = -47.74942))
)
print(fig)
Considering that my "data" dataset has the fields and coordinates, the result I'm getting is this:
What I am not able to do is change the marker symbols. According to plotly's documentation (https://plotly.com/r/reference/#scatter-mode), it is as simple as defining symbol = "some_symbol", but that won't work. I've seen some examples and some workarounds, but none seem to work very intuitively.
Ideally, I wanted to generate a map that looked like this:
Does anyone know if this is even possible with a simple scatterplot? Is there any other way? Am I missing something here?
I found a solution for this, although using a different package.
Using the leaflet
package, I was able to create a map using the same open-street-map
layout. The default marker symbol/icon is a pin, but you can create any customized icon you want, using svg files. The leaflet documentation is specified
here.
My specific solution was defining the hovertext as a set of labels and then simply calling the addMarkers
function inside the leaflet
object.
labels <- lapply(seq(nrow(data)), function(i) {
paste0( '<p><b> Some information: ', data[i, "field1"], '</b></p>',
"<p> Some other information : ", data[i, "field2"] / 1000, ' MWm </p>',
"<p> Some different information : ", data[i, "field3"],'</p>')
})
fig <- leaflet::leaflet(data = data) %>% leaflet::addTiles() %>%
leaflet::addMarkers(
~as.numeric(longitude),
~as.numeric(latitude),
label = lapply(labels, htmltools::HTML)
)
print(fig)