[英]How can I serialize all features on a layer to json using openlayers 3
[英]Using OpenLayers, how can I display different icons for different features on a single layer?
首先,我是 Openlayers/JS 的新手,總體上對編程缺乏經驗,因此我的代碼可能存在我不知道的其他問題。
我使用的是最新版本的 Openlayers (5.3.0)。
我的程序目前通過 Ajax 傳遞 GeoJson 格式的數據以顯示在 Openlayers 地圖上。 它為要顯示的要素創建地圖、視圖和圖層。 當我按下頁面上的“開始”按鈕時,要素已成功加載到地圖上。 在我的情況下,這些特征只是使用 png 標記進行可視化的帶有緯度/經度的簡單點。 在被序列化並發送到我頁面上的 JS 進行反序列化之前,GeoJson 在 C# 中看起來像這樣:
{{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-1.549077,
53.800755
]
},
"properties": {
"GPSKey": 1,
"Latitude": 53.800755,
"Longitude": -1.549077,
"TimeAdded": "2019-01-15T12:10:16",
"IconPath": "pinred.png"
},
"ID": 1,
"IconPath": null
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-1.545077,
53.800755
]
},
"properties": {
"GPSKey": 2,
"Latitude": 53.800755,
"Longitude": -1.545077,
"TimeAdded": "2019-01-15T12:10:16",
"IconPath": "pinred.png"
},
"ID": 2,
"IconPath": null
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-1.524043,
53.773222
]
},
"properties": {
"GPSKey": 3,
"Latitude": 53.773222,
"Longitude": -1.524043,
"TimeAdded": "2019-01-15T12:10:16",
"IconPath": ""
},
"ID": 3,
"IconPath": null
}
]
}}
JS接收到上面序列化后,使用這段代碼添加到圖層中查看:
var geojsonFormat = new ol.format.GeoJSON({
dataProjection: "EPSG:4326",
featureProjection: "EPSG:3857"
});//creates a format definition
jsonDecoded = JSON.parse(result); /
if (jsonDecoded.features.length > 0) {
for (var i = 0; i < jsonDecoded.features.length; i++) {
vectorSource.addFeature(geojsonFormat.readFeature(jsonDecoded.features[i], { featureProjection: "EPSG:3857" }));
}
}/
它添加到的矢量圖層如下所示:
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: iconStyleFunc()
});
iconStyleFunc() 看起來像這樣:
function iconStyleFunc() {
var zIndex = 1;
var iconName = null;
if (iconName == null) {
iconName = "pinother.png"
};
iconStyle = [new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 36],
anchorXUnits: "fraction",
anchorYUnits: "pixels",
opacity: 1,
src: "images/" + iconName,
zIndex: zIndex
})),
zIndex: zIndex
})];
return iconStyle;
這適用於使用圖標“pinother.png”設置所有功能的樣式。 當我按下按鈕時,我在地圖上顯示點沒有問題。
我想要做的是根據每個特征的 GeoJson“iconpath”屬性中的圖標路徑應用樣式,這樣任何具有“pinred.png”的特征都會使用它而不是默認的“pinother.png”,等等,還有我將來可能需要添加的各種圖標。
我不確定如何讀取每個功能的這個屬性,以及如何最好地在樣式函數中實現它。 我設想的方式是使用 iconStyleFunc() 遍歷功能,讀取每個功能的 IconPath 屬性,將該值附加到 iconStyleFunc() 中的“src/images/”路徑並適當地設置功能樣式。
使用樣式函數的特征參數,您可以獲得特征的屬性
function iconStyleFunc(feature) {
var zIndex = 1;
var iconName = feature.get("IconPath") || "pinother.png";
iconStyle = [new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 36],
anchorXUnits: "fraction",
anchorYUnits: "pixels",
opacity: 1,
src: "images/" + iconName,
zIndex: zIndex
})),
zIndex: zIndex
})];
return iconStyle;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.