'R leaflet: how to change initial zoom based on device (desktop vs mobile)?

I have a map that has a specific view and zoom specified that is good for desktop, however if the user is on a phone I need to adjust the zoom so that the continental U.S. is all viewable on the smaller device.

I'm using an RMD to build this in order to add some other functionality.

For desktop the zoom should be 3.5, but if mobile is detected, the zoom should be 1.

Example map:


library(leaflet)
leaflet() %>%
        addProviderTiles(providers$OpenStreetMap) %>%
        setView(lng=-100, lat=38, zoom=3.5)

I've tried adding this to the <head>: <meta name="viewport" content="width=device-width, initial-scale=1.0">

and then I have a js chunk with the following

```{js}
  // listen for screen resize events
window.addEventListener('resize', function(event){
  // get the width of the screen after the resize event
  var width = document.documentElement.clientWidth;
  console.log(event);
  // tablets are between 768 and 922 pixels wide
  // phones are less than 768 pixels wide
  if (width < 768) {
    // set the zoom level to 1
    map.setZoom(1);
  }  else {
    // set the zoom level to 3.5
    map.setZoom(3.5);
  }
});
```

When I use the inspector console, I see the following when I resize the window: enter image description here

I have tried defining the map various ways, for instance var map = L.map, but that doesn't work, nor does L.map.setZoom(1), (error: L.map.setZoom is not a function).

I think one issue is that while in pure JS, leaflet code requires naming the map object, but I don't know what R leaflet names them.

Also in case it matters I am building 3 maps at once into a flex dashboard, so I would think that there would be 3 different map variables? However I've tried my code with only one map included and the errors are the same.

I have tried fitBounds and it does not work as expected. I temporarily added mouse coordinates and set the map as I wanted it, then recorded the lat/lon of the top left and bottom right corners. I then set the fitBounds to that and re-generated the map. When it loads, the zoom is less and the corners are way further away that what I set.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source