Unlock the powers of Openlayers 5: Altering interactions and accessing targeted vertices

When making changes to a feature, there is a convenient option to delete a single vertex. The documentation explains this feature as follows:

removePoint(){boolean}: Removes the vertex that is currently selected.

()

Working on mobile devices, I intend to show a popup with a delete button next to a vertex when a user clicks or hovers over it. However, I am unsure how to obtain the coordinates of this particular vertex. Although I can visually identify the vertex on the map with a different style, I am puzzled about retrieving its coordinates. The information should be stored somewhere for it to work with the automatic "pointing to" style and removePoint method.

Answer №1

Presented here is a creative solution that utilizes a button for the purpose of deleting a vertex within a specific context. The visibility of the button is toggled based on the presence of a vertex to delete, which may be displayed as a popup.

Key features of this solution include:

  • A condition option that determines when to display the delete button based on the proximity of a point to the user's click.
  • An insertVertexCondition option that controls the visibility of the button when no vertex is present at the current location.
  • The utilization of modifystart and modifyend events to dynamically hide the button while the user is actively moving around the map.
  • A removePoint function that is triggered when the delete button is clicked.

The visibility of the button is dependent on the user's actions, ensuring that it is only shown when relevant and does not rely on undocumented or private features.

To see this solution in action, check out the demonstration here.

var btElt = document.getElementById("delete");

// Modify interaction
var mod = new ol.interaction.Modify({
  source: vector.getSource(),
  condition: function(e){
    var f = this.getMap().getFeaturesAtPixel(e.pixel,{
      hitTolerance:5
    });
    if (f) {
      var p0 = e.pixel;
      var p1 = f[0].getGeometry().getClosestPoint(e.coordinate);
      p1 = this.getMap().getPixelFromCoordinate(p1);
      var dx = p0[0]-p1[0];
      var dy = p0[1]-p1[1];
      if (Math.sqrt(dx*dx+dy*dy) > 8) {
        f = null;
      }
    }
    if (f) btElt.style.display = "inline-block";
    else btElt.style.display = "none";

    return true;
  },
  insertVertexCondition: function(e) {
    btElt.style.display = "none";
    return true;
  }
});
mod.on(['modifystart','modifyend'], function(){
  btElt.style.display = "none";
});
map.addInteraction(mod);

function deleteVertex() {
  mod.removePoint();
  btElt.style.display = "none";
}

Answer №2

After delving into the source code, I managed to come up with a somewhat messy yet effective solution. Here's the code snippet for reference:

this.modify = new Modify({
    features: new Collection([this.selectedFeature]),
    pixelTolerance:30,
    condition: (event)=>{
        if(this.modify["lastPointerEvent_"] && this.modify["vertexFeature_"])
            this.removePointPopup.setPosition(this.modify["lastPointerEvent_"].coordinate);
        else
            this.removePointPopup.setPosition(undefined);
        return true;
    }
});
this.modify.on("modifyend",ev=>{
   this.removePointPopup.setPosition(ev.target["lastPointerEvent_"].coordinate);
})

[...]

removePoint(){
     this.modify.removePoint()
     this.removePointPopup.setPosition(undefined);
}

If anyone has a more elegant solution, please feel free to share it.

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

Utilizing only select functions from lodash can be more beneficial than installing the entire library, as it reduces the amount of unnecessary dependencies

While working on my project, I incorporated underscore.js for its functionality. However, I recently discovered the need for Lodash's fill function. The idea of adding Lodash to my project seems excessive due to overlapping features with underscore.js ...

Trigger fixed element to appear/disappear when scrolling using JavaScript

I've tried multiple solutions, but I can't seem to get this functionality to work properly on my website. I'm attempting to create a "schedule a demo" button similar to the one on www.bamboohr.com Currently, I have the following html, css, ...

How can I best access the object being exposed on the webpage using <script type="text/json" id="myJSON">?

In our current project, we are successfully using AMD modules to organize and structure our code. One idea I have is to create an AMD module that accesses a script tag using a jQuery ID selector and then parses the content into JSON format. Here's an ...

Looking to develop a dynamic JSON preview feature using AngularJS

