I am interested in dynamically updating the position of a Google Marker using a loop or some other method

Exploring the wonders of the Google API, I am eager to find a way to automatically update the position of a Google Marker on a map every five seconds without having to store latitude and longitude in a database. Essentially, I aim to have the marker relocate randomly on the map at regular intervals.

Answer №1

Important Note: The solution presented below utilizes pure vanilla Javascript.

Without access to a database, you can utilize an array of LatLng class to define the coordinates for display purposes:

  //an array representing geographical coordinates
  var locations = [
      new google.maps.LatLng(6.528166, 20.439864), //location in Africa
      new google.maps.LatLng(34.494890, 103.854720), //location in China
      new google.maps.LatLng(51.802090, 7.771800), // location in Germany
      new google.maps.LatLng(46.153450, -101.948783), // location in US
      new google.maps.LatLng(-11.495951, -49.266451), // location in Brazil
      new google.maps.LatLng(-80.287421, 23.599101) // location in Antartica
  ];

Subsequently, the setInterval() function can be employed to randomize items within the geographical coordinates array and alter both the map and marker positions.

// set interval to repeat every 5 seconds
setInterval(function() {

    // select random coordinates from the locations array
    var randomLocation = locations[Math.floor(Math.random() * locations.length)];

     // update the map center
    map.setCenter(randomLocation);

    // update the marker position
    marker.setPosition(randomLocation);
}, 5000);

A live demonstration of the functioning solution can be found here.

Trust this clarifies any queries!

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

Setting up a retrieval callback in mongoose and storing it in a global variable

Is there a way to set the value of db as a global variable? I am having trouble with getting the console output of name outside of the findOne function, it keeps showing me undefined. Any suggestions on how to fix this issue? var name; schema.findone({na ...

Before starting the operation, the beforeEach() function in the asynchronous Jasmine test is not being called

I'm currently coding a test for my client-server modules. One challenge I'm facing is that I need to ensure the server is running before the client sends its requests. To achieve this, I am attempting to utilize the beforeEach method. However, th ...

Unable to locate the resource when trying to query DynamoDB

I am having trouble accessing a DynamoDb table, as I keep encountering a "Resource not found" error. The table is set up like this; it's Active and located in the Paris Region (eu-west-3). https://i.sstatic.net/W0IZs.png This is the code snippet I ...

Find the index of the element that was clicked by utilizing pure JavaScript

I am struggling to find the index of the element that was clicked. Can anyone help me with this? for (i = 0; i < document.getElementById('my_div').children.length; i++) { document.getElementById('my_div').children[i].onclick = f ...

Differences between JavaScript array manipulation using the split(" ") method and the spread operator

I'm currently attempting to determine if a given sentence is a palindrome, disregarding word breaks and punctuation. The code snippet that utilizes cStr.split(" ") DOES NOT achieve the desired outcome. Although it splits on whitespaces (&qu ...

The sidebar.querySelector method is not working as expected

Attempting to assign an 'active' class to the clicked 'nav-link' element in order for it to stay active on the next page the user navigates to. Encountering an issue with sidebar.getElementsByClassName is not a function showing up in t ...

Is it possible to display events on fullcalendar.io using PHP and MySQL?

I'm currently trying to integrate a calendar feature on my website using PHP's "while" command. I don't have knowledge of JSON or AJAX, so I'm unsure if those are viable options for me. The issue I'm facing is that the current code ...

Determine the HTTP status code for a request using Vue.js and Ajax

I need to retrieve the HTTP status code after submitting a form (using the form submission function): return fetch(serviceUrl + 'Collect', { method: "POST", headers: new Headers({ "Content-Type": "application/json", Authoriza ...

Is the "supports" feature supported by the browser?

As I make my return to web development after some time away, I can't help but wonder if the ancient art of CSS hacks could be the solution to bridging the gap between modern @supports queries and outdated browsers that don't support these feature ...

Adjust the appearance using Timeout within a React component

I am facing a challenge with updating the style in React - specifically, the opacity of a Div element is not updating despite successfully updating the opacity in a timeout event. import React from 'react'; function PortItem(props){ let style ...

What is the method for invoking a function with a chosen date in the @syncfusion schedule with Angular 9?

capture of calendar display I am looking for a way to trigger a function with the selected date as a parameter. However, I am unable to locate the appropriate event to use within this module. Can someone provide assistance with this issue? Thanks! ...

Is there a way to cycle through each element within a loop and output a corresponding item from another array?

My data structure consists of an array of objects like this: arrOfObjs = [{type: "flower", egg: "something"}, {type: "flower", egg: "something2"}, {type: "notFlower", egg: "something3"}, {type: &q ...

What is the best way to include the toast component in my button?

I am brand new to working with Next.js and React. I have a button in my project that triggers an external JavaScript file (query.js). After the script finishes executing, I would like to display a toast notification indicating whether it was successful or ...

preserving the status of checkboxes based on an array of binary values

I am trying to figure out how to restore the state of checkboxes in an ORACLE APEX tabular form. The selection is made in the first column using the APEX row selector f01. After saving the checkbox state in a collection and then transferring it to an arra ...

Measuring Page Loading Status using Ajax

I'm still learning Ajax and JQuery, and I've been having a tough time putting this together. My goal is to use ajax navigation to load URLs and implement back and front navigations with popstate. The code below is functional, but I'm facing ...

Guide on converting a JSON containing nested JSONs into an HTML table

Currently, I am working with a JSON data structure that contains nested dictionaries. My goal is to create an HTML table where each top-level key serves as a column in the table. The inner key-value pairs should be represented as a single text within cells ...

What is the best way to ensure a textarea remains expanded when the parent element is in focus?

I have successfully implemented a textarea box that expands upon click and retracts when it loses focus. However, I am facing an issue where if the textbox is already in expanded form, I want it to stay expanded if the user clicks anywhere within the cont ...

Struggling to Align NAV buttons to the Right in React Framework

My current Mobile Header view can be seen here: https://i.stack.imgur.com/CcspN.png I am looking to achieve a layout similar to this, https://i.stack.imgur.com/pH15p.png. So far, I have only been able to accomplish this by setting specific left margins, ...

Clearing the ui-grid after a button is clicked

Is there a method to clear all content from a ui-grid including filters, data, and columns? I want to reset the grid when a button is clicked in order to fetch new data with an HTTP request and display it using the same grid without refreshing the page. ...