Tips for preventing flickering caused by set Interval in angular 2+

Displaying dynamic latitude and longitude data on Google Maps while using setInterval() function. Code snippet below:

this.timer = setInterval(()=>{this.getMapData();},30000);

An issue arises where the map flickers when updating the data with this.getMapData(). How can the data be updated every 30 seconds without causing flickering on the div/map?

getMapData() {
    this.spinner.show();
    this.serv.getMapData(this.ds, this.ln).subscribe(res => {
      this.spinner.hide();
      this.deleteMarkers();


      if (res.Data && res.Data.length > 0) {

        this.mapData = res.Data;
        console.log(JSON.stringify(this.mapData));


        if (this.mapData != null && this.mapData.length > 0) {
          for (var i = 0; i < this.mapData.length; i++) {
            var latlng = {lat: parseFloat(this.mapData[i].latitude), lng: parseFloat(this.mapData[i].longitude)};
            this.addMarker(latlng, this.mapObject, this.mapData[i].Name);
            this.markerName = this.mapData[i].Name;


          }
        }
      } else {

        this.toastr.error('No Data Found', 'Oops!');
      }

    },err=>{
      this.spinner.hide();
    });


  }




 addMarker(latlng, mapobj, markerLabel) {
    var marker = new google.maps.Marker({
      position: latlng,
      label: '',
      map: mapobj,
      animation: google.maps.Animation.DROP,
    });






var infowindow = new google.maps.InfoWindow({
  content: markerLabel
});

google.maps.event.addListener(marker, 'click', function() {
 // infowindow.open(Map,marker);
});



 infowindow.open(Map,marker);





   // Set postion for the marker after getting dynamic data it posittions to the point
   mapobj.setZoom(17);
   mapobj.panTo(marker.position);
    this.markers.push(marker);
  }



// Sets the map on all markers in the array.
  setMapOnAll(map) {
    for (var i = 0; i < this.markers.length; i++) {
      this.markers[i].setMap(map);

    }
  }

  // Removes the markers from the map, but keeps them in the array.
  clearMarkers() {
    this.setMapOnAll(null);
  }


  // Deletes all markers in the array by removing references to them.
  deleteMarkers() {
    this.clearMarkers();
    this.markers = [];
  }

Answer №1

After our discussion, it was determined that within the addMarker() function:

if(this.marker != null){
    this.marker = new google.maps.Marker({
      position: latlng,
     label: '',
      map: mapobj,
      animation: google.maps.Animation.DROP,
    });
   }
   else{
     this.marker.setPosition(latlng);
   }

Basically, the code checks if the marker is null. If it is indeed null, then a new marker object is created. On the other hand, if the marker already exists, its position is simply updated to the current dynamic latlng.

This approach eliminates any flickering issues on the map since only the marker's position changes. Additionally, there is no longer a need for this.deleteMarkers() as you are now updating the position instead of re-creating the marker.

Instead of using a setInterval function, consider utilizing the rxjs operator interval to call the service and fetch data at specified intervals (e.g., once every 30 seconds).

To implement this change in your service, you can use the following structure:

return Observable.interval(30000).flatMap(()=>{ 
  return this.http.get(url + data+'/LocationId='+ param).map(res => { 
     return res.json(); 
  }); 
)};

EDIT

