The issue at hand is that the property 'Draw' is not found within the 'Control' type

I am working on integrating a map component using leaflet and other leaflet plugins. However, I am facing an issue where the other plugins do not seem to work with TypeScript for some unknown reason.

For instance, I am encountering a problem when trying to compile code with the leaflet-draw plugin, getting the following error:

Property 'Draw' does not exist on type 'typeof Control'

In my mapbox.component.ts file:

import { DataService } from "../data-service.service";
import { Component, OnInit } from '@angular/core';


import * as $ from 'jquery';
/// <reference types="leaflet" />
/// <reference types="leaflet-draw" />

declare var require: any


@Component({
    selector: 'app-mapbox',
    templateUrl: './mapbox.component.html',
    styleUrls: ['./mapbox.component.css']
})

export class MapboxComponent implements OnInit {

    constructor(private dataService: DataService) { }
    // helper flags
    map: L.Map = null;
    aggreagte: boolean = false;

    ngOnInit() {
        // Prepare map
        this.map = L.map('resultmap').setView([51.505, -0.09], 1);
        //
        L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
            attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
            maxZoom: 18,
            id: 'mapbox.streets',
            accessToken: '...'
        }).addTo(this.map);

        var drawnItems = L.featureGroup();
        this.map.addLayer(drawnItems);
        var control = new L.Control.Draw();
        ...

In angular-cli.json:

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "app",
      "styles": [
        "styles.css",
        "../node_modules/leaflet/dist/leaflet.css",
        "../node_modules/leaflet-markercluster/MarkerCluster.css",
        "../node_modules/leaflet-draw/dist/leaflet.draw.css"
      ],
      "scripts": [
        "../node_modules/jquery/dist/jquery.min.js",
        "../node_modules/leaflet/dist/leaflet.js",
        "../node_modules/leaflet-markercluster/leaflet.markercluster.js",
        "../node_modules/leaflet-draw/dist/leaflet.draw.js",
        "../node_modules/chart.js/dist/Chart.bundle.min.js"
      ],
      "environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ]
...

In tsconfig.json:

"compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "../dist/out-tsc-e2e",
    "sourceMap": true,
    "target": "es5",
    "files":[
      "../node_modules/@types/leaflet-draw/index.d.ts"
    ],
    "typeRoots": [
      "../node_modules/@types"
    ],
    "types":[
      "jquery",
      "leaflet",
      "leaflet-draw",
      "leaflet-markercluster"
    ]
  }

Answer №1

The problem was resolved after including leaflet-draw library

import 'leaflet-draw';

I'm not sure why it wasn't automatically imported by tsconfig, but I'm happy it's now functioning correctly!

Answer №2

Shoutout to @aclokay for the valuable input. I want to emphasize the importance of also updating the standard leaflet import in order to make this answer comprehensive. Take a look at the following snippet as an example:

// import * as L from 'leaflet';  
// --> Doesn't work : Property 'Draw' does not exist on type 'typeof Control'.
declare const L: any; // --> Works
import 'leaflet-draw';

export function drawPlugin(map: any) {
  const drawnItems = L.featureGroup().addTo(map);

  const drawControl = new L.Control.Draw({
    edit: {
      featureGroup: drawnItems,
    },
    draw: {
      polygon: false,
      polyline: false,
      marker: false,
      circlemarker: false
    }
  });
  map.addControl(drawControl);

  map.on(L.Draw.Event.CREATED, function (event) {
    const layer = event.layer;

    drawnItems.addLayer(layer);
  });
}

Answer №3

It's highly recommended to include this particular library

npm install --save-dev @types/leaflet-draw

By installing this library, it resolved the issue for me and also provided specific types for the draw functionality rather than leaving everything undefined.

https://www.npmjs.com/package/@types/leaflet-draw

Answer №4

Run the following command to install Leaflet Draw types for TypeScript:

npm i --save-dev @types/leaflet-draw

Then, import the package in your project like this:

import "leaflet-draw";

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

The specified reference token grant value of [object Object] could not be located in the store

