Leaflet map displaying accurate position only upon browser resize

Let me start by showing you a screenshot of the issue I am facing. Check it out here

The screenshot clearly shows a gap between my expandable left navbar and the left border of the map image.

However, when I resize the browser window by dragging and dropping, the gap disappears. Check out the resized view here

The gray line next to the navbar represents the left side of the map image I am using.

Some additional information about my setup:

  • Using Leaflet.css and .js 1.9.3
  • Using Bootstrap 5
  • Using jQuery 3.6.3
  • Testing on a Windows machine with Xampp

I've been struggling to figure out the issue. I've tried tweaking some CSS properties like giving the #map container left: -112px; or adjusting the translate3d values for the .leaflet-map-pane, but I can't seem to pinpoint the source of the problem.

Here is the code snippet I'm using. I've broken it down to keep it as minimal as possible in hopes that someone might be able to help me identify the root cause.

jQuery and JS scripts are included in the HTML, but here they are separately:

<script>
    $groesse = 6048;
    // Create a new Leaflet map object
    var map = L.map("map", {
      crs: L.CRS.Simple
    });
    var bounds = L.latLngBounds([
      [0, 0],
      [$groesse, $groesse]
    ]);
    var wantedZoom = map.getBoundsZoom(bounds, true);
    var center = bounds.getCenter();
    map.setView(center, wantedZoom);
    map.setMaxBounds(bounds);
    // Set maximum and minimum zoom levels
    map.setMaxZoom(2);
    map.setMinZoom(-4);
    map.setZoom(-3)
    L.imageOverlay("", bounds, {}).addTo(map);
  </script>
  <script>
      function toggleFilters() {
      $('#navbar_right').animate({
        width: 'toggle'
      }, function() {});
    }

    //     // Get the toggle button and navbar_right element
    const toggleBtn = document.querySelector('.btn-toggle-filters');
    const navbarRight = document.querySelector('.navbar_right');

    // Add click event listener to the toggle button
    toggleBtn.addEventListener('click', function() {
      // Toggle the collapsed class of the navbar_right element
      navbarRight.classList.toggle('collapsed');
    });
  </script>

Here is the HTML part:

<!DOCTYPE html>
<html>

<head>
  
  <link rel="stylesheet" href="https://unpkg.com/cdn-cgi/l/email-protection" />
...

And finally, the CSS styling:

.leaflet-container {
  background-color: black;
}
...

Answer №1

Here is the style code for your reference:

 #map {
  flex: 1;
  flex-basis: max-content;
  flex-grow: 1;
  margin-left: auto;
  margin-right: auto;
  
}

It seems like there are some redundancies in your CSS styles. The use of flex:1 already encompasses flex-grow, and the margin-left and right set to auto may not be necessary for achieving the desired layout. If you are simply aiming for equal-sized divs, consider using display:flex on the parent div and setting flex:1 on the child divs in your CSS. Bootstrap's grid system can also be helpful for fine-tuning sizes. Additionally, the flex-basis styles might be confusing, especially if you are looking to expand your navigation div. Inspecting the site in the browser and checking for gaps could provide some clarity. Feel free to share the code on GitHub and provide a live site link for further assistance.

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

code, scripting - modal pop-up

My script currently has a popup window using window.open, but most browsers block this type of popups. I now want to change it to another popup that includes a php script, similar to what I've seen on other sites. It seems like they are using ajax. Ca ...

When working with NodeJS and an HTML form, I encountered an issue where the 'Endpoint'

Having trouble sending input data from a form to my nodejs endpoint. When I try printing the req.body, it shows up as undefined and I can't figure out why. Here is the relevant API code snippet: var bodyParser = require('body-parser') var e ...

Is there a way to determine if an npm package is compatible with ES6 import syntax for importing?

Aside from reviewing the documentation of the package and trying different methods through trial and error, how can one be certain if an npm package can be imported using the ES6 import syntax? Is there a specific file within the package folder that can b ...

The use of callback functions with Model.findOne() in Mongoose is now deprecated, and will result

