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

jQuery does not pass data to bootstrap modal

I am currently working with the full calendar feature. Within this framework, I have implemented a modal that allows users to insert new events: <div id="fullCalModal_add_appointment" class="modal fade"> <div class="modal-dialog"> ...

Issue with reflect metadata in Next.js edge runtime causing functional problems

Currently, I am utilizing a package in my upcoming 13 app that incorporates reflect metadata. Unfortunately, during the next build process, an error occurs for which I haven't been able to find a solution. ../../eshop-sdk-js/node_modules/reflect-metad ...

Combining both AJAX variables and HTML classes

Having trouble combining two AJAX variables with JQuery and PHP to add to a MySQL database... Here is the code snippet: $.ajax({ url: DIR+"some.php", method: "POST", dataType: "JSON", data: { mobile: mobile.val(), d ...

Activate or deactivate a text box within a table based on the checkbox's status

I am seeking assistance with jQuery to enable or disable a textbox within a table when a checkbox is checked. Below is the code snippet from my edit.cshtml file. <table id="scDetails" class="dataTable"> <thead> & ...

PhoneGap iOS application storing outdated information

My Phonegap 2.1 app running on iOS 6, with jQuery 1.7.2 and JQMobile 1.1.1 libraries, is experiencing an issue where old data from ajax responses gets cached if the app is unused for a few days. The only way to resolve this issue is by reinstalling the a ...

Ways to make a jsonp request without including the 'callback' in the URL

I've been working on retrieving information from an Icecast Radio station using their API, which offers the status-json.xsl endpoint to access this data. Despite the format being in xsl, I suspect it returns a JSON file. However, I've encountere ...

Eliminate the ArrayOfObjects by filtering out the items with a specific ID

Here is an array of objects I've named mycart[]: [{"id":"6","quantity":"20","price":1500,"title":"casual blue strip"}, {"id":"10","quantity":"2","price":1500,"title":"casual blue round neck"},{"id":"5","quantity":20,"price":150,"title":"casual ...

Python baseHTTPserver encountering CORS error code 501 (Unsupported method 'OPTIONS') while running in Google Chrome

Hello, I need assistance with base authentication while making an AJAX get/post request to a Python BaseHTTPServer. I managed to modify some lines of code in the Python script to send CORS headers. It works perfectly in modern browsers when I disable HTTP ...

Tips for automatically setting focus to the following cell after inserting a new row in AngularJS

Transitioning from the Knockout world to Angular, I am facing an issue with a key-press event for tab. Whenever I add a new row in the table, the focus shifts to the information icon in the URI bar instead of the next cell in the newly created row. I belie ...

Ensure the CSS class stays on Quill clipboard.dangerouslyPasteHTML

One of the challenges I face with using the Quill Text Editor is that when I use the method clipboard.dangerouslyPasteHTML to paste HTML into the editor, it does not maintain custom CSS classes. For example: let content= '<p class="perso-clas ...

Is there a way to successfully submit multiple locations, each separated by commas, through the multipart form?

Here is my HTML form: <form method="POST" enctype="multipart/form-data" v-on:submit.prevent="handelSubmit($event);"> <div class="clear"> <div class="col-md-3"></div> <div class="col-md-6"> <div class="form ...

Implementing automatic selection mode in Kendo MVC grid

Seeking to modify the SelectionMode of a Kendo MVC Grid, I aim to switch from single to multiple using Javascript or JQuery upon checkbox selection, and revert back when the checkbox is unchecked. Is this feasible? Additionally, I am successfully binding a ...

The public folder in Node.js is known for its tendency to encounter errors

I'm facing an issue with displaying an icon on my website. Here is the current setup in my code: app.js const http = require('http'); const fs = require('fs'); const express = require('express') const path = require(&apo ...

Preventing Event Loop Blocking in Node.js: The Key to Streamlining Performance

I am currently working on developing two APIs using Express.js. The tasks for both APIs are quite straightforward. The first API involves running a for loop from 1 to 3,000,000, while the second API simply prints a string in the console. All the necessary ...

The getElementByID function will return null in this instance, as it has not been loaded

Hello everyone, I am facing an issue while trying to access an element by its ID in JavaScript as it keeps returning null. This problem arises because the element is not fully loaded when the DOM is initially created, due to a plugin called Restrict Conte ...

Implementing Laravel's functionality for calculating average ratings with the help of jQuery

In my database, I have two tables named Users and ratings. The Users can give ratings to consultants, and the Ratings table structure is as follows: User_id | consultant_id | rating --------------------------------- 1 1 2 ...

Enhance your figures with a unique Javascript magnifying tool that works seamlessly across all browsers

After searching the web for magnifying glasses, I found that most only work for one picture. So, I took matters into my own hands and created a magnifying glass that can magnify all pictures within a specific div. It functions perfectly on Chrome browser b ...

Verify if the specified value is present in the dropdown using AngularJS

Utilizing AngularJS, I have implemented an input field with autocomplete functionality. The autocomplete feature pulls data from a JSON file and displays it in a dropdown table format. Users are able to filter the results and select a value from the dropdo ...

An SQL query that functions flawlessly in STUDIO 3T, yet fails to execute in Express.js

I encountered a puzzling situation where a query that functions perfectly in STUDIO 3t fails to retrieve any data in express js. Below is the code comparison: STUDIO 3t Query: db.getCollection("tickets").find({ $and: [ {"TCKT_CRTE_DTTM" : { ...

How to eliminate the initial class with jQuery

I am encountering some issues with removing a class using jQuery. When I open a modal in Bootstrap, it generates code like this: <div class="modal-backdrop fade in"> in the footer. However, when I open a modal within another modal (2 modals), ther ...