Below is an example of JSON data: data: [{ test: { innertest: "2345", outertest: "abcd" }, trans: { sig: "sou", trip: [{ one: "2" }, { two: "3" }], otherac: "iii" },{ test: { innertest: "uuu", ...

Using more than one variable for filtering in Vue.js

I've been busy working on implementing table filtering in Vue.js. So far, I have successfully filtered the table by name and date. However, I'm now facing a challenge with adding another filter along with them. If you want to check out my curren ...

Disabling the submit button on an MC form - step by step guide

In order to create a multiple-choice question with radio buttons, each question must have only one answer choice. Each question should provide three options for the user to select from. It is necessary to validate whether the user has answered every questi ...

Enhancing the Calculator Functionality in a React Program

I'm struggling to incorporate a reset button into the input field, similar to CE on a calculator. I'm facing challenges when it comes to integrating it within the existing code structure. import { useRef } from "react"; import './A ...

Adding a JavaScript object into the $http service

Struggling to correctly insert an object in this format: $scope.newObj = {1: "N/A", 2: "KO", 3: "OK", 4: "OK", 5: "OK", 15: "N/A", 19: "OK"} An attempt was made using the following loop: var objt = $scope.newObject; console.log($scope.newObject[0] ...

Triggering unexpected syntax error upon clicking the dropdown menu in the navigation bar

I encountered an error when attempting to click the dropdown list on my website. The error message reads as follows: Uncaught Syntax error, unrecognized expression: #. This error only seems to occur when using Chrome or Edge browsers. Currently, I am usi ...

I'm curious about the origin and purpose of req.user - where does it come from and

Recently, I've been delving into Nestjs and found myself a bit puzzled by the req.user. Where does this come from and do we have to manually request it? What exactly is req.user and what advantages does it offer? Must I assign payload to it manually? ...

What could be causing the malfunction of the Google Maps iframe, preventing it from displaying the location properly

I am having trouble with this Google Maps iframe, it doesn't seem to display the location properly. Why is that? <iframe src="https://www.google.com/maps/place/18%C2%B045'14.7%22N+98%C2%B059'44.0%22E/@18.7540995,98.9933669,17z/data=!3m1! ...

Creating a dynamic dropdown list with PHP and AJAX using JQuery

I was attempting to create a dynamic dependent select list using AJAX, but I am facing issues with getting the second list to populate. Below is the code I have been working with. The gethint.php file seems to be functioning properly. I'm not sure whe ...

What is the best way to send a JQuery variable using JSON.stringify and retrieve it on the server-side?

I need to pass the value in JSON.stringify and receive it on the Server side. Please note: When I attempt to pass the value directly without utilizing a JQuery variable, everything works smoothly. Without using a JQuery variable (it's functional) d ...

Having trouble with jQuery toggle fade: Unable to make the div fade in/out when toggling

Is there a way to modify the functionality of my black button so that when clicked, the red div fades out while the blue div fades in? Right now, clicking the button switches between the two divs without any fading effect. Fiddle: http://jsfiddle.net/ddac ...

attempting to retrieve numerical variable beyond the function in jQuery

Trying to implement a star rating system and need to access the rating number for further actions. How can I make the number variable accessible outside of the click function? $(document).ready(function () { $(".li").mouseover(functio ...

Add styling to a window popup and close it when focus is lost in Ext JS

I am trying to implement a specific functionality where the popup arrow should be at the edge of the textbox as shown in the image below. How can I achieve this? Additionally, how can I make sure that clicking outside the control destroys the popup instead ...

How can you disable a single button when clicked using the map method, and update the className after a timer runs out in React?

Is there a way to disable only one button when clicked using the map method? I currently have a disabled hook that affects all pressed buttons. Also, how can I revert the 'current__events__hot-price disabled' className back to 'current__even ...

Ways to effectively hide one window or pop-up upon clicking another

I am working on creating an interactive website for my close circle of friends and family. One of the key features is to have a button that displays their biography when clicked. What I'm aiming for is that when a different bio is selected, the previo ...

Make the div disappear after a specified time

Does anyone know of a code snippet that can make a couple of div elements fade out after a specific time period? Currently, I have the following example: <div id="CoverPop-cover" class="splash"> <div id="CoverPop-content" class="splash-center"> ...

What is the method to create a polygon in its entirety by utilizing a for loop within Javascript?

After successfully using the Canvas of HTML to draw a convex polygon, I encountered an issue. In the provided code snippet, t2 represents an array of points with getX() and getY() methods. The drawing function performs as expected until it reaches the seg ...