How can I use JavaScript to add and remove geojson with just a button click?

Looking for a solution to add and clear geojson data with the click of a button? Check out this code snippet:

<input type="button" value="ruta vista imss" onclick="rutavistaimss()" >

<script>
var rutavs = { 
                "type": "Feature",
                "properties": {
                                "name": "ruta vista imss"
                              },
                "geometry": {
                             "type": "LineString",
                             "coordinates": rutavistaimsscoords
                            }
             };

var rutavistaimss1 = L.geoJson(rutavs);

let flag = true

function rutavistaimss() {
  if (flag) {
    // your logic
    map.addLayer( rutavistaimss1 ); 
  }
  flag = !flag
  map.removeLayer( rutavistaimss1 );
}
</script>

Consider incorporating jQuery for additional functionality.

Answer №1

To always remove the layer, make sure to update your code as follows:

let isVisible = true

function toggleLayerVisibility() {
  if (isVisible) {
    // Your logic here
    map.addLayer( rutavistaimss1 ); 
  } else {
    map.removeLayer( rutavistaimss1 );
  }

  isVisible = !isVisible
}

Answer №2

Alternatively, you can achieve the same outcome without using a flag variable:

function toggleIMSSRouteVisibility() {
if (map.hasLayer( imssRoute1 )) {
    map.removeLayer( imssRoute1 )
  }
else {
  map.addLayer( imssRoute1 )
  }
}

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

Unable to utilize PageMethod (Asynchronous JavaScript and XML in C# .net)

I've been experimenting with the PageMethod feature in asp.net. To start, I added a Script Manager to my aspx page: <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager> Then, I created an o ...

Utilizing ASP.Net Core version 3 to effortlessly send a POST request to the controller

I am having difficulty with my POST request to an ASP.NET Core 3 server because the number always seems to be 0. Is there something specific in ASP.NET Core 3 that I might be missing? Using the [FromBody] parameter has not resolved the issue. Even passing ...

Basic use of AJAX for sending the value from jQuery's datepicker

As a novice in JavaScript and AJAX, I'm hoping for your patience as I navigate my way through. In the scope of this project, I am utilizing the CodeIgniter framework. My objective is to implement a datepicker and transmit its value via AJAX. Below is ...

Creating a user-friendly product customization tool using fundamental JS, HTML, and CSS techniques

Can anyone provide me with some tips on the best practices for structuring JavaScript code? I am working on creating a tool for a smoothie shop owner where customers can select ingredients, and we need to calculate the total amount of sugar and vitamins. H ...

Access the child component within an @ChildComponent directive in Angular

Is it possible to retrieve child components of another component? For instance, consider the following QueryList: @ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>; This QueryList will contain all instances of the SysColumns class, which ...

What is the best method to retrieve the audio attributes of the currently playing song using the Spotify Web API?

Check out this link for more information on using the Spotify web API to access audio features of tracks. Hello, I am currently utilizing the Spotify web API to retrieve audio features of a track. However, the API documentation only explains how to obtain ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Managing the variances in changing dates

I need to gather information on varying durations, such as a month, a year, 2 months, or even 20 days. After collecting this duration, I want to send an email to all children whose birthdays are x days before the specified duration. The challenge lies ...

The error "TypeError: ollama.chat is not a function" has occurred when trying to use the ollama module in

Currently, I am grappling with a Node.js project that requires me to utilize the ollama module (ollama-js). The problem arises when I invoke the async function chatWithLlama() which contains ollama.chat(), resulting in the following error being thrown: Ty ...

Having trouble uploading files with jQuery File Upload functionality

Issue: I need to set a session variable and redirect the user to a different PHP page after uploading a .txt file using jQuery File Upload. HTML code (upload.php): <!-- The fileinput-button span is used to style the file input field as button --> ...

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 ...

Understanding when the @Input parameter has been modified

I need a way to trigger a function every time the @Input value is accessed, regardless of whether it has changed or not. Here's what I have tried so far: ngOnChanges(changes: { [propName: string]: SimpleChange }) { if( changes['inputName' ...

What is the process for binding an absolute path instead of a relative path in a script that includes Node and Perl calls?

In my script, there is a function with the following code: def tokenize(latex,kind='normalize'): output_file = './out.lst' input_file = './input_file.lst' cmd = "perl -pe 's|hskip(.*?)(cm\\|in& ...

Shadows persist despite light intensity being reduced to 0 during runtime

Struggling to figure out how to get rid of these persistent shadows... During runtime, I attempt: light.intensity = 0.0; This makes the scene darker (which is good), but the shadows created by the light remain visible. I've experimented with both ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...

PHP allows developers to access the response from a server without revealing the source code

I currently have a script that utilizes the fetch function in Javascript to fetch the HTML source code of a remote URL. Here is the script: <!DOCTYPE html> <html> <body> <p id="output"></p> <script> function g ...

What is the best way to make an array with values from a checkbox list?

I am working on a project that involves rendering a list of products categorized into different categories. Users can select these categories using checkboxes. Are you interested in learning how to create an array containing the selected values from the ch ...

Navigating a table while keeping headers in place at the top

Trying to construct a table where the thead remains fixed while the tbody scrolls. Utilizing percentages and fixed width for cell size determination, aiming for uniformity and alignment between percentage td's and thead headers. Referenced JSFiddle d ...

The function has already executed and returned data before receiving the late response from the Ajax call

I'm facing an issue in my code where I need to return an array of objects from a function based on certain criteria. If the URL passed contains the required data, I populate the array and return it with a promise. However, if the URL doesn't have ...

Simulated static functions are invoked within the main function under evaluation

Looking to mock certain functions within a function I'm currently testing. In my code, there is a class with various static private functions that are called by the main function. Specifically, I want to verify the output of MyClass.functionD (which ...