Search code examples
javascriptangulartypescriptleafletgeojson

Error when creating a new instance of L.control() using Leaflet & Angular 6


I follow this tutorial : https://leafletjs.com/examples/choropleth/

I try to make a custom control when i mouseover my Geojson on map.

But i have an error on "info = L.control();"

Cannot invoke an expression whose type lacks a call signature. Type 'type of control' has no compatible call signatures.

Someone can translate me ? thanks fo your help.

var mapboxAccessToken = "key";

const myfrugalmap = L.map('frugalmap').setView([47.482019, -2], 7.5);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=' + mapboxAccessToken, {
    id: 'mapbox.light',
    attribution: 'SOS'
}).addTo(myfrugalmap); 

    this.http.get('assets/departements.json').subscribe((json: any) => {
      console.log(json);
      this.json = json;

var geojson;

geojson =  L.geoJSON(this.json, {
    style: function(feature) {
        switch (feature.properties.code) {
            case '44': return {color: "white",fillColor:"red", fillOpacity: 0.1};
            case '53':   return {color: "white",fillColor: "yellow", fillOpacity: 0.1};
            case '72':   return {color: "white",fillColor: "orange", fillOpacity: 0.1};
            case '85':   return {color: "white",fillColor: "green", fillOpacity: 0.1};
            case '49':   return {color: "white",fillColor: "blue", fillOpacity: 0.1};

        }
    },

    onEachFeature: function onEachFeature(feature, layer) {
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight,
        click: zoomToFeature
    });
}

} ).addTo(myfrugalmap);

function highlightFeature(e) {
    var layer = e.target;

    layer.setStyle({
        weight: 5,
        color: '#666',
        dashArray: '',
        fillOpacity: 0.2
    });

    if (!L.Browser.ie &&  !L.Browser.edge) {
        layer.bringToFront();
    }

info.update(layer.feature.properties);    
}


function resetHighlight(e) {
    geojson.resetStyle(e.target);
    info.update();
}


function zoomToFeature(e) {
    myfrugalmap.fitBounds(e.target.getBounds());
}

var info;

info = L.control();

info.onAdd = function (myfrugalmap) {
    this._div = L.DomUtil.create('div', 'info'); 
    this.update();
    return this._div;
};


info.update = function (props) {
    this._div.innerHTML = '<h4>Pays de la Loire</h4>' +  (props ?   '<b>' + props.nom + '</b><br />'
        : '');
};

info.addTo(myfrugalmap);

    });

Solution

  • In order to avoid getting this error you need to initialize control like this: new L.Control()

    Furthermore some parts of your code do not make sense as for instance you supposed to have a global json variable but there is not anyone as you use it as this.json afterwards. instead you have a geojson variable .

    Also there is no constructor for injecting http to make a get request. I prepared a working example for what you are trying to achieve: Demo