Refresh the information displayed in the open Google Maps Infowindow

Experimenting with extracting JSON data from a bus tracker website and integrating it into my own version using Google Maps. Although not as visually appealing, I'm struggling to update an infowindow while it remains open. Despite finding some examples online, nothing seems to work as desired. While I've successfully managed to update and move the markers with each new dataset, the infowindows aren't behaving the way I want them to. What I aim for is to click on a marker and have the infowindow display additional information, such as the vehicle's speed. As the JSON updates and downloads, the marker shifts position and I expect the content of the infowindow to reflect the new speed in real-time without closing.

As an added challenge, I aspire to implement a toggle feature for the runbuses() function using a checkbox. When unchecked, this option would halt the download of new JSON data. However, figuring out how to achieve this functionality still eludes me. It has been quite enjoyable delving into Java and exploring these complexities!

function runbuses() {
  setInterval(function() {

    loadbus(map)

  }, 5000);
}


function loadbus(map) {

  //howardshuttle.com

  $.ajax({
    url: "http://www.howardshuttle.com/Services/JSONPRelay.svc/GetMapVehiclePoints",
    data: 'ApiKey=8882812681',
    dataType: 'jsonp',
    jsonp: 'method',
    async: false,
    cache: false,
    success: function(obj) {

      for (var i = 0; i < obj.length; i++) {

        var image = {
          url: setumicon(obj[i]['Heading']),
          anchor: new google.maps.Point(20, 20),
          scaledSize: new google.maps.Size(40, 40)
        }

        console.log(obj[i].Name);

        if (umbuses.hasOwnProperty(obj[i].Name)) {
          umbuses[obj[i].Name].setPosition(new google.maps.LatLng(obj[i].Latitude, obj[i].Longitude));
          umbuses[obj[i].Name].setIcon(image);

          console.log(Math.round(obj[i]['GroundSpeed']));
          console.log('has prop');

        } else {
          var hover = obj[i].Name;
          console.log('new');
          var image = {
            url: setumicon(obj[i].Heading),
            anchor: new google.maps.Point(20, 20),
            scaledSize: new google.maps.Size(40, 40)
          }

          marker = new google.maps.Marker({
            position: new google.maps.LatLng(obj[i].Latitude, obj[i].Longitude),
            map: map,
            icon: image,
            title: String(hover)
          });

          google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {

              if (activeInfoWindow != null) activeInfoWindow.close();

              uminfo.setContent("<p>" + obj[i]['Name'] + "<br />" + umFindroute(obj[i]['RouteID']) + "<br />" +
                "Speed: " + Math.round(obj[i]['GroundSpeed']) + " mph" + "</p>");

              uminfo.open(map, marker);
              activeInfoWindow = uminfo;

            }
          })(marker, i));

          umbuses[obj[i].Name] = marker;
          console.log(umbuses);

        }

      }


    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert("some error");
    }

  });

}

Answer №1

To update the content of an open InfoWindow, assign an id to the HTML element you wish to change within it and use HTML DOM manipulation to make the necessary modifications.

uminfo.setContent("<div id='infowin'><p>" + obj[i]['Name'] + "<br />" + umFindroute(obj[i]['RouteID']) + "<br />" +
            "Speed: " + Math.round(obj[i]['GroundSpeed']) + " mph" + "</p></div>");

Subsequently, if the InfoWindow is currently displayed, the following steps can be implemented:

document.getElementById('infowin').innerHTML = "<p>" + obj[i]['Name'] + "<br />" + umFindroute(obj[i]['RouteID']) + "<br />" +
            "Speed: " + Math.round(obj[i]['GroundSpeed']) + " mph" + "</p>";

Code Snippet:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var marker = new google.maps.Marker({
    map: map,
    position: map.getCenter()
  });
  var infowindow = new google.maps.InfoWindow({
    content: "<div id='infowin'>original content</div>"
  });
  google.maps.event.addListener(marker, 'click', function(evt) {
    infowindow.open(map, marker);
  })
  google.maps.event.trigger(marker, 'click');
  setInterval(function() {
    marker.setPosition(google.maps.geometry.spherical.computeOffset(marker.getPosition(), 100, 90));
    document.getElementById('infowin').innerHTML = "<b>Time</b>:" + Date() + "<br>" + marker.getPosition().toUrlValue(6);
  }, 5000);

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map_canvas"></div>

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

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

Is it possible to incorporate a next.js image onto the background design?

I've encountered an issue while attempting to create a fixed background image with a parallax effect using Tailwind CSS and Next.js Image. If you need to see an example of this in action, check out this Template Monster theme. Here's the code s ...

Efficient initialization process in Vue.js components

