The leaflet map I created is not showing up on my website for some reason

I am currently working on a project using ReactJS and NextJS.

One issue I am facing is that my leaflet map is not filling the entire parent div on my page, and it is not showing up at all. I had expected the map to automatically adjust to the parent div size, but it seems that is not the case. Does anyone have any suggestions on how to resolve this issue?

Below is the snippet of my leaflet code:

const Wrapper = styled.div` 
  width: ${props => props.width};
  height: ${props => props.height};
`;

const location = [34.0522, -118.2457]
export default class Map extends Component { 
  componentDidMount() {  
    this.map = L.map("map", { 
      center: location,
      zoom: 12,
      zoomControl: true
    })
    L.tileLayer('https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', {
      maxZoom: 20,
      attribution: '© Openstreetmap France | © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    })
    .addTo(this.map) 

    var marker = L.marker(location, {icon: placeholder}).addTo(this.map); 
    setTimeout(() => {
      marker.bindPopup("Come see us, it would be awesome!", {maxWidth: "500"});  

      this.map.setView(location);
    }
  }

  render() { 
    return (
      <Fragment>
        <Head>
          <link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/images/marker-icon-2x.png"/>
          <link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.4.0/images/marker-icon.png"/>

          <link rel="stylesheet" href="https://unpkg.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="254940444349405165140b110b15">[email protected]</a>/dist/leaflet.css"
   integrity="yyyy"
   crossorigin=""/> 

          <script src="https://unpkg.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d21282c2b2128390d7c6379637d">[email protected]</a>/dist/leaflet.js"
   integrity="yyyyy"
   crossorigin=""></script>   
        </Head>
        <Wrapper width="100%" height="100%" id="map"/> 
      </Fragment>
    )
  }
} 

Any help or hint would be greatly appreciated, Thank you

Answer №1

In my opinion, it's not advisable to set the width and height of the div containers for the map as 100%. Instead, consider specifying a width of 1200px and a height of 600px to ensure better visualization. You can rest assured that leaflet maps are designed to be responsive in nature.

Answer №2

If you're on the hunt for a specific way to implement React, look no further:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import './styles.css';

class App extends Component {
  state = {
    center: [51.505, -0.091],
    zoom: 13,
  };

  render() {
    return (
      <div>
        <Map center={this.state.center} zoom={this.state.zoom}>
          <TileLayer
            attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
          />
          <Marker position={this.state.center}>
            <Popup>
              A stylish CSS3 popup. <br /> Customizable with ease.
            </Popup>
          </Marker>
        </Map>
      </div>
    );
  }
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);  

Don't forget to include this style in your CSS file:

.leaflet-container {
  height: 600px;
  width: 100%;
}

Check out the live code example here:https://codesandbox.io/s/2wnv7o1mlr

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

Using Sinon to create a mock of a function

I'm having trouble figuring out a simple task like the one below: render() { return ( <div className="messageDetail"> <div className="messageForm" > Name: <input id="senderMsgName" value={this.props.nameVa ...

"415 (Unsupported Media Type) encountered when making a POST request in a REST API

I've encountered an issue with a React component where a checkbox triggers a POST request to a REST API with a single parameter. Despite setting a breakpoint in the WebAPI code, it's not being hit and I'm receiving a 415 Unsupported Media Ty ...

To implement a server-side 301 redirect to force the URL to go to www in React.js using Next.js

I am currently facing an issue with routing my website to redirect to the www server side. Specifically, when a user visits my website example.com, I want to redirect them to www.example.com. To achieve this, I have implemented a redirect using Next.js in ...

The function successfully triggers when clicked using (React, JS, TS) but does not respond to key presses

When the function is called with "onClick", it works correctly, but when called with "onKeyPress", it does not execute an if statement. scenario Consider a scenario where you can search for food recipes (e.g. "pizza") and receive a list of recipes from a ...

ReactJS: The /dist directory contains a minimal set of files, including only bundle.js and bundle.js.map. There are no additional files included in this folder

I am having trouble with my reactjs app. It runs smoothly in the development environment when I use npm start The app launches without any issues on localhost:8080. However, when I try to generate a distribution folder for static hosting on AWS S3 using t ...

"Transforming icons into text within the material-ui-table component: A step-by-step guide

If I want to replace the + icon in a material-table row with text like "ADD ROW," is there any way to do it? The material-table only accepts the icon object, and there doesn't seem to be another prop that allows for text replacement. I am utilizing th ...

Utilizing useEffect in the header component of ReactJS/Next.js: A Comprehensive Guide

In my next.js/react project, I have a component called header.js that is included on every page. Within this component, I've implemented a typewriter effect with rotation by using the following code snippet inside useEffect: export default function H ...

Unable to assign a value to an element obtained from the Axios response in React

I'm having trouble mapping an array, it doesn't seem to be working. You can find the code here : https://codepen.io/ilaan16/pen/eYRKgOm setUtils(result.data); if (!utils) { console.log("ERROR_UTILS", result); } else if ...

Encountered an issue with useContext in Next.js, displaying the error message: "Unhandled Runtime Error TypeError: Right side of assignment cannot be destructured"

Regarding the middle component used in page.tsx and the error encountered: "use client" import React from 'react' import { CiSearch } from 'react-icons/ci' import { FaPlus } from 'react-icons/fa' // Other import ...

Creating a border with a unique and specific image

Is there a way to use an image as the border for my div elements? The key requirement is that the border must be positioned outside the box without affecting its size. It's important to note that all div items have the same width, but varying heights ...

What steps should I follow to ensure that the "-> comes after the text?

Here is the link to my page: . Currently, the arrow appears under the text. I am looking for a way to rearrange it so that the arrow comes after the text while still maintaining its hover effect. Can you provide any suggestions? ...

Tips for creating responsive content within an iframe

I have inserted a player from a website that streams a channel using an iframe. While I have managed to make the iframe responsive, the video player inside the iframe does not adapt to changes in viewport size. Despite trying various solutions found online ...

How to optimize the loading speed of background images in an Angular application

Utilizing Angular v6, typescript, and SASS for my project. A CSS background image is set for the homepage, however, it's a large photo that always takes too long to load. Custom CSS: @import '../../../scss/variables'; :host { .wrapper { ...

Can the z-index of a div be altered by a checked checkbox?

I've been trying to figure out how to make a PayPal button only clickable after the user confirms the Terms of Service. My idea is to place another div over the PayPal button with an unchecked checkbox, opacity, and z-index. When the user checks the c ...

Conceal a Column in Material UI Data Grid Filter

I've managed to conceal the id within the columns, but how can I also hide it in the filter? <StyledDataGrid getRowId={(r) => r.newId} columns={columns} rows={rows} disableSelectionOnClick checkboxSelection />; const columns = [ ...

How come default props do not prevent a TypeError from occurring with a destructuring assignment within a component?

I am facing an issue with a component that requires a prop a which should be an object with a property b: const MyComponent = ({ a: { b } }) => b; MyComponent.defaultProps = { a: { b: 4, }, }; This component is linked to a Redux store: expor ...

NPM and GitBash are both currently experiencing technical difficulties. What steps can be taken to resolve this issue?

My experience with GitBash is limited, especially in relation to VisualStudio Code. The main issue I'm encountering involves getting React.js to work properly within VSCode. Below is the error message currently being displayed. D:\_Dearest_Lord_G ...

"The incredible power of the spread operator in conjunction with EsLint

Is there a way to duplicate an object and modify one of its properties? Here's an example: const initialState = { showTagPanel: false, }; export default function reducerFoo(state = initialState, action) { switch(action.type) { case types.SH ...

When hovering over the background, it will enlarge but the text in front will remain the same size

As the user hovers over the image, the image enlarges. However, there is also some information that needs to be displayed in front of the image. This is my current implementation: .home-about-link { overflow: hidden; width: 100%; } .home-about { ...

Keep the table header in place while scrolling

I am currently working with Bootstrap V4 alpha 6 and Angular 5 to develop a table that includes a fixed header while scrolling. Unfortunately, I have been facing challenges in getting this functionality to work effectively. Note: The navbar is set to fixe ...