Is there a way to utilize OpenLayers to showcase various icons for distinct features all within one layer?

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.

Answer №1

By utilizing the feature argument within the style function, you can access properties of the feature

function customizeIconStyle(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;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send the Children prop to the React Memo component

Currently, I am in the stage of enhancing a set of React SFC components by utilizing React.memo. The majority of these components have children and the project incorporates TypeScript. I had a notion that memo components do not support children when I en ...

Pass the returned variable value from a request.get call to another function in NodeJS Express

I have a situation where I am calling a function that makes a request to get some JSON data and then fills in the variables from my router.get method. The issue I am facing is that the variables are getting their value inside the callFunc function, but wh ...

Is there a way to determine when an HTML video has finished playing?

I'm working on a webpage that features multiple videos. I want to capture a specific value from an input field and display it once a video finishes playing. Below is my current setup: HTML <input type='text' name='profileUsernam ...

The external javascript file is unable to recognize the HTML table rows that are dynamically inserted through an AJAX request

I have a situation where I'm pulling data from an SQL database and integrating it into my existing HTML table row. Here's the code snippet: Using Ajax to fetch data upon clicking analyze_submit: $(document).ready(function(e) { $('#anal ...

Updating the key within an array of objects

In my array of objects, I have the following data: arrayOfObject = [{'key1': [1,2]} , {'key2': [1,2,3]} , {'key3': [1,2,4]}] I know the name of the key that I want to replace in my array : var keyString = 'key1&apos ...

Encountering special symbols in the ID of a form element triggers an error message in jQuery validator, stating 'Unrecognized expression'

One of the challenges I am facing is that I have a form with elements that have ids containing special symbols. For example: The id="$FormData[1]$PersonData[1]$PhysicalPerson[1]$PersonName[1]$Affix[@type='qualification' and @position='prefi ...

One the year is chosen, it will be automatically hidden and no longer available for selection

<div ng-repeat="localcost in vm.project.localCosts" layout="column"> <md-select name="localcost_{{$index}}"ng-model="localcost.year" flex> <md-option ng-repeat="years in vm.getYears()" ng-value="years">{{years}}< ...

JavaScript Recursive Function for Generating FancyTree JSON Structure

I'm currently building an array of JSON objects for FancyTree (https://github.com/mar10/fancytree/wiki/TutorialLoadData). My JSON source is from the Jira REST service, and its structure can vary widely. Therefore, the code to construct the array of JS ...

Combining numerous objects into one object within an array, each with distinct keys, and displaying them using FlatList

I'm struggling to present this information in a FlatList. Array [ Object { "-N1gqvHXUi2LLGdtIumv": Object { "Message": "Aeaaeaea", "Message_CreatedAt": 1652167522975, "Message_by_Ema ...

The height of the container is not adjusted correctly after loading data via ajax which causes it to overlap with

My HTML code consists of a container with two columns (content and sidebar) and a footer. The content contains a horizontal list with li elements that are populated via ajax when the "Load More" button is pressed. I am using Bootstrap and testing on Chrome ...

Creating a Vue.js component that animates text to fade in and out within a textarea when a button

I need assistance with updating a <textarea> element in my Vue application. Currently, I have the textarea bound to some data in my state. However, when a button is clicked, I want the existing data in the textarea to fade out and be replaced with ne ...

The equivalent of the $.curCSS method in jQuery version 1.10 is as follows:

While working with a library called mcdropdown from http://www.givainc.com/labs/, I encountered an issue with the $.curCSS method. The latest version of jQuery no longer supports this method and suggests using $().css instead. Following the documentation, ...

How can I use AJAX to transmit a 2D array to a PHP page and then display each dimension individually?

Recently, I created a webpage with multiple checkboxes. Using jQuery, I am able to fetch data from these checkboxes and store them in a two-dimensional array. Here is an excerpt of my code: HTML snippet: <input type="checkbox" name="checkboxs[]" pric ...

What is the best way to retrieve data attributes from multiple div elements that share the same class name?

I have multiple div elements with the same class name. I want to extract the data attribute from these div's. I have tried some code and managed to get the result. However, I am unsure if this is the best approach for retrieving data("cartid"). Any as ...

ReactJS: An error occurred - TypeError: this.state.items.map is not a function

As a beginner in ReactJS, I am working on my first project which is a To-Do List with drag and drop feature, add, delete, and edit functionalities. I encountered an error while trying to map an array upon submitting a text to add an item to the items array ...

Consecutive AJAX requests triggered by previous response

While there are numerous resources available regarding making synchronous AJAX calls using deferred promises, my specific issue presents a unique challenge. The process I am attempting to facilitate is as follows: Initiate an AJAX call. If the response i ...

Insufficient Resources Error (net::ERR_INSUFFICIENT_RESOURCES) encountered while executing jQuery script with multiple ajax requests for 2 minutes

Upon initially loading the code below, everything seems to be functioning smoothly with the dayofweek and hourofday functions. However, shortly thereafter, the browser (Chrome) freezes up and displays the error message: net::ERR_INSUFFICIENT_RESOURCES. Thi ...

Pass data between JavaScript and PHP using the Phaser framework

I am trying to pass a JavaScript variable to PHP and then store it in a database. Despite searching for solutions on Google, I have not been successful. Most suggestions involve using AJAX, but the code doesn't seem to work when I try it. I attempted ...

Adding the output of a UNIX command to a div container

I am currently working on creating a UNIX web-based terminal for educational purposes. My progress so far includes setting up a text box and displaying the output, similar to this: <?php $output = shell_exec('ls'); echo "<pre>$output< ...

When attempting to bind various data to a single div using knockout js, the issue of duplicate records appearing arises

I am encountering an issue with a div that is set up to display 10 records at a time. When the user clicks on the next link, the next set of 10 records should be loaded from the server. However, after binding the newly added records, they are being shown m ...