【发布时间】:2021-08-29 00:12:10
【问题描述】:
我正在使用带有 Angular 11 的 Leaflet 1.7.1。我有下一个代码:
渲染组件的 html 如下所示:
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.1/leaflet.css">
<div id="map" style="height: 100vh;"></div>
这是组件本身:
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
constructor(private http: HttpClient) {}
map: L.Map;
geojson: L.GeoJSON;
ngOnInit() {
this.map = L.map('map').setView([37.8, -96], 4);
L.tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution: "ATTRIBUTION",
tileSize: 512,
zoomOffset: -1
}).addTo(this.map);
this.geojson = L.geoJSON(statesData, {style: style, onEachFeature:
onEachFeature}).addTo(this.map);
}
}
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight,
click: zoomToFeature
});
}
function resetHighlight(e) {
this.geojson.resetStyle(e.target);
}
function zoomToFeature(e) {
this.map.fitBounds(e.target.getBounds());
}
function highlightFeature(e) {
const layer = e.target;
layer.setStyle({
weight: 5,
color: "#666",
dashArray: "",
fillOpacity: 0.2
});
if (!L.Browser.ie && !L.Browser.edge) {
layer.bringToFront();
}
}
function style(feature) {
return {
fillColor: getColor(feature.properties.density),
weight: 2,
opacity: 1,
color: 'white',
dashArray: '3',
fillOpacity: 0.7
};
}
function getColor(d) {
return d > 1000 ? '#800026' :
d > 500 ? '#BD0026' :
d > 200 ? '#E31A1C' :
d > 100 ? '#FC4E2A' :
d > 50 ? '#FD8D3C' :
d > 20 ? '#FEB24C' :
d > 10 ? '#FED976' :
'#FFEDA0';
}
所以问题在于,无论我在 onEachFeature 方法中使用什么来处理层上的事件,例如
layer.on({
click: layer.setStyle({fillColor: 'red'}),
mouseover: layer.setStyle({fillColor: 'blue'}),
mouseout: layer.setStyle({fillColor: 'green'})
});
所有图层都将填充颜色绿色
如果我使用这个:
layer.on('click', function(e) {
layer.setStyle({fillColor: 'red'})
});
不会触发任何点击事件,即不会发生任何事情。
我尝试将代码放在不同的 Angular 生命周期方法 ngOnInit()、ngAfterViewInit() 中,发生了相同的行为。
PC:我将商业代码替换为来自官方 Leaflet 网站的代码:https://leafletjs.com/examples/choropleth/
**我看到了几个类似的问题,但是,或者他们没有得到回答,或者他们没有考虑 Angular 版本 11 中的 Leaflet。
【问题讨论】:
标签: javascript angular leaflet