Upon initialization of a component, the data callback is executed as follows: data(){ return { name: myNameGetter(), age: myAgeGetter(), // etc... } }, Following that, a notification is sent to a parent component regarding ...

vue.js libs requiring "new ..." are being scolded by eslint for their misspelling

When working with Vue libraries, such as Swiper, that require the use of 'new …' in the script section, I encounter ESlint errors no matter how I try to write it. Even though 'new ...' works perfectly fine in the frontend, ESlint cont ...

Is there a way to simulate a click event within a Jasmine unit test specifically for an Angular Directive?

During the implementation of my directive's link function: $document.on('click.sortColumnList', function () { viewToggleController.closeSortColumnList(); scope.$apply(); }); While creating my unit test using Jasmine: describe(&apo ...

JavaScript interval setting multiples

In my current situation, I have implemented a setInterval based code that continuously checks the value of an AJAX call response. Here is how it looks: var processInterval = setInterval(function () { var processResult = getVideoStatus(data.file_name) ...

What is the reason behind V8's perplexing error notification?

When running this code on Chrome or Node (v8), an error message is displayed: Uncaught TypeError: f is not iterable function f(){} f(...undefined); Why is such an ambiguous error message generated in this case? Does it really have nothing to do with ...

Button with a Jquery icon design

Hello, I am currently working on implementing an icon button that can collapse and expand text. Although I have successfully implemented the logic for collapsing/expanding, I am facing difficulties in creating the actual icon button. The theme I am require ...

What is the process for assigning an id to a div in order to make comparisons in React?

After attempting to assign an id to a div for comparison, an error was thrown indicating that "id is not defined". Here is the data: https://i.sstatic.net/PZjDk.png And here is the function: https://i.sstatic.net/y4MEB.png I attempted to add an id attri ...

Does anyone know if it's feasible to return a value from PHP to an HTML form without relying on JavaScript?

Currently, I am in the process of learning how to create a basic web form. My goal is to develop an HTML web form that sends a number to PHP and then displays the number in another text field without refreshing the page. After doing some research online, ...

Emphasize the designated drop zone in Dragula

Incorporating the Dragula package into my Angular 2 project has greatly enhanced the drag-and-drop functionality. Bundling this feature has been a seamless experience. Visit the ng2-dragula GitHub page for more information. Although the drag-and-drop fun ...

When attempting to execute a function within another function in JavaScript, a ReferenceError is triggered

I recently developed a straightforward app that utilizes the Google Drawing Library (https://developers.google.com/maps/documentation/javascript/examples/drawing-tools) to allow users to draw circles on a map. The first circle represents the source locatio ...

Invoke a function within a distinct context using a loop

I'm currently using a script where a function is called for each element on the page. It works fine when I make separate function calls, but if I try to call the function with a unique selector, it doesn't work as expected. Is there a way I can c ...

Script for converting Fixed Positioned Elements to Static

I am frequently finding that elements on web pages are causing disruptions due to their fixed positioning. I am exploring ways to disable the position: fixed CSS rules on any website I visit. To address this issue, I have developed a userscript specifical ...

Contrast among 17-digit timestamps

Currently, I am dealing with timestamps in Node.js that are in the UTC+02:00 timezone. I am trying to calculate the time difference between two timestamps, each consisting of 17 digits. For instance, I have two timestamps: 20180712080000000 (YYYYMMDDHHmmss ...

Is it possible to transfer data from a JavaScript file to the Express server without relying on a form submission?

As a newcomer here, I apologize if I overlook any best practices. Currently, I am in the process of developing a sudoku game using express, JavaScript, HTML, and mongoDb. My current challenge involves setting up a statistics system. My goal is to send da ...

Struggling to connect to Node/Express Backend

I have developed a backend service using Node and Express. However, I am encountering an issue where none of the routes for this application are being accessed. Despite expecting to see an error message in the console if the routes were misconfigured, no s ...

Search through a group of distinct objects to find arrays nested within each object, then create a new object

I am currently working with objects that contain arrays that I need to filter. My goal is to filter an array of classes based on category and division, then return the new object(s) with the filtered arrays. Below is a representation of the JSON structure ...

Is it feasible to deliver a push notification on iOS without utilizing the "alert" attribute in a JSON payload?

Is there a way to send a JSON format without including the "alert" attribute and still have the notification appear? I've attempted to remove the alert attribute, but it seems to prevent the notification from showing up. Any suggestions on how to hand ...

Attempting to establish both the minimum and maximum time date in a jQuery datepicker across two separate inputs

I've been working on a project for my classes that requires setting minimum and maximum dates for two input fields. The first input should allow dates from now to 12 months in the future, while the second input should be restricted to dates picked wit ...