javascript - Error al crear una nueva instancia de L.control() usando Leaflet y Angular 6
Sigo este tutorial: https://leafletjs.com/examples/choropleth/
Intento crear un control personalizado cuando paso el cursor sobre mi Geojson en el mapa.
Pero tengo un error en "info=L.control();"
No se puede invocar una expresión cuyo tipo carece de una firma de llamada. El tipo 'type of control' no tiene firmas de llamada compatibles.
¿Alguien puede traducirme? Gracias por tu ayuda.
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);
});
Respuesta #1
Para evitar obtener este error, necesitas inicializar el control así: new L.Control()
Además, algunas partes de tu código no tienen sentido, por ejemplo, se supone que debes tener una variable global json, pero no hay ninguna ya que la usas como this.json después. En su lugar, tienes una variable geojson.
Además, no hay un constructor para inyectar http y hacer una solicitud GET. Preparé un ejemplo funcional de lo que estás intentando lograr: Demo