Search code examples
javascriptreactjsleafletreact-leafletreact-leaflet-draw

React leaflet and react-leaflet-draw


I'm trying to implement the draw functions on leaflet map. I've created a new app with only react-leaflet installed, using npx create-react-app and the following packages installed:

  • npm install react react-dom leaflet
  • npm install react-leaflet

At this point, I've started the application and everything is working fine: the map is correctly visualized with a marker in the middle.

Then I've added the react-leaflet-draw package, with npm install react-leaflet-draw, and import it in the page I get the following error:

./node_modules/react-leaflet-draw/dist/esm/EditControl.js
Attempted import error: 'MapControl' is not exported from 'react-leaflet'

This is the full code:

import './App.css';
import 'leaflet/dist/leaflet.css';
import { MapContainer, TileLayer, Marker, Popup, MapControl } from 'react-leaflet'
import L from 'leaflet';
import icon from 'leaflet/dist/images/marker-icon.png';
import iconShadow from 'leaflet/dist/images/marker-shadow.png';
import iconRetina from 'leaflet/dist/images/marker-icon-2x.png';

import 'leaflet-draw/dist/leaflet.draw.css';
import { EditControl } from "react-leaflet-draw";


delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: iconRetina,
  iconUrl: icon,
  shadowUrl: iconShadow
})



function App() {
  return (
    <MapContainer center={[51.505, -0.09]} zoom={10} scrollWheelZoom={true}>
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Marker position={[51.505, -0.09]}>
        <Popup>
          A pretty CSS3 popup. <br /> Easily customizable.
    </Popup>
      </Marker>
    </MapContainer>
  );
}

export default App;

What's the issue with this package? Does it work on react?


Solution

  • If you check this github issue you will conclude that react-leaflet-draw is only compatible with react-leaflet versions 2.x and not with versions 3.x.

    As a result it does not work in your case because you are using react-leaflet version 3.x.

    If you downgrade to versions 2.x it should work as expected

    Last but not least you do not need to import MapControl as it is not required from the package. You only need to import

    import { EditControl } from "react-leaflet-draw"
    

    as you already did. MapControl is used internally in the library and probably something has changed in the newer version, that is why you get the error.