Currently, I am working with NestJs along with the oidc passport strategy using identityserver. Below is a snippet of the code: import { UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; ...

Setting up AngularJS 1.5.x to function seamlessly with SystemJS and TypeScript

I'm looking to keep all my code in AngularJS 1.x while also preparing it for an easy upgrade to AngularJS 2 in the future. To align my code with Angular 2 standards, I am interested in using TypeScript and SystemJS in version 1.5.x initially. Is ther ...

Linking a button to a (click) event within HTML content fetched from the backend

Hey there, I'm facing a scenario where I have an angular service that sends a HTTP request to the backend for some HTML code. Once the HTML is received, I'm inserting it into the component's HTML using <div [innerHTML]="..."/>. The iss ...

Having trouble triggering an alert() after a successful post to the database

As I delve into the realm of backend development, I find myself facing what seems like a simple puzzle that I just can't solve. My goal is to create a basic CRUD app to enhance my skills, so I decided to build a blog platform that could eventually be ...

Can NodeJs packages be incorporated into Angular projects?

Is it possible to use the Pluralize package in an Angular project? I'm encountering an error in VS Code that says 'Can't find module pluralize' when trying to import it. I am unsure if NodeJs packages can be used in Angular. Any help w ...

Updating the dropdown option value in Angular 10's edit component

In my Angular and ASP.NET application, I have an edit form in a component with multiple select options in a dropdown list. When displaying all data in the edit form, the dropdown list fields are displayed as empty instead of showing the previously stored v ...

Waiting for timeout to pass before proceeding in Angular 2 with Jasmine testing

I have a scenario in my code where a method is returning a part object inside a setTimeout function. The issue arises when testing this method as the test does not wait for the timeout to complete before evaluating the response. How can I ensure that the t ...

What are the benefits of precompiling my Typescript project for production instead of just running it directly with ts-node?

Many people recommend precompiling production builds. However, the reasoning behind this advice is not clear to me. What potential issues may arise from running a project in production using node --loader ts-node/esm src/server.ts ? ...

Dynamically loading Angular modules based on API response is a powerful way to enhance

Can modules be lazily loaded in Angular without a static declaration in the RoutingModule? Right now, each module is declared in the RoutingModule. { path: 'path-one', loadChildren: () => import('./components/PathOne').then(m =&g ...

The @Input default value is being replaced by `undefined` within the testing environment

Within my component, I have the following input: @Input() someThing: string = 'm'; // default value When testing, I defined it as follows: @Component({ selector: 'app-test-wrapper-component', template: ` <app-my-component so ...

Troubleshooting: JavaScript code not functioning properly with variable input instead of fixed value

I have encountered an issue with a JS function that I'm using. The function is shown below: // A simple array where we keep track of things that are filed. filed = []; function fileIt(thing) { // Dynamically call the file method of whatever ' ...

Error encountered when referencing prop on textarea: 'There is no suitable overload for this call'

I've been referring to the documentation in order to set a reference using the useRef hook, with the goal of being able to programmatically clear an input field. However, when I add ref as a prop to a textarea, it triggers a lint error saying that no ...

Exploring the power of Supabase's two-tiered joins using TypeScript

After reviewing the documentation here, I managed to successfully implement the first level join (agent_profile) but encountered issues when trying to join the next level (agent_office). Although the query returns the correct data, both VS Code and my app ...

Breaking down an array into alphabetical sections using React and Typescript

I have a large array of strings containing over 100 words. I have already sorted the array in alphabetical order, but now I need to group or split the array into a hash array called hashMap<String(Alphabet), List<String>>. This will allow me to ...

The switchMap operator in RXJS v6.4 will output an Observable instead of the final result, as indicated by the TypeScript linter

I encountered an error while running my Angular 8 app. It seems to be related to a potential bug in RxJS or maybe I am overlooking something. import { of } from 'rxjs'; import { switchMap } from 'rxjs/operators'; of(1,2,3) .pipe( ...

The latest version of Reinforced.Typings, 1.4.0, is causing build crashes when upgrading from the previous version 1

Recently, I updated my C# 4.5.1 .NET library named "ViewModels" to the newest 1.4.0 version of the Reinforced.Typings library/tool using NuGet. This tool allows me to convert my C# code to .ts files. During the upgrade process, I chose not to overwrite th ...

What is the best way to access document identifiers in a Firestore Database?

I am completely new to working with Angular, Firestore, and Firebase. Currently, I have a component set up that successfully retrieves all my hero documents. I was able to display their names in a list. However, my next goal is to retrieve the unique ID f ...

Deciphering the .vimrc setup for tooltips and symbols in TypeScript

Currently, I have integrated the Tsuquyomi plugin for my typescript development in Vim. The documentation mentions tooltips for symbols under the cursor, which are working fine. The issue arises as I am using terminal-based Vim, and even if I were using a ...

A novel way to enhance a class: a decorator that incorporates the “identify” class method, enabling the retrieval

I have been given the task to implement a class decorator that adds an "identify" class method. This method should return the class name along with the information passed in the decorator. Let me provide you with an example: typescript @identity(' ...

Incorrect type declarations in Typescript navigation.push in React Native cause unexpected behavior

Currently in my react native application, I have integrated @react-navigation/native-stack. However, the following line of code is causing an error: navigation.push('ScreenName', {myParam}); The error message reads as follows: TS2345: Argument ...