通过加载geoJSON更改标记的样式



所以我想用我的分析数据制作一个简单的html网页。我在有效的geoJSON中收集所有数据。我在HTML部分使用了这个:

<!DOCTYPE html>
<html>
<head>
<title>GeoJSON + Flask + MongoDB</title>
<meta charset="utf-8">
<link href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" rel="stylesheet"/>
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<h1>
Let's display some nice maps here!
</h1>
<div id="map" style="height: 80vh;"></div>
<script>
const map = L.map('map').setView([55.73135, 37.59104], 10);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: 'Open street map',
}).addTo(map);

axios.get('http://127.0.0.1:5000/points')
.then((response) => {
L.geoJSON(response.data, {
style(feature) {
console.log(feature);
if (feature.properties.count < 5) {
return { color: '#3cb043' };
}
if (feature.properties.count < 8) {
return { color: '#fad201' };
}
return { color: '#ff0033' };
},
}).addTo(map);
});

</script>
</body>
</html>

它显示地图上的标记,但并没有真正给它们上色。我试着把计数小于5的点变成绿色,把计数小于8的点变成黄色,把其他情况变成红色。我觉得问题出在axios.get上,但我不是一个很前端的人,所以我真的不知道出了什么问题。此外,我添加了console.log(feature),只是想看看是否调用过该函数,但它看起来不像

标记不能用默认传单库着色,只能更改图标:https://leafletjs.com/examples/custom-icons/

你可以尝试这样的库:https://github.com/lvoogdt/Leaflet.awesome-markers

所以我发现调用样式不起作用,并将其更改为pointToLayer以下是正确的标记:

<!DOCTYPE html>
<html>
<head>
<title>GeoJSON + Flask + MongoDB</title>
<meta charset="utf-8">
<link href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" rel="stylesheet"/>
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<h1>
Let's display some nice maps here!
</h1>
<div id="map" style="height: 80vh;"></div>
<script>
const map = L.map('map').setView([55.73135, 37.59104], 10);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: 'Open street map',
}).addTo(map);
var greenMarkerOptions = {
radius: 8,
fillColor: "#3cb043",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
};
var yellowMarkerOptions = {
radius: 8,
fillColor: "#fad201",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
};
var redMarkerOptions = {
radius: 8,
fillColor: "#ff0033",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
};

axios.get('http://127.0.0.1:5000/points')
.then((response) => {
L.geoJSON(response.data, {
pointToLayer: function (feature, latlng) {
if (feature.properties.count < 3) {
return L.circleMarker(latlng, greenMarkerOptions);
}
else if (feature.properties.count < 6) {
return L.circleMarker(latlng, yellowMarkerOptions);
}
return L.circleMarker(latlng, redMarkerOptions);
},
}).addTo(map);
});

</script>
</body>
</html>

最新更新