Stop the deletion of markers from the layer upon refreshing the map

Being a beginner, I am facing a complex project. The map refreshes every 10 seconds and there is a button that generates coordinates, time, and events (markers) for each ID. When I click the button for the first time, new data is generated for odd IDs, and when clicked again, it is generated for even IDs.

Ajax:

function callAjax() {
        console.log('ajax');
        $.ajax({
            url: '/device_new',
            type: 'GET',
            dataType: 'json',
            success: function(data) {
                var coordinates = data;

                markerLayer.clearLayers();

                for (var i = 0; i < coordinates.length; i++) {
                    var icon = getMarkerType(coordinates[i].event);
                    if (coordinates[i].x && coordinates[i].y) {

                        marker = L.marker([coordinates[i].x, coordinates[i].y], {
                                icon: icon
                            })

                            .bindPopup("Device ID: " + coordinates[i].deviceId + '<br>' + "Time: " + coordinates[i].datetime);

                        marker.addTo(markerLayer).addTo(map);
                    }
                }
                map.fitBounds(markerLayer.getBounds(), { padding: [50, 50] });
            },
        });
        setTimeout(callAjax, 10000);
    }

Update script:

function updatedev() {
        $.ajax({
            //the route pointing to the post function
            url: '/device/update/',
            data: {
                id: updateDeviceNew
            },
            type: 'GET',
            // remind that 'data' is the response of the AjaxController
            success: function(data) {
                updateDeviceNew++;
            },
        });
    }

Controller:

public function update(Request $request)
{
    $value =$request->id;

    $number=Device_new::get()->count();


    //while i < broj zapisa u tabeli $device_new = Device_new::where('deviceId',1)->update(['x' => $x, 'y' => $y, 'datetime' => $datetime]); prvi put za neparne drugi put za poarne itd
    if($value%2!=0)
    $i=1;
    else
    $i=2; 
    for ($i; $i<=$broj; $i+=2){
        $x = rand(44450000, 45000000) / 1000000;
        $y = rand(16400000, 17900000) / 1000000;
        $event=rand(1,4);
        $datetime = new Carbon('now','Europe/Belgrade');


        $device_new = Device_new::where('deviceId',$i)->update(['x' => $x, 'y' => $y, 'datetime' => $datetime, 'event' => $event]);
    }
    return $number;
}

In the callAjax() function, there is a command markerLayer.clearLayers(); that removes the layer with markers and recreates it at the end of the loop. This causes a problem for me as it refreshes the map and displays both old and new markers again.

Is there a way to prevent rewriting unchanged markers?

Answer №1

For each new layer, make sure to add it only to the markerLayer and not the map as well. If you clear the layers from the markerLayer, they will still remain on the map. It is recommended not to add them directly to the map. Instead of using:

marker.addTo(markerLayer).addTo(map);

Use the following:

marker.addTo(markerLayer);

This way, you only need to add the markerLayer to the map once.

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

Various ways to declare functions in JavaScript

