nkforce
nkforce

Reputation: 39

React & Leaflet: Map container not found

I tried to use function component to load the leafletmap but got an error saying "Map container not found". I found a solution which is to add <div id="map"> to DOM. I couldn't find a way to do this in function component. I ended up using class component to do this, and it works:

import React from "react";
import L, { LeafletMouseEvent } from "leaflet";
import "leaflet/dist/leaflet.css";
import icon from "leaflet/dist/images/marker-icon.png";
import iconShadow from "leaflet/dist/images/marker-shadow.png";

let DefaultIcon = L.icon({
  iconUrl: icon,
  shadowUrl: iconShadow,
});

class LeafletMap extends React.Component {
  componentDidMount() {
    this.map();
  }

  map() {
    L.Marker.prototype.options.icon = DefaultIcon;
    var mapSW = new L.Point(0, 960),
      mapNE = new L.Point(960, 0);
    var map = L.map("map", { crs: L.CRS.Simple }).setView([0, 0], 4);

    L.tileLayer("/assets/maps/map0/{z}/{x}/{y}.png", {
      tileSize: 32,
      minZoom: 4,
      maxZoom: 5,
      noWrap: true,
    }).addTo(map);

    var maxBounds = L.latLngBounds(
      map.unproject(mapSW, map.getMaxZoom()),
      map.unproject(mapNE, map.getMaxZoom())
    );
    map.setMaxBounds(maxBounds);

    var marker = L.marker([0, 0], {
      draggable: true,
    }).addTo(map);
    marker.bindPopup("<b>Our hero!</b>").openPopup();
    function onMapClick(e: LeafletMouseEvent) {
      let tileSize = new L.Point(32, 32);
      let pixelPoint = map.project(e.latlng, map.getMaxZoom()).floor();
      let coords = pixelPoint.unscaleBy(tileSize).floor()
      alert("You clicked the map at " + coords);
    }
    map.on("click", onMapClick);
  }

  render() {
    return <div id="map"></div>;
  }
}

export default LeafletMap;

this is where the LeafletMap component gets called:

const comp: React.FC<RouteComponentProps> = () => {
  return (
    <div>
      <Grid columns={2}>
        <Grid.Column>
          <LeafletMap/>
        </Grid.Column>
        // codes
      </Grid>
    </div>

Now I need to use hook features so I have to use function component. How do I solve the "Map container not found" error or add map element to DOM using function component?

Upvotes: 0

Views: 3563

Answers (2)

hoogw
hoogw

Reputation: 5535

I had same error, the working solution is here,

the same question is Leaflet: Map container not found

The error caused by

The div id="map" must be added to the dom before calling L.map('map').

The solution is use:

         useEffect(() => {

This is my working app.js :

           import React, { useState, useEffect } from 'react';



           import './App.css';

           import L from 'leaflet';
           import 'leaflet/dist/leaflet.css';


           function App() {






          // Similar to componentDidMount and componentDidUpdate:
          useEffect(() => {



                              let current_lat = 28.625789;
                              let current_long = 77.0547899;
                              let current_zoom = 16;
                              let center_lat = current_lat;
                              let center_long = current_long;
                              let center_zoom = current_zoom;




                              // The <div id="map"> must be added to the dom before calling L.map('map')
                                let map = L.map('map', {
                                  center: [center_lat, center_long],
                                  zoom: center_zoom
                                });

                                L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
                                  attribution: '&copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                                }).addTo(map);



          });





                  return (


              

                                <div class="right-sidebar-container">
                                        
                                  <div id="map">

                                  </div>
                                
                              </div>

                  );





         } // app







     export default App;

Upvotes: 0

kboul
kboul

Reputation: 14600

From the code you have included it seems you are not using react-leaflet but native leaflet code instead.

It shouldn't be a problem to use your class component as a function. Replace componentDidMount with an effect hook and remove render method

 export default function LeafletMap() {
      useEffect(() => {
        map();
      }, []);
    ...rest of code same as yours only remove render method
      return <div id="map" style={{ height: "100vh" }}></div>;
    }

Since you are using typescript maybe the error comes from there due to a wrong type.

I used an openstreet map tile provider (because you are using a custom one) and some fixed icons and it seems to be working without errors

Demo

Upvotes: 3

Related Questions