Is there a way to display a Google Map marker after a certain amount of time without needing to refresh the

Is it possible to update Google Map markers without refreshing the map itself every 30 seconds?

The markers' latitudes and longitudes are retrieved from a database.

Once obtained, these markers are then allocated onto the Google Map.

However, the issue arises when the markers' positions change after 30 seconds as the entire map is refreshed. The goal is to have the Google Map display the updated marker positions without refreshing the whole map.

Below is the provided code snippet:

<script>

    function initMap() {
        var infowindow = new google.maps.InfoWindow();
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 12,
            center: {lat: 19.9518684, lng: 73.7354084}
        });

        var image = '<?php echo $getImagePath; ?>'
        for (var o in markers) {

            lat = markers[ o ].lat;
            lng = markers[ o ].lng;
            address = markers[ o ].address;

            var my = new google.maps.LatLng(lat, lng);
            //console.log(my);
            var marker = new google.maps.Marker({
                position: my,
                map: map,
                icon: image,

            });
            google.maps.event.addListener(marker, 'click', function () {
                infowindow.setContent("'" + address + "'");
                infowindow.open(map, marker);
            });

        }

    }

</script>

Attempts using

google.maps.event.addDomListener(window, "load", initMap);
and window.onload = initMap; haven't been successful. Any assistance would be greatly appreciated!

Answer №1

Hopefully this slight modification to your code will steer you in the right direction. Without all the necessary details provided in the question, I can only make educated guesses

// These variables are global as they are set in initMap and utilized outside of it
var image = '<?php echo $getImagePath; ?>';
var map;
var infowindow;
var markers = [/* some initial markers loaded almost magically */];

function initMap() {
    infowindow = new google.maps.InfoWindow();
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 12,
        center: {lat: 19.9518684, lng: 73.7354084}
    });
    updateMarkers(true);
}

function updateMarkers(firstLoad) {
     markers.forEach(marker => {
         var lat = marker.lat;
         var lng = marker.lng;

         marker.my = new google.maps.LatLng(lat, lng);

         if (firstLoad) {
             marker.marker = new google.maps.Marker({
                position: marker.my,
                map: map,
                icon: image,

            });

            google.maps.event.addListener(marker.marker, 'click', function () {
                 infowindow.setContent("'" + marker.address + "'");
                 infowindow.open(map, marker.marker);
            });
        } else {
            marker.marker.setPosition(marker.my);
        }
     });
}

function locateAndModifyMarkerDataWithMagic(marker) {
    // Find corresponding marker in markers array
    // Update lat, lng, and address
}

function retrieveNewMarkerPositionsViaAjaxAndInvokeCallback(cb) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'someURI');
    xhr.onload = function() {
        var data = JSON.parse(xhr.responseText);
        data.forEach(function(marker) {
            locateAndModifyMarkerDataWithMagic(marker); 
        });
       cb()
    };
    xhr.send();
}

setInterval(function () {
    retrieveNewMarkerPositionsViaAjaxAndInvokeCallback(function() {
        updateMarkers(false);
    });
}, 30000);

Without insight into how markers are initially loaded into markers, or what is expected from

retrieveNewMarkerPositionsViaAjaxAndInvokeCallback
and
locateAndModifyMarkerDataWithMagic
, it's challenging to offer precise guidance without further context on marker handling within your codebase

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

Ways to verify if a variable holds a JSON object or a string

Is it possible to determine whether the data in a variable is a string or a JSON object? var json_string = '{ "key": 1, "key2": "2" }'; var json_string = { "key": 1, "key2": "2" }; var json_string = "{ 'key': 1, 'key2', 2 } ...

Tips for sending web form data straight to Google Sheets without the need for an authentication page

Exploring the Concept I have a unique idea to develop a landing page with a form that captures visitors' email addresses in a Google Sheet. After discovering a helpful post containing a Google App script for this purpose, I followed the guidelines o ...

The HTML checkbox remains unchanged even after the form is submitted

On a button click, I have a form that shows and hides when the close button is clicked. Inside the form, there is an HTML checkbox. When I check the checkbox, then close the form and reopen it by clicking the button again, the checkbox remains checked, whi ...

Guide for displaying SQL data in an HTML table

