Being new to Openlayers/JS and fairly inexperienced with programming in general, there may be other issues in my code that I'm unaware of.
I am currently using the latest version of Openlayers (5.3.0).
My application sends GeoJson formatted data via Ajax for display on an Openlayers map. It initializes the map, view, and a layer for the features to be shown. Upon clicking a "Go" button on the page, the features are successfully loaded onto the map. In this scenario, the features consist of simple points with latitude/longitude coordinates marked by a png image. The GeoJson format in C# before being serialized and sent to JS is as follows:
{{
"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
},
...
]
}}
The JavaScript receives the serialized data and incorporates it into the layer as shown here:
var geojsonFormat = new ol.format.GeoJSON({
dataProjection: "EPSG:4326",
featureProjection: "EPSG:3857"
});
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" }));
}
}
The vector layer where the features are added is defined by:
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: iconStyleFunc()
});
The function `iconStyleFunc()` manages the styling for the icons as depicted below:
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;
}
Currently, all features are styled with the default icon "pinother.png". However, I aim to customize the styling based on the icon path specified in the GeoJson properties of each feature. For instance, any feature with an "IconPath" of "pinred.png" should use that specific icon. I'm uncertain about how to access this property for each feature and implement it within the styling function. My approach involves iterating through features using `iconStyleFunc()`, extracting the value of the IconPath property, appending it to the "src/images/" path in the iconStyleFunc(), and customizing the feature accordingly.