1)Function declaration with variable name: var x = function (a, b) {return a * b}; 2)Another type of function in JavaScript within Angular1: var method = { add_category: function(data, success, failure) { $upload.upload({ url: b ...

Remove Angular.js entirely from your system

Is it okay to remove all Angular files and directories without causing any issues? I've searched for information on uninstalling Angular but have come up empty-handed. ...

Next.js page transitions causing Google Tag Manager to malfunction with 'react-gtm-module'

I am currently working on a Next.js project and have successfully integrated Google Tag Manager (GTM) using the react-gtm-module package. Interestingly, everything works perfectly when the application is initially loaded in debug mode, regardless of the st ...

How can nested arrays be utilized in Angular 2 reactive forms?

After successfully using a tutorial to create reactive forms in Angular 2, I encountered a new challenge. The tutorial helped me set up an 'Organisation' form with an array of 'Contact' groups, but now I am struggling to add an array wi ...

Retrieve the HTTP Code and Response Header for a successful AJAX request

I am attempting to retrieve the HTTP Response Code/Response Header from my AJAX request. Below is the initial script I used: $("#callContact1").click(function() { $.ajax({ url: "https://www.server.com?type=makecall", data: {}, type: ...

Implement a single-click function for two separate input elements with the type="submit" using JQuery

I have a dilemma with my two buttons <input type="submit" id="update" value="Update"> <input type="submit" id="close" value="Close"> Is it possible to create a single click operation for both of them? One suggestion is: $('#update || # ...

Troubleshooting issue with Jquery animation from left to right

What's the issue with this code? It is supposed to animate the arrow from left to right and then back to left again repeatedly, but it's not working as expected. Any ideas on why that might be? function moveRight(){ $('#myIcon'). ...

Utilizing Laravel 5 to Send Password Reset Link via Ajax

I'm currently troubleshooting a code snippet that I have: jQuery.ajax({ type:"POST", url:"/password/email/", data:{ _token: jQuery("#forgotPasswordContainer input[name='_token']").val(), email: email }, d ...

The JavaScript class failed to work properly within the asp.net framework

I have successfully implemented a JavaScript function on my aspx page. Here is the code snippet: <script type="text/javascript"> $(document).ready(function () { console.log("ready!"); var options = []; var ...

Enhancing WooCommerce by including additional text following the price for specific shipping methods

I need assistance with including a short message like "(incl. VAT)", following the shipping-price display on the checkout page. The challenge lies in ensuring that this message only appears for a specific shipping method within Zone 1 (zone_id=1), but I&a ...

What is the best way to condense a repetitive method declaration and make it more concise?

I'm facing a situation where I have declared similar const values. Here's my current setup... import React from 'react' function Component_a() { const x = 5; const y = 10; const image_a = [...Array(x)].map((e, i) => ...

Is it possible to make changes to dynamically inserted HTML using jQuery.ajax?

I'm facing a scenario in jQuery where I make an ajax call that inserts HTML into my website. However, I also need to perform operations on this inserted HTML within the same ajax call's success callback function. Here is a simplified version of ...

Retrieving the content of a dynamic template with Angular-UI-Router

Currently, I am in the process of developing an angular application utilizing angular-ui-router. The backend of the application consists of a REST api that provides a form URL based on a specific ticket id. My aim is to dynamically set the template in app. ...

How to Exhibit a Line or Value from a CSV File with the Help of JavaScript and AJAX

The data in the CSV file is structured as follows: STATION,DATE,HLY-WIND-AVGSPD,HLY-WIND-VCTDIR USW00013904,01-01T01:00:00,5.6,350 USW00013904,01-01T02:00:00,5.4,346 USW00013904,01-01T03:00:00,5.5,342 USW00013904,01-01T04:00 ...

Vue form mysteriously invisible

After attempting to create a Products form using VueJS, I encountered an issue where my localhost simply displayed a blank page upon refreshing. Here is the screenshot of the page Despite restarting XAMPP, the problem persisted with only a blank page bein ...

Sending a JSON stringified JavaScript object to a server: A step-by-step guide

I am currently working with VB.Net and MVC 5. In my project, I have an object that I created using javaScript: var myEdits = { listOfIDs: [], listOfValues : [] }; My goal is to send this object to the controller an ...

No data was returned after submitting the formData in the post request

Attempting to send a POST request in VueJS let data = new FormData() data.append('name', 'hey') fetch('http://homestead.test/api/customers', { method: 'POST', headers: { 'Content-type': &a ...

Can drop down menus be integrated into the tablesorter plugin?

I have successfully created a table using PHP, AJAX, and the tablesorter plugin. Now, I want to convert some input fields into dropdown boxes so users can select options for certain fields that may need to be changed. Additionally, I need to save this upda ...

The Laravel APIs are experiencing issues with HTTPS, resulting in the error message NET::ERR_CERT_COMMON_NAME_INVALID

Recently, I encountered an issue while using Laravel on my Linux server. The Laravel APIs were not functioning properly when accessed through HTTPS on both my local and live servers. This resulted in an error message stating NET::ERR_CERT_COMMON_NAME_INVAL ...

What is causing the angular ng-repeat table to not sort correctly?

Currently, I am facing an issue with a table that is being populated by Angular: I have provided the code here so you can see the problem in action: http://plnkr.co/edit/qzY4r2XWq1UUJVrcqBsw?p=preview When I click on the a elements, the sort order change ...