Tips for including markers on Google Maps once the map has finished loading:

Currently, I am developing a phoneGap application and going around my house to gather coordinates:

var locations = [
  {lat:123.12313123, lng:123.123345131},
  {lat:123.12313123, lng:123.123345131}
]

While referring to the documentation here, everything seems to be working perfectly. In a particular example, the script defer async is triggered when calling initMap(). This function sets up a single marker on the map, which displays accurately in Australia for me.

To start off, I create the map itself:

var map; // declaring it globally

function initMap() {
  var myLatLng = {lat: 39.909736, lng: -98.522109}; // center US

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 2,
    center: myLatLng
  });
}

This script generates the map successfully. Now, I want to loop through my list of coordinates like this:

// Note that the map has already been initialized at this stage
$(locations).each(function(i, item) {
          var marker = new google.maps.Marker({
            position: item,
            map: map,
            title: 'Route item ' + i
          });
        })

Unfortunately, this approach is not functioning as expected. I'm unable to call initMap() within a loop, and even if I could, it wouldn't work properly. Moreover, specifying a fixed number of coordinates beforehand isn't feasible since I need to wait until they are all collected. What could potentially be the issue with my current setup?

Answer №1

The issue here is related to scope. When you declare the map variable using var map, it creates a local variable named map within the initMap function. As a result, the global map remains uninitialized, causing your marker not to be placed on the map due to the undefined map variable passed to it. To resolve this, remove the var keyword and assign your new Map directly to the original global map variable outside the function:

var map; // declaring it as a global variable

  function initMap() {
    myLatLng = {lat: 39.909736, lng: -98.522109}; // center US

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 2,
      center: myLatLng
    });
  }

On a separate note, there seems to be some confusion regarding the async defer attributes in script loading. By using these attributes, you instruct the browser to delay fetching and executing a script until after the entire page has loaded. In the case of Google Maps API, when including the script URL, you can also specify a callback function to be invoked once the script has finished loading, like so: &callback=initMap.

Therefore, the browser loads the full page, awaits the script fetch, executes the Google Maps code, and finally calls the designated initMap function.

Answer №2

It looks like the issue may be that you have declared the map variable twice - once outside of the initMap function and once inside. This could result in the global map variable remaining as undefined. To fix this, remove the var before the assignment:

map = new google.maps.Map(document.getElementById('map'), {
      zoom: 2,
      center: myLatLng
    });

By making this change, you will now assign the map instance to the existing map variable outside of the function scope instead of creating a new variable that conflicts with the global one.

Remember, it's generally better practice to minimize the use of global variables whenever possible :)

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

javascript encounter surprise issue

