Displaying infowindow pop-ups on random markers on Google Maps every 3 seconds

Here lies the challenge.

  • I am tasked with creating a Google map that displays multiple markers.
  • Each marker must have a unique info window with distinct content. Upon opening the website, an info window randomly appears on one of the markers after 3 seconds.
  • The info window then closes, only to reappear on another random marker after an additional 3 seconds, and so forth.
  • Additionally, the info window should automatically display without the need to click on the marker.

What tools or techniques are necessary to accomplish this task?

Answer №1

Setting up a map with multiple markers and triggering click events on them using setInterval is a simple process. First, create a map with the markers stored in an array. Then, utilize setInterval to automatically click on each marker.

Here is the HTML code:

<div>
    <div id="map" style="width: 500px; height: 400px;"></div>
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
</div>

And here is the JavaScript code:

//Define the markers
var locations = [
    [
        "New Mermaid",
        36.9079, -76.199,
        1,
        "Georgia Mason",
        "",
        "Norfolk Botanical Gardens, 6700 Azalea Garden Rd.",
        "coming soon"
    ],
    [
        "1950 Fish Dish",
        36.87224, -76.29518,
        2,
        "Terry Cox-Joseph",
        "Rowena's",
        "758 W. 22nd Street in front of Rowena's",
        "found"
    ],
    // Add more markers here...
];

// Set up the map
var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: new google.maps.LatLng(36.8857, -76.2599),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var markers = [];
for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
    });
    markers.push(marker);
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infowindow.setContent(locations[i][0], locations[i][6]);
            infowindow.open(map, marker);
        }
    })(marker, i));
}
var i = 0;
setInterval(function() {
    if (i == markers.length) i = 0;
    google.maps.event.trigger(markers[i], 'click');
    i++;
}, 3000);

Demo for sequential order: http://jsfiddle.net/lotusgodkk/pGBZD/153/

Demo for random order: http://jsfiddle.net/lotusgodkk/pGBZD/154/

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

Adjust the size of the mouse cursor in real time

I'm currently in the process of developing a project where I want to create a web application with a mouse cursor that appears as a circle with a customizable radius, which can be altered by the user. The main requirement is for this custom cursor to ...

Deliver varied asset routes depending on express js

I have a situation where I am working with express routes for different brands. My goal is to serve two separate asset directories for each brand route. One directory will be common for all brand routes, located at public/static, and the other will be spec ...

What is the best way to measure the timing of consecutive events within a web browser, utilizing JavaScript within an HTML script tag?

Currently delving into the realm of JavaScript, transitioning from a Java/Clojure background, I am attempting to implement a basic thread-sleep feature that will display lines of text on the screen at one second intervals. Initially, I considered using t ...

Exploring the process of retrieving outcomes from Node.js within a Knockout ObservableArray

Below is the Node.js code snippet I have: var http = require('http'); var port = process.env.port || 1337; var MovieDB = require('moviedb')('API KEY'); MovieDB.searchMovie({ query: 'Alien' }, function (err, res) { ...

Trouble encountered when implementing setInterval in Next.js

While working on a progress bar component in Next.js and tailwind.css, I used JavaScript's setInterval() function for animation. Below is the code snippet: import React, { useState } from "react"; const ProgressBar = () => { let [progress, setPr ...

I am having trouble retrieving the content-length from the response headers within the app.use() middleware function

Can anyone help with retrieving the content-length from response headers within the app.use() middleware function? const app = express(); app.use((req, res, next) => { // Need to find a way to access content-length of res console.log("co ...

What is the implication when Typescript indicates that there is no overlap between the types 'a' and 'b'?

let choice = Math.random() < 0.5 ? "a" : "b"; if (choice !== "a") { // ... } else if (choice === "b") { This situation will always be false because the values 'a' and 'b' are completely disti ...

What is the best way to navigate back to the previous state in reactjs?

I have implemented a sidebar component with its initial state set to false in order to hide the block until a user interacts with the hamburger icon. Once clicked, the state changes to true and displays the sidebar menu. However, I am facing an issue whe ...

"Learn how to convert basic input fields into user-friendly Bootstrap input groups using the power of jQuery

Is there a way to use jQuery to convert my basic input field into a bootstrap input-group like the one shown below? This is how I created the input: <div class='input-group date' id='ff'> <input type='text' class= ...

Solving the CORS issue with Vue, Axios, and the Google Maps Place API

After reviewing the other responses, it seems that my question remains unanswered. Environment NodeJS 12.19.0 VueJS 2.6.10 Axios 0.15.3 Current Axios configuration: axios.defaults.headers.common['Authorization'] = store.apiKey axios.defaults.he ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...

Execute the script before the Vue.js framework initiates the HTML rendering

In order to determine if the user is logged in or not, and redirect them to the login page if they are not, I am looking for a way to check the user's login status before the HTML (or template) loads. I have attempted to use beforeCreate() and variou ...

A continuous jQuery method for updating select option values

I'm currently working on a form and using jQuery to make some alterations. The form consists of multiple select elements, and I want to change the value of the first option in each of them. However, as the form allows for dynamic addition of new selec ...

What is the reason behind only the final input value being shown on the screen?

I'm encountering an issue with my input fields. I have a total of five input fields. After filling all of them and clicking the button to display them on the screen, only the last one I entered is shown in all places... (let me know if this explanatio ...

retrieve: add elements to an array

I'm having trouble identifying the issue here. I am fetching some json data (using a text file) and trying to push it into an array in the global scope. Even though I iterate over the json and push entries to the array, when I log it out, it appears e ...

Nested components knockout knockout knockout! The $(document).ready() function fires off before the nested component is even loaded

I am faced with a situation where I have multiple nested knockout components in my code: <component1> <component2> .... </component2> </component1> The issue here is that while component1 is custom-made by me, component2 ...

Tips for avoiding multiple function calls in React JS when a value changes

How can I avoid multiple function calls on user actions in my demo application? I have tabs and an input field, and I want a function to be called when the user changes tabs or types something in the input field. Additionally, I need the input field value ...

Top strategies for managing fixed datasets

Imagine having a dataset containing country names and their corresponding phone prefixes, like so: var countryPhonePrefixes = [ { 'name': 'Germany', 'prefix': '+49' }, { 'nam ...

Error: The function `this.xhr_.upload.addEventListener` is not supported in Firebase Storage

Having some trouble with file uploads. Small files work fine, but when it comes to larger ones I keep getting this error: this.xhr_.upload.addEventListener is not a function. I'm currently using vue.js along with the firebase 6.1.0 npm package. Th ...

Choosing only those elements that are not children of parents with a specific class by utilizing the `.not()` method

I am attempting to target all elements having the class .select that are nested somewhere within the DOM tree. The only condition is that these elements should not have any ancestors with the class .forbidden. This means it will not detect any elements ...