我需要一些帮助来设置图标向量在我的地图。我的意思是当地图加载时它会显示不同的图标这取决于属性和车站。GeoJson。使用"for"我得到了车站名称和设置变量来存储获取图标的路径。在控制台上,它显示了正确的路径,但当我尝试使用它openlayerIcon作为src时,它采用最后一个变量。
let startDatajson = (new ol.format.GeoJSON({
dataProjection : 'EPSG:4326',
featureProjection: 'EPSG:3857',
})).readFeatures(startJson);
let stationStartSource = new ol.source.Vector({
features: startDatajson
});
var onLoadSrc;
var getLoadStation = startDatajson.length;
for(i=0;i<getLoadStation;i++){
var getStation = startDatajson[i].get("Station");
if(getStation == "NNAA"){
onLoadSrc="assets/img/alert-smaller.png";
}else{
onLoadSrc="assets/img/blue-triangle.png";
}
/* switch(getStation){
case "NNAA": onLoadSrc="assets/img/alert-smaller.png";
break;
case "LIM027": onLoadSrc="assets/img/blue-triangle.png";
break;
} */
console.log(getStation);
console.log(onLoadSrc);
}
/* creating image as style */
var startIconStyle = new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5,0.5],
size: [28,19],
offset: [1,1],
scale: 1,
src: onLoadSrc,
})
});
/* creating vector and adding image on style created before */
startStationsLayer = new ol.layer.Vector({
source: stationStartSource,
visible:true,
title:"ultimasEstaciones",
style: startIconStyle,
});
map.addLayer(startStationsLayer);
在浏览器
如果你有比可能的图标更多的功能,你应该设置一个图标样式缓存,并使用一个样式函数来返回适合你的功能名称的样式。
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.6.1/css/ol.css" type="text/css">
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.6.1/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script type="text/javascript">
const styles = {};
for (let i = "A".charCodeAt(); i <= "Z".charCodeAt(); i++) {
const char = String.fromCharCode(i);
styles[char] = new ol.style.Style({
image: new ol.style.Icon({
src: "https://maps.google.com/mapfiles/kml/paddle/" + char + ".png",
anchor: [0.5, 1]
})
});
}
const vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: "https://openlayers.org/en/latest/examples/data/geojson/world-cities.geojson",
format: new ol.format.GeoJSON()
}),
style: function (feature) {
return styles[feature.get("accentcity").charAt(0)];
}
});
const map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
],
target: document.getElementById("map"),
view: new ol.View({
center: ol.proj.fromLonLat([0, 52.25]),
zoom: 9
})
});
</script>
</body>
</html>