Search code examples
javascriptleafletleaflet-geoman

Webpack lazy loading Leaflet-Geoman


I am trying to lazy load js drawing library Leaflet-Geoman

I am using webpack and the following code to load

  private async loadGeoman () {
    await import(/* webpackChunkName: "leaflet-geoman" */ '@geoman-io/leaflet-geoman-free')
  }

And then using it in the following function

  public async enableDrawing (type: TaggedType, item: any) {
    await this.loadGeoman()

    this._map.pm.enableDraw(type, {
       ...
    })
    ....

I keep getting the following error

TypeError: Cannot read properties of undefined (reading 'enableDraw')
    at DrawingService.enableDrawing (drawing.service.ts?af11:192)
    at eval (drawing.service.ts?af11:75)

It seems like the library isn't hooking up on leaflet map. Leaflet map is created before the library is loaded and i am assuming that's the problem, but i don't know how to go around it


Solution

  • Geoman is adding it self to the map while initializing the map. This means if L.Map is called before Geoman-Script is added to your site, Geoman will not be added to the map. Then you need to call L.PM.reInitLayer(map).

    public async enableDrawing (type: TaggedType, item: any) {
        await this.loadGeoman();
    
        L.PM.reInitLayer(this._map);
    
        this._map.pm.enableDraw(type, {
           ...
        })