helpful when using mapshot/saveWidget + webshot to ensure map is zoomed to desired level
### zoom to after rendering (relevant for mapshot)
library(mapview)
map = mapview(franconia)@map
m = htmlwidgets::onRender(
map,
paste0(
"function(el, x, data) {
// get the leaflet map
var map = this;
var z = map.getZoom();
map.setZoom(z + 1);
}"
)
)
mhelpful when using mapshot/saveWidget + webshot to ensure map is zoomed to desired bounds
### fit bounds
library(mapview)
library(leaflet)
library(sf)
map = mapview(franconia) + gadmCHE
bounds = unname(st_bbox(franconia[1, ]))
m = htmlwidgets::onRender(
map@map,
paste0(
"function(el, x, data) {
// get the leaflet map
var map = this;
var bounds = [[", bounds[2], ", ", bounds[1], "],
[", bounds[4], ", ", bounds[3], "]];
map.fitBounds(bounds);
}"
)
)
mThis will let you control the opacity of a ratser layer using o/t buttons to increase/decrease opacity (opaque vs. transparent)
library(mapview)
library(raster)
library(leaflet.opacity)
library(leaflet)
addOpacityKeyControl <- function(map, layerId) {
if (inherits(map, "mapview")) map = map@map
map$dependencies <- c(map$dependencies, leaflet.opacity:::dependency())
data = list(layerId = layerId)
htmlwidgets::onRender(
map,
htmlwidgets::JS("function(el,x,data){
var map = this;
var opacitySlider = new L.Control.opacitySlider();
var opacityLayer = map.layerManager.getLayer('image', data.layerId)
opacitySlider.setOpacityLayer(opacityLayer);
decreaseOpacity = function() {
op = opacity_layer.options.opacity;
var op_target = op - 0.1;
if (op_target < 0) op_target = 0;
opacity_layer.setOpacity(op_target);
console.log(opacity_layer.options.opacity);
}
increaseOpacity = function() {
op = opacity_layer.options.opacity;
var op_target = op + 0.1;
if (op_target > 1) op_target = 1;
opacity_layer.setOpacity(op_target);
console.log(opacity_layer.options.opacity);
}
map.on('keypress', function(e) {
console.log(e.originalEvent.code);
var key = e.originalEvent.code;
if (key === 'KeyO') {
increaseOpacity();
}
if (key === 'KeyT') {
decreaseOpacity();
}
});
}"),
data)
}
mapview(poppendorf[[4]], layer.name = "pop") %>%
addOpacityKeyControl("pop")Note that you will need to click on the map once to "activate" the behaviour.