Think about this: app.get("/posts/:postId", function(req, res) { const requestedPostId = req.params.postId; Post.findOne({_id: requestedPostId}, function(err, post) { res.render("post", { title: post.title, content ...

Cover any HTML element with a translucent overlay box

I have a unique problem with an HTML file that is out of my control when it comes to its content. My only option is to inject a CSS file and/or JavaScript (potentially using libraries like jQuery) into the mix. Within this HTML, there are elements that re ...

Is it possible to encase <v-img> within an anchor element?

I am currently using Vuetify 1.5 and have included a couple of <v-avatars></v-avatars> elements in which there is a nested <v-img></v-img>. I attempted to enclose the img tags within an a tag but encountered an issue wherein the ima ...

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

I am interested in designing a dynamic wave-themed background for a menu

I am looking to create a menu background that ripples like a wave when hovered over. Check out the first example here: https://i.sstatic.net/LoOWM.png I want to achieve the same effect. Can anyone help me with how I can do this? <ul> <li>likk ...

Strategies for aligning a div element in the middle of the screen

Positioned in the center of the current viewport, above all other elements. Compatible across different browsers without relying on third-party plugins, etc. Can be achieved using CSS or JavaScript UPDATE: I attempted to use Javascript's Sys.UI.Dom ...

Typescript - type assertion does not throw an error for an invalid value

When assigning a boolean for the key, I have to use a type assertion for the variable 'day' to avoid any errors. I don't simply do const day: Day = 2 because the value I receive is a string (dynamic value), and a type assertion is necessary ...

ng-view scope interacting with parent scope connection

Excuse the late-night desperation, but I have a question about my AngularJS application that uses ngRoute. Currently, everything is being handled in one controller. The issue arises with a form in a view where I need to take the input field data and store ...

What could be causing my Bootstrap modal to fail to load dynamically?

I'm currently immersed in a fun side project, where data is fetched from a MySQL database and dynamically displayed. Everything seems to be running smoothly except for the modal display issue. The ID always matches, but the modal just won't open. ...

As soon as a key is pressed in tinyMCE, the tracking continues until reaching the conclusion of the initial <

I am attempting to capture, in real-time, the user input in the .content textarea and paste it into the .intro. I have tried the following code without success: //This code is specifically for tinymce, as I am using tinyMCE as a rich text editor for textb ...

Is it possible for me to create an If statement that can verify the current index within a Map?

I have the following TypeScript code snippet: export default class SingleNews extends React.Component<INews, {}> { public render(): React.ReactElement<INews> { return ( <> {this.props.featured ...

What methods are available to stop Internet Explorer from caching HTML content without resorting to utilizing arbitrary query parameters?

To avoid caching HTML on postbacks in Internet Explorer, we are currently utilizing random query strings, but our goal is to transition to URL re-writing. Removing these random parameters would be ideal. What is the recommended approach for resolving this ...

Troubleshooting Safari compatibility issues with Twitter Direct Messages in Angular

I am attempting to create a Twitter direct message with predetermined text already filled in. My current method involves using window.open() to prepare the message. window.open(https://twitter.com/messages/compose?text=${this.helloWorld}); helloWorld = ...

Fetching data using an Ajax request can yield varying response values from PHP

Here is the ajax request code I am currently using: $("#input_form").on("your change event",function(e){ if(changeTimer !== false) clearTimeout(changeTimer); changeTimer = setTimeout(function(){ $.ajax({ type: 'POST', ...

Angular 7: Resetting multiple dynamically generated checkboxes back to their original state with the click of a button

I have created a child component that contains 3 checkboxes, generated dynamically using ngFor, along with Apply and Cancel buttons. In the parent template, I include the selector tag for the child component. The parent component accesses this child compo ...

React Router will not remount the component when using this.context.router.push

We have implemented a click handler that utilizes react router 2.0 to update the URL with this.context.router.push(). Here is the code snippet: selectRelatedJob(slug) { JobActionCreators.fetchJobPage(slug); JobsActionCreators.getRelatedJobs({'sl& ...

Can we display the chosen form values before submitting?

Want to implement a confirmation message for users before submitting their form using onClick="return confirm('are you sure ?')". The basic form structure is as follows: <form> <Select name='val[]' class='select'> ...