The array of markers in the Google Maps API 3 has not been defined

Trying to manipulate markers on a Google map using data from an XML file is proving challenging. I aim to create and store the markers in an array.

markerArray[fzg] = marker;  

However, when attempting to update the positions of these markers based on new data, I encounter an issue where my moveMarker function displays "markerArray is undefined."

I have been unable to pinpoint the exact source of the problem within the code snippet provided:

<!DOCTYPE html >
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title></title>
<link href="swu.css" rel="stylesheet" type="text/css">
<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
</head>

<body>

<div id="map"></div>

<script type="text/javascript">

function initialize() {
    //map
    map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(48.393866111111, 9.9770183333333),
        zoom: 16,
        mapTypeId: 'roadmap'
        });

    //traffic
    var trafficLayer = new google.maps.TrafficLayer();
    trafficLayer.setMap(map);
}

markerArray = [];

function createMarkers () {

            //for testing without XML file
            // create for every i 1 marker

            for (var i = 0; i < 1; i++) {

                var pos = new google.maps.LatLng(
                48.393866, 9.977018);

                var marker = new google.maps.Marker({
                    map: map,
                    position: pos,
                });

                marker.setMap( map );

                //store marker in the array with index i
                markerArray[i] = marker;

          } // end for

          moveMarker(map, markerArray);

} // end createMarkers()


function moveMarker(map, markerArray) {

        for (var i = 0; i < 1; i++) {

        //move marker with index i on the map   
        //console says following markerArray is undefined

        markerArray[i].setPosition(new google.maps.LatLng(48.393860, 9.9770199));

        }
    }

initialize();
createMarkers();
setTimeout(moveMarker(), 2500);
</script>



</body>
</html>

Here's the CSS file used for styling:

html, body {
    height: 100%;
    font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#map {
    width: 100%;
    height: 100%;
}

Answer №1

When you call the second function, it requires two parameters:

moveMarker(map, markerArray);

However, the function is actually defined with only one parameter:

function moveMarker(map) {

As a result, moveMarker() is searching in a broader context for markerArray and encountering an undefined variable.

Answer №2

You have invoked moveMarker without any arguments:

setTimeout(moveMarker(), 2500);

Upon execution, markerArray is undefined. The function signature should be as follows:

function moveMarker(map, markerArray)

To rectify this issue, you can modify the code snippet like so:

setTimeout(function() {
  moveMarker(map, markerArray)}, 
  2500);

Here's a revised code snippet:

function initialize() {
  //map
  map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(48.393866111111, 9.9770183333333),
    zoom: 15,
    mapTypeId: 'roadmap'
  });

  //traffic
  var trafficLayer = new google.maps.TrafficLayer();
  trafficLayer.setMap(map);
}

markerArray = [];

function createMarkers() {

    //for testing without XML file
    // create for every i 1 marker

    for (var i = 0; i < 1; i++) {

      var pos = new google.maps.LatLng(
        48.393866, 9.977018);

      var marker = new google.maps.Marker({
        map: map,
        position: pos,
      });

      marker.setMap(map);

      //store marker in the array with index i
      markerArray[i] = marker;

    } // end for

    moveMarker(map, markerArray);

  } // end createMarkers()

var increment = 0.001;

function moveMarker(map, markerArray) {

  for (var i = 0; i < 1; i++) {

    //move marker with index i on the map   
    //console says following markerArray is undefined
    var position = markerArray[i].getPosition();
    console.log("move marker " + position.toUrlValue(6));
    markerArray[i].setPosition(
      new google.maps.LatLng(
        position.lat(), (position.lng() + increment))
    );
  }
  // markerArray[i].setPosition(new google.maps.LatLng(48.393860, 9.9770199));

}


