Adjust Leaflet map size when the containing element is resized (Dash Plotly)

I am encountering some difficulties with dash-leaflet, particularly regarding its width when the parent container is resized. I am utilizing dash-resizable-panels to resize certain divs.

Allow me to present a Minimal Reproducible Example (MRE) below:

# pip install dash dash-leaflet dash-resizable-panels
import dash
import dash_leaflet as dl
from dash import html
from dash_resizable_panels import PanelGroup, Panel, PanelResizeHandle

handle = {"height": "100%", "width": "3px", "backgroundColor": "#51ada6"}
layout = html.Div([
    PanelGroup(id="panel-group", 
               children=[
                    Panel(id="panel-1",children=[html.Div([html.P("Dummy component")])]),
                    PanelResizeHandle(html.Div(style=handle)),
                    Panel(id="panel-2",
                          children=[
                            dl.Map(center=[45.81, 15.98], zoom=12, children=[
                                dl.TileLayer(),
                                dl.FeatureGroup([dl.EditControl()]),
                            ], style={'height': '100%', 'width': '100%'})]
                    )], direction="horizontal",),
], style={"height": "100vh"})

app = dash.Dash(__name__)
app.layout = layout
if __name__ == "__main__":
    app.run_server()

The initial layout appears to be satisfactory:

https://i.sstatic.net/efZGfkvIl.jpg

However, upon resizing the map container, an unrendered portion of the map becomes visible (gray area on the right). Here is a visual representation:

https://i.sstatic.net/f5iq9jK6l.jpg

Is there a method, whether through Python or JS, to resize or rerender the leaflet map when the container is resized so that the map completely fills the width of its container?

SOLUTION:

app.clientside_callback(
        """
        function set_event(map_id) {

            // On resize event 
            var callback = function() {
                window.dispatchEvent(new Event('resize'));
            }

            new ResizeObserver(callback).observe(document.getElementById(map_id))

            return dash_clientside.no_update;
        }
        """,
        Output("map", "id"),
        Input("map", "id")
    )

Answer №1

SOLUTION:

defining_event_callback(
        """
        function set_interaction(element_id) {

            // Event listener for click 
            var callback = function() {
                // Trigger custom event
                element.dispatchEvent(new Event('customEvent'));
            }

            new EventListener(callback).observe(document.getElementById(element_id))

            return no_update;
        }
        """,
        Output("element", "id"),
        Input("element", "id")
    )

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate barcodes using Angular 2

Can anyone point me in the direction of an Angular 2 Barcode Generator capable of creating code 128 barcodes? I've been searching but haven't had any luck finding one. If you have any suggestions or can offer assistance, it would be greatly appr ...

Using gulp to compile TypeScript is resulting in a directory being generated that we do not want

My goal is to use Gulp to transpile my .ts files located in the /dev directory, and then move the transpiled .js file to a /build directory. The ideal folder structure I am aiming for is as follows: /dev - index.ts /build - index.js However, the curre ...

Is it necessary to sanitize strings before assigning them as the content of a textarea element?

Consider the situation described below: var evil_string = "..."; $('#mytextarea').val(evil_string); Is it necessary to sanitize an untrusted string before setting it as the value of a textarea element? While I am aware of the importance of han ...

Tips for implementing the new useState value in your code

Using DataGrid Material UI, I am facing an issue where the selected row is not being deleted when clicking on the delete button. The problem arises from setting the ID value in the useState hook and encountering asynchronous behavior in deleting the rows. ...

Interactive game created using JavaScript input

I've scoured the internet for guidance on creating a text-based game that utilizes user input, but all I come across are tutorials focusing on button interactions. What I envision is triggering different responses based on specific user inputs. For i ...

Tips for preventing the colors of all buttons from changing when only one is clicked in JavaScript

const tasks = `[{ "taskName": "Task 1", "image": "./images/task1.jpg", "description": "Task 1 description", "importance": 0 }, { "taskName": "Task 2", "image": "./images/task2.jpg", "description": "Task 2 description", ...

What is the best way to create transitions for item entry and exit in ReactJS without relying on external libraries?

I am looking to create an animation for a toast notification that appears when a user clicks on a button, all without the use of external libraries. The animation successfully triggers when the toast enters the screen upon clicking the button. However, I e ...

An AJAX function nested within another AJAX function

Is there a way for me to return the second ajax call as the result of the ajax function? I could use some assistance with this. function ajax(url: string, method:string, data:any = null) { var _this = this; return this.csrfWithoutDone().done(funct ...

Store the ID of a div in a variable

Currently, I have transformed rock paper scissors from a terminal/console game using prompts and alerts to something playable in a web browser through the use of the jQuery library. In order to achieve this transition, I created images for each hand - roc ...

Running JavaScript code without blocking the main thread

While studying JavaScript and JSON, I encountered some issues. I have a script that functions with JSON data, but the performance of my code is not optimal. The code only works when I debug it step by step using tools like Firebug which leads me to conclud ...

Establishing a connection to a JSON API to retrieve and process

I am trying to extract all instances of names from this page: . For guidance, I have been using this tutorial as a reference: . However, when I run the code provided, it doesn't return anything. What could be going wrong? var request = new XMLHttpRe ...

What is the process for setting up an automatic submission for the "Search" feature?

My Perspective: @using (Html.BeginForm()) { <p id="a"> Search for VCMEMBRE/VCPARENT: @Html.TextBox("SearchString") <input type="submit" name="searchType" value="Find!" /> </p> } My Handler: public ActionResult ...

Whenever I attempt to use for or while loops in my application, it consistently crashes

I've recently started learning reactjs and I'm working on a simple app. I created a decrement button that should only work if the item count is greater than or equal to zero. However, when I tried using while and for loops in my code, my app cras ...

Ways to prevent onMouseDown from triggering when the element is exclusively clicked?

I'm currently working on developing a game where units (svg elements) are controlled using React. In this game, the units should be draggable, and clicking on a unit should open a form. However, when I click on the unit, only the mousedown event is t ...

safely sending different form inputs in a Ruby on Rails form

Within this snippet, you'll find a part of a table with a form. Each row has its own submit button, which means users have to click on each one individually. I'm currently working on changing this so there is just one button for submission. < ...

Activate audio when the link is clicked

Recently, I created a compact web application and it's almost complete. However, there is one cool functionality that I am missing. My goal is to have a sound play when the user clicks a link, but after playing, I want the navigation to continue as us ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

Javascript Dependencies Are Failing to Load with Ajax

My index.php file has the functionality to load content based on a $_GET variable. Here's how it works... <?php $problem_id = $_GET['problem_id']; include('include/' . $problem_id . '.php'); ?> For example, ...

Incorporate a customizable month option within a flexible calendar design

I'm working on creating a calendar that adjusts to different screen sizes for my website. The script I've implemented is as follows: <script type="text/javascript"> $(document).ready(function () { $(".responsive-calendar").responsiv ...

Exploring the Contrast between window.location.href and top.location.href

I'm curious about the distinction between window.location.href and top.location.href. Can anyone explain this to me? Furthermore, I'd like to know when it's appropriate to use each one. Which option is more suitable for redirection after a ...