Search code examples
angulartypescriptngx-leaflet

How to use colorFilter with ngx-leaflet on Angular6


How can i use a Leaflet plugin like Leaflet.TileLayer.ColorFilter with ngx-leaflet on Angular 6 ?

I think my problem is in the import of the project because i want to use a function created by the ColorFilter plugin but this plugin is not a part of the Type Definition ( index.d.ts ) of ngx-leaflet. Am i right ? If yes, how can i fix it ? Is there a way to contribute a Type definition in the ColorFilter to be plug&play in the future and help other people like me ? Do you have some docs ?

Here is my actual fail :

app.module.ts

Here i import ngx-leaflet

imports: [
    ...
    LeafletModule.forRoot()
],

.angular-cli.json

Here i import directly the JS file since i don't have a module in the ColorFilter plugin

"scripts": [
    "../node_modules/leaflet.tilelayer.colorfilter/src/leaflet-tilelayer-colorfilter.min.js"
],

my.component.ts

import {circle, icon, latLng, marker, polygon, tileLayer} from 'leaflet';

...

ngOnInit() {
    const myFilter = [
      'grayscale:100%',
      'invert:100%',
    ];

    this.options = {
      layers: [
        tileLayer.colorFilter(
          'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
          { maxZoom: 18, attribution: '...' },
          myFilter
        )
      ],
      zoom: 5,
      center: latLng(46.879966, -121.726909)
};

Error

error TS2339: Property 'colorFilter' does not exist on type 'typeof tileLayer'.


Solution

  • In order to make lealfet.tilelayer.colorfilter plugin to work on ngx-leaflet you need to import it directly on component.ts as for some reason it is not possible via angular.json - Webpack does not seem to bundle the file allowing it to modify L namespace (it did not work in my case) and then although you should be able to call L.tileLayer.colorFilter directly in your component in my case it worked only using (L.tileLayer as any).colorFilter.

    import * as L from 'leaflet';
    
    import "node_modules/leaflet.tilelayer.colorfilter/src/leaflet-tilelayer-colorfilter.js"
    
    ...
    
    defaultToDarkFilter = [
        'grayscale: 100%',
        'invert: 100%',
    ];
    
    options = {
        layers: [
            (L.tileLayer as any).colorFilter('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { 
                maxZoom: 18, 
                attribution: '...' , 
                filter: this.defaultToDarkFilter
            }),
        ],
        zoom: 3,
        center: L.latLng(46.879966, -121.726909)
    };
    

    Demo