While diving into my code, I encountered an error. $('.log').prepend('<div class="symbol sublog"> অনুগ্রহ করে একটি প্রতীক যুক্ত করুন (`~!@#$%^&*()_+-={}|[]\;:",./< ...

Android development offers the capability to create either Compound or Custom views that can incorporate two-way

I am looking to develop a unique Custom or Compound View in Android that combines multiple standard components and allows me to bind variables. Below is a brief example of the new control (view_custom.xml): <?xml version="1.0" encoding="utf-8"?> &l ...

The choices in the second dropdown menu will change based on the selection made in the first dropdown menu

Currently utilizing reactJS, I have the choices for two dropdown lists named categories and items. constructor(props) { super(props) } this.state = { categories: [ { "id": 1, "category_name": ...

Struggling with the lack of two-way data binding functionality in Kendo UI

Recently, I encountered a challenge with my kendo-dropdownlist component. Initially, I was fetching data from an API using the kendo-datasource and everything was working smoothly. However, as I started to implement multiple instances of the kendo-dropdown ...

Ways to assign a secondary color theme to the DatePicker widget

As someone who is new to exploring Material UI components, I encountered a roadblock while experimenting with different features. <TextField type="email" name="email" id="email" label="Email" variant="outlined" color="secondary" required /> <D ...

Error: Unable to locate module '@emotion/react' in 'E:frontend ode_modules@muistyled-engine' directory

I've been trying to import a box component from @mui/material/Box. After installing Material-UI 5 using npm i @mui/material, I encountered the error message Module not found: Can't resolve '@emotion/react' in 'E:\frontend&bsol ...

If the iframe's CSS source is updated, the parent's CSS source will also change

I'm currently working on a unique school project that involves creating multiple CSS styles for different views. <link rel="stylesheet" type="text/css" href="css/main.css" title="main" media="screen"> <link rel="stylesheet" type="text/css" h ...

What is the best way to assign a unique number to every div id that is generated?

I am currently using a django for loop to retrieve data from a query set. As the information is displayed, I would like to have each item wrapped in a div tag with a unique id that increments by 1 for every instance. Is there a way to achieve this directly ...

What is the best way to access the dimensions of a parent element in React with Hooks?

I am currently working on a new component and I am facing the challenge of obtaining the width and height of its parent <div>. Since all my components are functional ones using Hooks, the examples I found involving classes do not fit my case. Here i ...

Disable body scrolling on mobile devices in native browsers

When using the native browser on Samsung Galaxy S5 / S6, the following CSS code: body { overflow: hidden; } does not successfully prevent the body from scrolling. Is there a way to work around this issue? Edit: As mentioned below, one workaround is t ...

Tips for resolving the error message "TypeError: props.scoreboard.map is not a function" that only occurs after refreshing the page

I'm encountering an unusual problem while attempting to iterate over the response from my backend. Despite logging the response as an array, I still face issues similar to those where the response is not considered an array. I am passing the scoreboa ...

Modify the parent scope variable within an Angular directive that contains an isolated scope

Here is a directive implementation: <some-directive key="123"></some-directive> This directive code looks like this: angular.module('app').directive('someDirective', ['someFactory', '$compile', '$ ...

What is the best method for retrieving options based on a data attribute?

All <option> elements in a <select> have data-value attributes set (example provided below). Upon page load, I must find and iterate through the values of all <option> elements to pick out one that suits further processing. We plan on us ...

What could be causing Highchart to return the error message "Typeerror: undefined variable byte"?

My current project involves creating a graph using highchart and updating values every second. I am also working on displaying data in Mb, Kb, and Gb format on the graph by developing a function to convert byte values. Here is a snippet of my code: // hi ...

Tips for efficiently finding and comparing text within the results generated by a for loop in Angular/Javascript

In my XML data, I have extracted all the tag names using a for loop and some other logic. Now, I am looking to find the word 'author' from the output values that are displayed in the console during the loop. If any of the output values match &apo ...

Android device experiencing difficulties in receiving broadcast messages

Despite registering the "SMS received event" for the broadcast receiver in my app, I am facing an issue where the onReceive method of the broadcast receiver is not triggered when I launch the app and send a message to the emulator. Below is the code snipp ...

What is the best method for removing a class with JavaScript?

I have a situation where I need to remove the "inactive" class from a div when it is clicked. I have tried various solutions, but none seem to work. Below is an example of my HTML code with multiple divs: <ul class="job-tile"> <li><div ...

Obtaining the contents of a local directory with JavaScript

Currently, I am attempting to access the contents of a local folder using JavaScript. Despite my efforts with the Filesystem API, an error is consistently appearing: DOMException: It was determined that certain files are unsafe for access within a Web app ...

Perform two separate sets of asynchronous calls with a pause in between each series

I am in need of creating a sequence of AJAX requests to different URLs, and only after all of them have completed I need to initiate another set of calls. This is the code I have written so far: (function (delay) { var tasksToDo = 10, currentTask ...

I'm having trouble launching Clinic.js, any suggestions on what steps I should take next?

When starting up your application, use the following command: clinic doctor --on-port 'autocannon -m POST localhost:8000/users/register' -- node dist/main.js If you need help, check out the Clinic.js Doctor - v9.2.0 log. The clinic doctor tool ...