initialize();
createMarkers();
setInterval(function() {
  moveMarker(map, markerArray)
}, 2500);
html,
body {
  height: 100%;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
#map {
  width: 100%;
  height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></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

Apply a specific class using JavaScript/jQuery when a user selects a specific timezone from the user interface

Currently, I am coding in HTML with the code below extracted from this website link. The listings under timezone ET are all correct as they align with the accurate dates; however, for other timezones (PT, MT, CT, AT, NT) some shows seem to be on incorrect ...

Filter an array of objects by the integer property of the objects

Check out my object below. class TicketsCellModel: NSObject { var title: String? var text: String? var price: String? var tintColor: UIColor? var quantity: Int? } Ready for some random data? var ticketCellModels: [TicketsCellModel] ...

Remove webpack functions from the bundle

After following a comprehensive tutorial on bundling files with webpack and some additional online research, I successfully created a configuration file that organizes the modules in my library into the specified structure: dist/node/weather.min.js dist/we ...

Adjusting AngularJS scroll position based on key presses

I am currently working on an autocomplete feature using AngularJS. I seem to be experiencing a problem with the scrollbar behavior. In the interactive gif provided, you can observe that the scrollbar remains stationary when navigating with the arrow keys. ...

Storing a Vue JS component as a string in a variable and displaying it using that variable

I am currently working on a project where I need to implement the following code snippet: <template v-for="(element, k) in place.data.content"> <data_elements[element.name].component></data_elements[element.name].component> </te ...

Error: JSON key data not present in rendering

Here is a JSON string I am working with: {"{\"nodeName\":\"abc\"}":[{"url":"abc","status":true},{"url":"abc","status":true}]," {\"nodeName\":\"pqr\"}":[{"url":"abc","status":true},{"url":"abc","status":true}]} ...

Expanding the capabilities of the JQuery submit function

Within my web application, I find myself working with several forms, each possessing its own unique id. To streamline the process, I decided to create a custom handler for the submit event in my JavaScript file: $('#form-name').submit(function(ev ...

Mastering the art of creating functions using JavaScript

Just starting out on this, and looking for some help. I have set up a jsfiddle http://jsfiddle.net/JustJill54/GDVt6/ where the visibility of name and email fields can be toggled based on the selection of yes or no in an anonymous drop-down. I also wrote a ...

Having issues with validating a form using Yup for a Checkbox input?

My form is built using mui, formik, and yup. If the input fields are empty (e.g. "surname") after clicking the submit button, an error is displayed. However, the issue arises when the checkbox for Terms of Service isn't checked as no error shows up. ...

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...

Tips for sending values via props to a different component and the common error message: "Consider using the defaultValue or value props instead of setting selected on the <option> element"

Currently, I am attempting to pass the selected value using the prop: handle state change, but encountering two errors. Error 1 : Instead of setting selected on <option>, use the defaultValue or value props. Error 2 : A property 'active' ...

Passing input parameters from a jQuery dialogue box to a handler file (.ashx) in ASP.NET: A step-by-step guide

Hey everyone! I've set up a jQuery dialog box with two input fields as shown below: <div id="dialog" title="Login"> <form action="" method="POST" id="loginForm"> Username: <input type="text" name="username" /><b ...

Mastering Arrays in C Programming

The expected result from the code should be displayed as: 6.30 1.25 2 14.40 1 I've noticed some errors in the printf statements, but I'm having trouble rectifying them. This is the code snippet: #include<stdio.h> #define SZ 5 int main ...

Ways to aggregate the values from collections.frequency to identify duplicate words in Java

for(String temp : uniqueSet) { if((Collections.frequency(list, temp)) >= 2) { System.out.println(temp + "=" + (Collections.frequency(list, temp) -1)); } } I'm struggling to find the total count of repeated words in my text file. I ...

Transmit the JavaScript array via AJAX to PHP server

Is it possible to transfer a JS array created using the .push function to another PHP file? I have included the code snippets for the two files involved, game.js and gallery.php. In Game.js: imgarray.push({"img_name": img_name,"x": x_value,"y": y_value,"w ...

Guide on how to retrieve the parent element's number when dragging starts

Within my div-containers, I have a collection of div-elements. I am looking to identify the parent number of the div-element that is currently being dragged For example, if Skyler White is being dragged, the expected output should be "0" as it is from the ...

Dynamic addition of a Javascript script to a component leads to malfunctioning

I am facing an issue with a dynamically created component where I added the script tag, but unfortunately, the code inside is not functioning properly. Despite trying multiple solutions, none seem to work for me. Could you please review the code? https:// ...

Code snippet in webpage body

Hey there, I could really use some assistance: I currently have the following: A) Login.html B) Documentation.html C) Base.html Within the login page, there is a form with fields for User and Password. In Documentation, there are links to various folder ...

What is the best way to access the names of iframes and frames within window.length?

I am currently working on a project with numerous frames. While I am aware that using window.length will provide the number of "child browsing contexts", like frames and iframes, I am unsure how to access a list of these frames and view their names. Is t ...

Accessing data from arrays asynchronously using JavaScript

Update I have included actual code below, in addition to the concept provided earlier. Here is the async array access structure I am trying to implement: for (p = 0; p < myList.length ; p++){ for (k = 0; k < RequestList.length; k++){ i ...