Ensure you have the following imports in your code:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMap`;

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 use of `slot` attributes in Ionic has been deprecated and flagged by the eslint-plugin-vue

I encountered an error message while using VS Code: [vue/no-deprecated-slot-attribute] `slot` attributes are now considered deprecated. eslint-plugin-vue https://i.sstatic.net/DUMLN.png After installing two plugins in .eslintrc.js, I have the following c ...

The Material UI button shifts to a different row

I need help adjusting the spacing between text and a button on my webpage. Currently, they are too close to each other with no space in between. How can I add some space without causing the button to move to the next line? const useStyles = makeStyles((the ...

Using Angular 4 to import an HTML file

I am trying to save test.svg in a component variable 'a' or svgicon.component.html. To achieve this, I have created the svgicon.component.ts file. However, it's not working. What steps should I take next? svgicon.component.ts import ...

BoxHelper causes BoxGeometry to become enormous

UPDATE Upon further investigation, I discovered that the issue with the oversized box occurs specifically when I attempt to incorporate the HelperBox. To demonstrate this problem, I created a JSFiddle, where the second box's size remains unaffected. ...

What is the most effective method for preserving RichText (WYSIWYG output)?

I am currently using a JavaScript-based rich text editor in my application. Could you suggest the most secure method to store the generated tags? My database is MySQL, and I have concerns about the safety of using mysql_real_escape_string($text);. ...

Retrieving data from the database into a DIV using ajax

Here is the code snippet I am using to retrieve values from my database at regular intervals: <script type="text/javascript"> $(document).ready(function(){ var j = jQuery.noConflict(); j(document).ready(function() { j(".refreshMe ...

Trouble installing NPM packages from Artifactory on Windows 10

Problem Description: I am utilizing Artifactory for my NPM packages. When attempting to install them on "Windows - 7", everything is functioning correctly. However, on "Windows - 10" an error is being displayed and the packages are not installing. Error M ...

Receiving an error stating "module not found" when attempting to retrieve the NextAuth session using EmailProvider in getServerSideProps

Trying to access the NextAuth session from a server-side call within getServerSideProps, using an EmailProvider with NextAuth. Referring to an example in NextAuth's documentation, I'm attempting to retrieve the session from getServerSideProps. T ...

Client-side database integrated in web application

As I work on a project for healthcare providers, the handling of sensitive data is crucial. Since I am utilizing server-side operations solely for CRUD tasks, I have considered whether it would be viable to deliver the Angular application directly to the u ...

Steps for including an animation class in a div

Is it possible to add the sweep to top blue color animation to the red box using a set-timeout function instead of hover? I tried using the following code but it doesn't seem to be working. Can you help me troubleshoot? setTimeout(function() { $( ...

What steps can I take to avoid horizontal scrolling on mobile due to a table overflowing?

My website displays a table within a bootstrap container, row, and column. While everything looks good on larger screens, the content within the table is causing a horizontal scroll on smaller screens, making the footer look distorted. This results in a me ...

Every Other Element

I'm currently stuck on a math problem and could use some help. The task is to write a JavaScript function that identifies elements at even positions in an array. The array is composed of number elements. The desired result should be displayed in an el ...

Utilizing Dynamic Image Sources in Vue.js with the Help of APIs

Can someone help me figure out how to solve this issue? I have an API that returns a base64 image, and I want to load this image on my site. Any suggestions on where or how I should implement my function? This is the API call located in the methods: metho ...

Integrating a fresh element into the carousel structure will automatically generate a new row within Angular

I'm currently working on an Angular4 application that features a carousel displaying products, their names, and prices. At the moment, there are 6 products organized into two rows of 3 each. The carousel includes buttons to navigate left or right to d ...

How can we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

Sign-in options displayed in a drop-down menu

I have successfully implemented a jQuery animation for a dropdown sign in div. The sign up form is integrated with PHP to verify the existence of users in the database. However, I came across an issue where if I echo something, the dropdown menu disappears ...

What is the best way to immediately update the state in a React functional component?

Having recently started learning React, I find myself struggling to understand the lifecycle of a functional component. Let's consider a scenario where I have multiple checkboxes labeled as: checkbox, a, b, c, and d, each corresponding to values a, b, ...

Creating a cutting-edge Angular 2 project with the power of webpack

Previously, I created a sample Angular 2 application using System JS for module loading, which was functioning properly. Now, I decided to switch to webpack module bundler instead of system JS and made the necessary changes. However, upon running the app ...

Is it possible to revert an image back to its original state after it has been altered on hover

I am currently experimenting with jQuery to create an image hover effect where hovering over one image changes the other. I've managed to accomplish that part successfully. However, I'm struggling with how to make the original image revert back w ...

What could be causing my express router.get endpoints with multiple paths to only render text?

Currently, I am in the process of configuring a password reset flow using Pug (formerly Jade) and Express. Oddly enough, GET requests that contain URLs with multiple appended paths are causing my Pug view files to render with only text. The images and sty ...