leaflet-markers-canvas
leaflet-markers-canvas copied to clipboard
Typescript
not entirely sure how to use this in typescript when importing stuff from leaflet like this
import {
Map, Layer, MapOptions, TileLayer, CRS, tileLayer,
TileLayerOptions, LeafletMouseEvent, LeafletEvent, Canvas, canvas, circleMarker
} from 'leaflet';
i tried:
import {markersCanvas} from 'leaflet-markers-canvas';
import * as L from 'leaflet-markers-canvas';
import 'leaflet-markers-canvas';
import * as L from 'leaflet';
would be good to make this properly for typescript
you can ofc do this, but this is like a giant mess
import 'leaflet-markers-canvas';
// @ts-ignore
import { MarkersCanvas } from 'leaflet';
and even in that case im getting:
ERROR TypeError: n is undefined
_addMarker leaflet-markers-canvas.min.js:1
addMarkers leaflet-markers-canvas.min.js:1
addMarkers leaflet-markers-canvas.min.js:1
Hi, I use this plugin with TS in our current project. I know, this is kind of a workaround but you can work with it until somebody implements a TS-style way to import the plugin.
First I wrote a little declaration file for the plugin: projectpath/@types/leaflet-markers-canvas/index.d.ts
import 'leaflet';
declare module 'leaflet' {
export class MarkersCanvas extends Layer {
addTo(map:Map|LayerGroup):this;
addMarker(marker:Marker):void;
addMarkers(markers:Array<Marker>):void;
getBounds():LatLngBounds;
redraw():void;
clear():void;
removeMarker(marker:Marker):void;
}
function markersCanvas(): MarkersCanvas;
}
If you haven't created a local @types directory before you need to add it to your tsconfig.json:
{
"compilerOptions": {
......
"typeRoots": [ "./projectpath/@types", "./node_modules/@types"]
},
.....
"exclude": [ "./projectpath/@types", "./node_modules/@types"]
}
Now, in your main source code, you can "import" the plugin like so (half pseudo code):
import * as L from "leaflet";
require("../libs/canvas-element-layer");
class NewMap {
private _map: L.Map;
private _markersCanvas: L.MarkersCanvas;
constructor(map: L.Map) {
this._map = map;
this._markersCanvas = new L.MarkersCanvas();
// you can also use: this._markersCanvas = L.markersCanvas();
this._markersCanvas.addTo(this._map);
}
}
I hope this helps :-)
Another thing you can do is:
And then:
import MarkersCanvas from 'path/where/is/the/library/leaflet-markers-canvas.js)';
var markersCanvas = new MarkersCanvas();
markersCanvas.addTo(map);
//Create your marker
var marker = L.marker(
[58.5578 + Math.random() * 1.8, 29.0087 + Math.random() * 3.6],
{ icon }
);
//Add your marker to the MarkersCanvas
markersCanvas.addMarker(marker)