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

What are some ways to enhance the speed of my canvas animations?

My code generates imagedata and places it in a canvas. However, when I expand the window size, the rendering slows down significantly. Is there a way to optimize this for smooth operation in fullscreen mode, even though it might seem naive? What would be ...

Ways to determine if the popupState component in Material UI is currently opened

I am currently utilizing PopupState and the Popover component to create a specific element. It is functioning properly, but I have a requirement to modify the icon displayed based on whether the popup is open or closed. Here is the code for my component: ...

When attempting to use Python's json.loads function, it encountered an issue with the error message: "simplejson.errors.JSONDecodeError: Invalid control character 'x00' at position 535 on line 1, column 536."

I am facing an issue while trying to load the contents of a json file line by line using the json.loads command. The error I encounter is as follows: "simplejson.errors.JSONDecodeError: Invalid control character '\x00' at: line 1 column 536 ...

I'm having trouble with AngularJS routes not functioning properly when accessed directly. I am using html5 mode in conjunction with

When accessing URLs directly in my Angular app either through the address bar or from external links, all routes default back to the home page. However, when navigating within the app, routes work as expected. I have come across similar issues on Stack Ov ...

The ajax response is returning the entire page's html code instead of just the text content from the editor

I've been working with CKEditor and I'm using AJAX to send the editor's content via POST method. However, when I try to display the response in a div, the HTML for the entire page is being returned instead of just the editor's content. ...

Ways to determine if an AngularJS modal is currently displayed

I am currently in the process of determining whether a modal is opened or closed. However, I keep encountering an error that says "cannot read property of open." To address this issue, I realize that I need to connect with $modal.open and retrieve the resu ...

There was a problem encountered when attempting to finalize the order in Softlayer

An exclusive solution was developed for the IBM dst team to conveniently place orders for storage from SoftLayer. Initial tests of the solution confirmed its efficiency, but a recent issue has arisen during the ordering process. Upon attempting to place a ...

Checking for null values using the "and/or" syntax

While reading an article on special events in jQuery, I came across a syntax that was unfamiliar to me: var threshold = data && data.threshold || 1 I have previously encountered the following: var threshold = data.threshold || 1 As far as I kno ...

When using Express, the XML response is returning an empty document

I'm experimenting with a simple API that returns XML response: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const libxmljs = require("libxmljs"); const PO ...

Image carousel with interactive buttons

I've taken over management of my company's website, which was initially created by someone else at a cost of $24,000. We recently made some edits to the slideshow feature on the site, adding buttons that allow users to navigate to corresponding p ...

Trouble with closing windows in the in-app browser on Android devices

Is there a method to successfully close the in-app browser? Despite window.close working on iOS devices, it is not effective on Android. I have experimented with alternatives like window.top.close and window.open("", "_self") window.close, but none have ...

The functionality of Intersection Observer causes text to appear over the header

Hey everyone, I've been working on a scrolling animation to make text appear when it's at least 50% visible. So far, I have an animated header with an Onscroll Event and Intersection Observer for the text. It's all working well, except for ...

Separating the rules for development and production modes in the webpack configuration file

I'm currently in the process of working on a front-end project using HTML. Within my project, I have integrated the Webpack module bundler and am utilizing the image-webpack-loader package for image optimization. However, I've encountered an issu ...

Create a form with two submission buttons along with a captcha verification system

I'm currently developing a booking page form that requires a unique functionality. I need a single form where clients can enter their information, followed by two submit buttons at the bottom. The first button should hold their reservation for 72 hour ...

Every time I attempt to execute this piece of code in "node.js", an error pops up

const express = require('express'); const request = require('request'); const bodyParser = require('body-parser'); const https = require('https'); const app = express(); app.use(express.static('public')); ...

Retrieve the property called "post" using Restangular

With the following code, I am fetching a list of 'postrows': $scope.postrows = {}; Restangular.all('/postrows').getList().then(function(data){ $scope.postrows = data; }); The returned JSON structure is as follows: { id: 1, post ...

Is there a way to incorporate the ::after or ::before pseudo-elements into an image tag?

While working on my project, I attempted to incorporate the ::after tag (I had used ::before as well) for an image within an img tag. However, I am facing difficulties as it doesn't seem to be working. Any advice or guidance would be greatly appreciat ...

What is the best way to organize and group messages in JavaScript in order to push them to a subarray?

Having trouble coming up with a name for this question, but here's the issue I'm facing: I currently have an array in PHP containing several entries. Array ( [0] => stdClass Object ( [sender_id] => 0 [me ...

Discovering the process to verify and obtain the outcome of an API request through jQuery Ajax

Seeking assistance in utilizing jQuery AJAX to access an API with a URL and parameters using the POST method. Specifically, I aim to determine the availability of delivery for a given Pincode on an e-commerce website. Any guidance on how to retrieve data f ...

Trouble With Ajax Submission in CakePhp: Issue with Form Serialization

In my attempt to utilize ajax for sending an array of objects along with serialized form data, I encountered a problem. The issue arises when I include the array in the ajax data along with the serialized form data. This results in the serialized form data ...