Set Openlayers to display all features at the exact same scale as the background layer

Incorporating OpenLayers into Angular2, I successfully displayed a custom SVG-image as a background map. The zoom and scroll functionalities work flawlessly across the map.

However, upon implementing Features (also SVG) and placing them in a separate Vector-Layer above the map, I encountered an issue where the features resize strangely when zooming.

While zooming out, the Features enlarge, and while zooming in, they shrink. I desire for them to maintain a consistent size, so that they decrease in size when zooming out (similar to static content on the map).

I attempted using an additional style-function and experimented with recalculating the scale of the feature's current style. Unfortunately, I was unsuccessful in resolving this issue.

Therefore, my query is: How can I overlay another Layer with Features above an existing layer and ensure that everything shrinks in size when zooming out?

Am I making an error somewhere? Do I require Projections for this? As someone relatively new to OpenLayers, any guidance would be appreciated.

Thank you in advance!

Here is a minimal code example: The SVG-Points increase in size continuously when zooming out (similar issue to the one demonstrated in the following official OpenLayers code example: Official Code Example: When Zooming out, the marker becomes as large as a whole country or continent....

let center = ol.proj.transform([8.30368, 47.05243], 'EPSG:4326', 'EPSG:3857');
let style = new ol.style.Style({
        image: new ol.style.Icon({
            anchor: [0, 0],
            anchorXUnits: 'pixels',
            anchorYUnits: 'pixels',
            src: '/assets/images/test.svg',
            imgSize: [50, 50],
            size: [50, 50],
            scale: 1.0
        })
    });

    let iconFeature = new ol.Feature({
        geometry: new ol.geom.Point(center)
    });

    iconFeature.setStyle((resolution) => {
        return [iconStyle];
    });

    this.featureArray.push(iconFeature);

    let vectorSource = new ol.source.Vector({
        features: this.featureArray
    });
    let extent = [0, 0, 1024, 968];
    let projection = new ol.proj.Projection({
        code: 'xkcd-image',
        units: 'pixels',
        extent: extent
    });

    // load vector layer for dynamic elements
    let vectorLayer = new ol.layer.Vector({
        source: vectorSource,
        projection: projection,
        imageExtent: extent
    });

    this.layerArray.push(vectorLayer);

    // basic setup
    this.map = new ol.Map({
        renderer: 'canvas',
        layers: this.layerArray,
        view: new ol.View({
            center: center,
            zoom: 16,
            minZoom: 1,
            maxZoom: 26,
        })
    });

Answer №1

Are you looking for something similar to this example on CodePen?

To achieve this, you would need a style function where you adjust the size of the icon based on the resolution:

function(feature, resolution) {
  style.getImage().setScale(16000 / resolution);
}

The value 16000 represents the resolution at which the icon should be displayed at its original size.

It's also important to set the ol.layer.Vector instance with

updateWhileAnimating: true,
updateWhileInteracting: true

This ensures that the icon size is dynamically updated whenever there is a change in resolution.

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

The IMDB API is throwing a GraphQL error that says, "ClientError: Unable to retrieve information on the field 'Image' for the type 'MainSearchEntity'."

Seeking suggestions for the top 10 movies related to 'Africa' using the IMDB API demo available here. In my query, I am looking for movie id, title, poster image, and filming location. However, I encounter an error message 'ClientError: Ca ...

I need to incorporate specialized error management into Ionic 4

One of my tasks is to develop a service that can handle and log any run-time errors that occur in the application. To accomplish this, I have created a service called "ErrorHandlingService" and implemented the following code: import { ErrorHandler } fro ...

How can I incorporate an error page into this Express application?

I'm currently working on an express application that simulates a basic version of Twitter. One feature I'm trying to implement is an error page. This way, if there are any issues with the routing, users will see a friendly message instead of a g ...

"Mongoose Nodejs is throwing an error as it is unable to retrieve the property 'id' from an undefined

I'm currently attempting to retrieve and delete an object from MongoDB, but I keep encountering the following error. Cannot read property 'id' of undefined My goal is to fetch an object by its ID. The ID is crucial in my Schema as I am e ...

How exactly does document.write function in JavaScript?

Currently, I am delving into JavaScript through W3Schools and have encountered a statement that says "If you execute document.write after the document has finished loading, the entire HTML page will be overwritten." From the examples provided, I have notic ...

Notification triggered in GridView editing according to authorization levels

I have a formview displaying data with an option to edit each row. There are different user roles in my system such as Admin, SuperUser, and User. If a non-Admin user tries to edit a row, I want to display a warning message. Currently, the JavaScript funct ...

Creating a React Mui TextField specifically for currency input on iPhone Safari: ensuring that only digits are allowed

I have implemented a Mui TextField component for currency input that displays only the numeric keyboard in the Safari browser. However, I want to restrict users from pasting literal strings into the field and ensure that only currency number inputs are al ...

Error: Authorization requires both data and salt arguments

As a novice in NodeJS, I attempted to create an authentication form using NodeJS + express. The issue I am facing is regarding password validation - specifically, when "confirmpassword" does not match "password", it should return nothing. Despite my effo ...

JavaScript random number functionality experiencing an unexpected problem

function generateRandomNumbers(){ var max = document.getElementById('max').value; var min = document.getElementById('min').value; var reps = document.getElementById('reps').value; var i; for (i=0; i<reps ...

What is the best way to transfer a user-generated PNG file to my backend server?

I'm in the process of developing a website that enables users to generate personalized graphics and easily download them directly from the platform. My approach involves allowing users to customize an svg using a javascript-powered form, which is the ...

There was an issue trying to access the 'img' property of an undefined value in JSON data

I have successfully generated a JSON file containing data. Through the use of a provider in Ionic 3, I have managed to fetch the data. Below is the content of the JSON file [ { "teachers": { "img":"assets/home/img.png" } ...

Creating a dynamic Bootstrap carousel with a fixed hero header text inside a designated container - here's how!

I am currently working on a project to develop a responsive Bootstrap slider with a fixed hero header that remains consistent while the slider images change. The hero header needs to be aligned to the left within a responsive Bootstrap container and center ...

Syntax of the Vue.js application object model

Just delving into the world of vue.js and stumbled upon this code snippet. Curious to know more about its structure. const CounterApp = { data() { return { counter: 0 } }, mounted() { setInterval(() => { this.counter++ ...

Angular: The type AbstractControl<any> cannot be assigned to type FormControl

I am working with a child component that includes an input tag <input [formControl]="control"> component.ts file @Input() control: FormControl; In the parent component, I am using it as follows: <app-input [control]="f['email ...

Tips for sharing JSON data between JavaScript files

Here is the initial script setup to utilize static .json files for displaying and animating specific content. The code provided is as follows: var self = this; $.getJSON('data/post_'+ index +'.json', function(d){ self.postCa ...

Guide to using the PUT method in Node.js Express to update a record using the primary key

I'm currently struggling with understanding the proper usage of the put statement in node js. Here is the code I have been using: app.put("/cars/:id", (req, res) => { //retrieving a record based on id (uuid) e.g. http://localhost:3000/cars/a5ad957 ...

Recognizing JavaScript in Intellij IDEA within a script tag that does not specify the type as "text/javascript"

Using the MathJax javascript library has presented a challenge for me. Whenever I make changes to the MathJax configuration, I encounter issues because it is written in javascript but its type is labeled as "text/x-mathjax-config". This causes Intellij Ide ...

jQuery carousel displaying a blank slide at the conclusion

I am experiencing an issue with my slideshow where it shows an empty slide after the last element. I suspect that there is something in my script causing this behavior, as it seems to be finding one extra child for the element and adding it as an empty spa ...

Encountering an issue during the user login or registration process

Issue: I've been facing a challenge with storing user signup and login information in my database and redirecting the user to another page using the useNavigate Hook. Every time I try clicking on the signup or login button on the frontend, it fails an ...

Is there a way to remove the sign up link from the AWS Amplify Vue authenticator?

Utilizing the amplify-authenticator component from the aws-amplify-vue library to manage authentication in my application. I am currently exploring methods to disable the "Create Account" link on the front end interface, but haven't found a direct sol ...