Show the last polygon that was created using OpenLayers on the screen

Using this example from OpenLayers website:

I am attempting to create a polygon but I would like it to vanish once the polygon is finished.

Could anyone offer assistance with this?

Thank you :)

Answer №1

To ensure the polygon remains visible during interaction setup, simply exclude the source:

draw = new Draw({
    type: 'Polygon'
  });

If a target source for the drawn features is not specified, the polygon will vanish upon completion (otherwise it is appended to the source). To retrieve the polygon, monitor the drawend event.

Answer №2

It seems like you're looking to disable the draw interaction once the user has finished drawing their geometry. As @Anatoly pointed out in the comments, you can achieve this by using the drawend event to remove the interactions.

Here is a custom example I created for you:

<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css" type="text/css">
    <style>
      .map {
        height: 400px;
        width: 100%;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script>
    <title>End Draw Interaction After Draw</title>
  </head>
  <body>
    <div>
      <button id="startDraw">Start Draw</button>
      <button id="endDraw">End Draw</button>
    </div>
    <div id="map" class="map"></div>
    <script type="text/javascript">
      // vector layer
      var source = new ol.source.Vector();
      var vector = new ol.layer.Vector({
        source: source,
        style: new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255, 255, 255, 0.2)'
          }),
          stroke: new ol.style.Stroke({
            color: '#ffcc33',
            width: 2
          })
        })
      });
      // map
      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          }),
          vector
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([37.41, 8.82]),
          zoom: 4
        })
      });
      // buttons
      var startDrawBtn = document.getElementById('startDraw');
      var endDrawBtn = document.getElementById('endDraw');
      endDrawBtn.disabled = true;

      // interaction
      var draw = new ol.interaction.Draw({
        source: source,
        type: 'Polygon'
      });
      var snap = new ol.interaction.Snap({source: source});

      function endInteractions() {
        map.removeInteraction(draw);
        map.removeInteraction(snap);
        startDrawBtn.disabled = false;
        endDrawBtn.disabled = true;
      }

      function startInteractions() {
        startDrawBtn.disabled = true;
        endDrawBtn.disabled = false;
        map.addInteraction(draw);
        map.addInteraction(snap);
        draw.on('drawend', evt => {
          // console.log(evt.feature);
          endInteractions();
        });
      }

      startDrawBtn.addEventListener('click', startInteractions);
      endDrawBtn.addEventListener('click', endInteractions);
      
    </script>
  </body>
</html>

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

How can I retrieve information on a logged in Auth0 user from an API?

I'm currently working on a React application that utilizes auth0 in conjunction with an express API server. One issue I'm facing is how to access user information within the API when a secure endpoint is called. While I can retrieve user data on ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...

Splitting JavaScript Arrays: Exploring Efficient Division

I'm attempting to develop a recursive function that divides an array in half until it only consists of lengths of 3 and 2. After dividing, I want to neatly organize all the new arrays into another array. My idea is to find a way to determine the numb ...

(angular 8) Error occurred when converting a file or image to FormData due to an invalid value (Note: FormData object printed as Object Form{})

I encountered an issue where I am getting an invalid value from form data. The value appears correct in `this.fileData` with a size of 5701, but becomes empty when converted to form data - `{}` is logged when I console.log the form data. Additionally, acce ...

The selected jQuery plugin is not functioning properly within CodeIgniter framework

I recently downloaded the jQuery Chosen plugin to use the simple "multiselect" version on my website. I followed all the necessary steps and even copied and pasted the code into CodeIgniter. Despite my experience with jQuery, I am facing an issue where the ...

Integrating external information with components

Currently in my React application, I am fetching a list of stores by directly calling the API through the URL. const getStore = async () => { try { const response = axios.get( 'http://localhost:3001/appointment-setup/storeList& ...

Unable to adjust the padding of a div while the Bootstrap 4 navbar is in a collapsed state on mobile devices

I am facing an issue with a fixed navbar at the top of my page. Below the navbar, I have the page content which includes a Bootstrap 4 image carousel. The problem arises on mobile devices where I need to add top-padding to the page-container (below the nav ...

Deciding on the proper character formatting for each individual character within the RICHT TEXT EDITOR

After browsing numerous topics on Stackoverflow, I was able to develop my own compact rich text editor. However, one issue I encountered is that when the mouse cursor hovers over already bold or styled text, it's difficult for me to identify the styl ...

The lookahead will only find a match if there are brackets present within the string

Trying to use a negative lookahead to search for a particular pattern within a single line string: /\s+(?![^[]*]).+/g Applicable to the following cases: // Case 1 a.casd-234[test='asfd asdf'] abc defg // Case 2 asf.one.two.three four fiv ...

Interactive Bar chart updates in real-time with Highcharts and AngularJs

With the help of a sample from Highcharts (here), I successfully integrated a bar chart into AngularJs. Below is the HTML code: <!DOCTYPE html> <html ng-lang="en" ng-app="myModule"> <head> <meta charset="ISO-8859-1"> <script sr ...

Is it necessary to always pause before I click?

Currently, I am in the process of writing tests for my website using WebdriverIO with Mocha and Chai. However, I encountered an issue where my element is not rendered before attempting to interact with it. it('select application', function(done) ...

Proper functionality of Chrome Extension chrome.downloads.download

I am currently developing an extension with a feature that allows users to download a file. This file is generated using data retrieved from the localStorage in Chrome. Within my panel.html file, the code looks like this: <!DOCTYPE html> <html&g ...

Show information based on the user's role

I need to adjust my menu so that certain sections are only visible to specific users based on their roles. In my database, I have three roles: user, admin1, and admin2. For instance, how can I ensure that Category 2 is only visible to users with the ROLE_A ...

The JQuery ajax post function is typically called towards the conclusion of a JavaScript script

I am struggling with validating whether a username is already taken. I have been attempting to determine if the username exists by utilizing the "post" method in jQuery. However, every time I execute this function, the script seems to skip to the end of th ...

Updating the database with values dynamically using ajax without the need to refresh or change the current page

My current challenge involves adding records to a database table without the need to reload the page. I've implemented ajax for this purpose, but have been receiving an unexpected response (201) from the server (alert("Error occurred !")). Despite spe ...

Cookie Cutter Chrome Extensions

Is there a way to create a cookie that can be shared between my plugin and contentPage? I've tried creating one but it doesn't seem to appear on the cookie list of the tab page. Any suggestions or ideas on how to achieve this? ...

Go to the identical page with a message embedded in it

Creating a login page using JSP involves an index.jsp file which contains the form and javascript scriplets. The connectivity to an Oracle database and validation of username and password are handled in check1.jsp. The problem arises after entering the us ...

Issue encountered while trying to render an item from a state array in React

I encountered an issue with retrieving state data within the render function. Everything seems to work fine and displays the array when I utilize console.log(items) However, attempting to access the first item from the array results in an error console. ...

The information displayed in my Google snippet does not match the content of the intended URL

It may seem a bit confusing, so to clarify, here is an example: When you click the +1 button on this page, the snippet will display the text and URL from that specific page. However, in my case, the snippet displays text from the homepage URL instea ...

The UPDATE query failed to make any changes to the data stored in the MySQL

Currently I am developing an application using express.js. In my project, I have incorporated the "mysql" add-on (https://www.npmjs.com/package/mysql). The issue I am facing is while sending an UPDATE query to the server and receiving a response that shows ...