0

I'm have been trying to use leaflet.js library with react.js and following this code:

import {L} from 'leaflet'

const myApp = () => {

const map = L.map("map").setView([45, 1], 4);

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

L.control.scale().addTo(map);
L.marker([45, 1], {icon: new L.Icon({iconUrl: 'https://unpkg.com/leaflet@1.6.0/dist/images/marker-icon.png'})}).addTo(map);

return (
    <div id="map" style="height:100vh"></div>
)}

I get the following type error: TypeError: Cannot read properties of undefined (reading 'map') in line:

const map = L.map("map").setView([45, 1], 4);

Any ideas how to solve it?

OfekKaveh
  • 3
  • 2

1 Answers1

0

There are multiple issues to address here.

Library is being imported incorrectly - It should be

import L from "leaflet";

The div with the id map needs to be rendered before executing the code L.map - for more information refer to Leaflet: Map container not found

With these 2 fixes applied it should work - working example https://codesandbox.io/s/agitated-galileo-w6now?file=/src/App.js:42-67

Besnik Korça
  • 939
  • 3
  • 9