After successfully implementing the technique of displaying an image on hover in a regular R plotly chart, I encountered issues when trying to apply the same method to a plotly map. Specifically, the approach broke down and failed to display the image. Can anyone assist in modifying the code to make it work with a plotly map?
library(dplyr)
library(plotly)
df <- data.frame(x = c(-81.026, -81.025, -81.028), y = c(44.13, 44.14, 44.15),
url = c("https://upload.wikimedia.org/wikipedia/commons/6/6f/Beethoven.jpg",
"https://upload.wikimedia.org/wikipedia/commons/4/47/Croce-Mozart-Detail.jpg",
"https://upload.wikimedia.org/wikipedia/commons/6/6a/Johann_Sebastian_Bach.jpg"))
d3 <- htmltools::htmlDependency(
"d3", "7.3",
src = c(href = "https://cdnjs.cloudflare.com/ajax/libs/d3/7.3.0/"),
script = "d3.min.js"
)
js <- '
function(el) {
var tooltip = d3.select("#" + el.id + " .svg-container")
.append("div")
.attr("class", "my-custom-tooltip");
el.on("plotly_hover", function(d) {
var pt = d.points[0];
var x = pt.xaxis.range[0];
var y = pt.yaxis.range[1];
var xPixel = pt.xaxis.l2p(x) + pt.xaxis._offset;
var yPixel = pt.yaxis.l2p(y) + pt.yaxis._offset;
var img = "<img src=\\\"" + pt.customdata + "\\\" width=100>";
tooltip.html(img)
.style("position", "absolute")
.style("left", xPixel + "px")
.style("top", yPixel + "px");
tooltip.transition()
.duration(300)
.style("opacity", 1);
});
el.on("plotly_unhover", function(d) {
tooltip.transition()
.duration(500)
.style("opacity", 0);
});
}
'
The above code successfully displays an image on hover
p <-plot_ly(df, x = ~x, y = ~y, type = "scatter", mode = "markers", hoverinfo = ~x, customdata = ~url) %>%
htmlwidgets::onRender(js)
p$dependencies <- c(p$dependencies, list(d3))
p
However, the following code fails to display the image on a plotly map...
p <- plot_ly(df, lon = ~x, lat = ~y, type = "scattermapbox", mode = "markers", hoverinfo = ~x, customdata = ~url) %>%
layout(mapbox = list(style = "white-bg", sourcetype = 'raster', zoom = 4,
center = list(lon = -81 ,lat= 44),
layers = list(list(below = 'traces', sourcetype = "raster",
source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"))))) %>%
htmlwidgets::onRender(js)
p$dependencies <- c(p$dependencies, list(d3))
p