I am currently working on transferring my SQL data to an HTML format. The code I have so far is not functioning as expected. I attempted to include HTML within my PHP code, and now I am considering if it would be better to do it the other way around (emb ...

I am interested in scraping a webpage, how should I go about it?

Similar Questions: How to create a web crawler? Top techniques for parsing HTML I've always been curious about accomplishing a task like this. Although I do not own or manage the website (), the information I am interested in is publicly acce ...

Exploring the Prototype-based programming concept in JavaScript

I am determined to deepen my understanding of JavaScript and explore what lies beneath its surface. While I have delved into various guides on the Object-Oriented Paradigm with Prototypes in JavaScript, I am struggling to comprehend how this paradigm diffe ...

Issues encountered with jQuery Form Plugin failing to pass a string value to PHP

I'm currently experimenting with the jQuery form plugin (http://jquery.malsup.com/form) to handle photo uploads and previews. However, I'm encountering an issue where the data strings expected to be sent to PHP using the ajaxForm function are com ...

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

Should pages be indexed to index.php or should the top and bottom parts of the page be created and included in all content pages?

I've been out of the webpage creation game for a while, but I've recently decided to get back into it. Like everyone else, I want to learn the best way to do this. However, I find myself facing a dilemma on how to structure my pages. My initial i ...

Guide on displaying the name attribute of a button along with its price in a separate div when clicked

Upon clicking the Koala button, I want to display a message showing the id name of the button and the corresponding price for Koalas. Here is the HTML code snippet: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link h ...

selecting options from a drop-down menu within a table's row

I am currently working on a project where I need to populate a table in PHP by reading data from a file and parsing it line by line. One of the fields in the table needs to display a drop-down select list with predefined values, not generated dynamically. ...

removing the mapStateToProps function will result in an undefined value

I am new to React and I'm in the process of converting a class component to functional components using hooks. I need some guidance on safely removing 'mapStateToProps' without encountering undefined errors. I have two pages, A.js and B.js. ...

The parsing of source maps fails due to issues with the .htaccess file

After analyzing the web page, I found that the .htaccess file contains the following code: RewriteEngine On RewriteBase / Options -MultiViews DirectorySlash Off # skip POST requests RewriteCond %{REQUEST_METHOD} POST RewriteRule ^ - [L] RewriteCond %{R ...

Error: Collection2 validation did not pass: The field 'name' must be filled in, the field 'email' cannot be empty, and the field 'message' is mandatory

I need to set up a way for visitors to send messages through my website const mongoose = require("mongoose"); mongoose.connect("MongoDb-Connection-Uri") .then(() => { console.log("mongodb connected"); }) .catch(() => { console.log("fail ...

Automatically numbering table columns with custom language localization in JavaScript using Jquery

Is there a method to automatically number table data in a local or custom language? As a Bengali individual, I have figured out how to automatically number the first data of each row using css and js. However, I am uncertain about how to implement custom n ...

Issue encountered while transferring data from view to controller via ajax

I'm looking for a way to send the ID of the checked field and the string "checked" to the database using AJAX. I'm not very familiar with how AJAX works. <h2 id="h2">To Do List</h2> <ul id="new"> <?ph ...

Refreshing GIF images in React using forceReload

In order to restart the gif animation every 12 seconds or whenever the activeIndex changes, I need to reload a GIF image with CHECKMARK_ANIMATION_ICON as the source. Below is the code: const reloadImgSource = (imgSource) => { setTimeout(() =& ...

Iterating over the IDs of div elements using jQuery loop

Currently, I am working with a bootstrap accordion and attempting to retrieve the ID and HREF values for each individual accordion using jQuery. Here is the code snippet that I have been utilizing: $('.room-loop').each(function(id){ $('. ...

What could be causing the jQuery news ticker to malfunction on my site?

I recently made some changes to my main page by embedding HTML and adding the following code/script: <ul class="newsticker"> <li>Etiam imperdiet volutpat libero eu tristique.</li> <li>Curabitur porttitor ante eget hendrerit ...

Mastering regular expressions in TypeScript

My goal is to perform linting on staged files that are either .ts or .tsx and located within the src folder. I am aware that for selecting all js files one can use "*.js": [--list of commands--] inside the lint staged property. I'm curious to learn m ...