I'm having trouble with Google Map InfoWindows not displaying when clicked within a loop

I'm facing an issue where the info window on Google Map API doesn't open on click within a loop, although all info windows show with an outside click event.

var map;
function initMap() {
    var mapProp = {
       center: new google.maps.LatLng(-22, 133),
       zoom: 4,
       mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map'), mapProp);
}
var request = new XMLHttpRequest();
request.open('GET', 'https://...', true);
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        // Success!
        var data = JSON.parse(request.responseText);
        appendData(data.data);
        console.log(data, "Data received");
    } else {
        // We reached our target server, but it returned an error
    }
};
request.onerror = function() {
    // There was a connection error of some sort
};
request.send();
function appendData (data) {
    var markers = [];
    for (var i = 0; i < data.length; i++) {
        var pos = new google.maps.LatLng(data[i].Latitude, data[i].Longitude);
        markers[i] = new google.maps.Marker({
            position: pos,
            map: map,
            icon: '//...icon.png'
        });
        var infowindow = new google.maps.InfoWindow({
            content: data[i].Name
        });
        //infowindow.open(map, markers[i]); - this shows all infowindows..
        //There seems to be a problem with this click event
        google.maps.event.addListener(markers[i], 'click', function() {
            infowindow.open(map, markers[i]);
        });
    }
};

Answer №1

All set, figured it out. Added description and id to markers and used setContent for click event triggering this

markers[i] = new google.maps.Marker({
                position: pos,
                map: map,
                icon: 'icon.png',
                description:"<div style='text-transform:uppercase;'><h6 style='color:red'>" + data[i].Name + "</h6>" + data[i].Description + "</div>",
                id: i
});
google.maps.event.addListener(markers[i], 'click', function () {

                infowindow.setContent(markers[this.id].description);
                infowindow.open(map, this);
});

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

Ensuring that the text in the Bootstrap navbar is responsive for all screen

Yesterday, I inquired about how to modify my navbar menu to switch from horizontal to vertically arranged depending on layout. However, I've noticed that the responsiveness is not consistent when adjusting the window size. Is there a way to ensure my ...

Enhancing Website Performance with Vue.js 2.0 Lazy Loading

I'm attempting to implement Lazy Loading for my components in Vue.js 2.0 (within a Laravel 5.3 project). As per the guidelines, I should proceed like this: Vue.use(VueRouter); const Forum = resolve => require(['./Components/Forum/Forum.vue& ...

Request to convert jQuery Ajax code into Vanilla JavaScript code

Are there any vanilla JavaScript alternatives available for the code snippet below? function verifyEmail() { var apiUrl = "https://apilayer.net/api/check?access_key=c5118f1f9827f42a5fc4b231932130a8&email=" + document.getElementById('email&apos ...

Send a pair of values using a set of two parameters

My current code is currently passing only one parameter value. However, I would like to modify it to pass two values with two parameters. This is my current code: <script> function getfilter(str){ document.getElementById("result"). ...

Enhance your website with a dynamic dropdown feature using Javascript and Bootstrap 5, allowing buttons to respond

Currently, I am experimenting with Javascript to dynamically incorporate elements into a Bootstrap 5 dropdown. To guide me, I referred to the relevant documentation which can be found here (https://getbootstrap.com/docs/5.0/components/dropdowns/#menu-items ...

X-editable does not verify if the checklist values are checked

Hello everyone, currently I am working on a Laravel project where I have implemented the X-editable library for inline editing functionalities. I am facing an issue with updating a many-to-many relationship table (pivot table) and I am trying to use the X- ...

How can I retrieve the path to a specific subnode using Javascript/JSON?

What is the best way to obtain a JSON path that leads to a specific child node within an object? For example: var data = { key1: { children: { key2:'value', key3:'value', key4: { ... } ...

What is the best way to stop a series of Ajax promises from continuing?

Managing multiple ajax requests that are dependent on each other can be tricky, especially when you need to stop the chain if one of the requests returns false. Check out this sample code snippet below: // Implementing a promise chain return this.getBan ...

Retrieving Data from Vue JS Store

I am fetching value from the store import {store} from '../../store/store' Here is the Variable:- let Data = { textType: '', textData: null }; Upon using console.log(store.state.testData) We see the following result in the cons ...

Jasmine's spyOn method in Angular does not impact functions within the factory

Initially, my Controller looks like this: login.controller.js: angular.module('app').controller('LoginController', function($scope,UserService,$location) { $scope.submit = function() { UserService. ...

Tips for ensuring a document stays at the top of my collection when performing an update

Whenever I make changes to a document, it always ends up at the bottom of my collection. Is there a way to prevent this from happening? try { await Card.update({_id: fixedUrl}, {$push:{'comments': data}}) } catch (err) { console.log(err ...

Tips for incorporating an unordered list inside a list item

<li class="cate-item"> <button class="cate-label" >item 1 </button> <ul class="sub-categ"> <li> sub item 1</li> <li> sub item 2</li> <li> sub item 3</li ...

This error message 'React Native _this2.refs.myinput.focus is not a function' indicates that

When working with React-Native, I encountered a specific issue involving a custom component that extends from TextInput. The code snippet below demonstrates the relevant components: TextBox.js ... render() { return ( <TextInput {...this.props} ...

How can Ext JS 4 handle the transmission of multiple metaData to support multiple dynamic grids by utilizing a single JSON file?

Looking to create multiple grids on a single panel using an accordion layout? I'll be dynamically generating all the grids based on metaData in JSON and handling metachange listener events on my store to reconfigure the grid. But here's the quest ...

Creating a function that counts the number of times a button is clicked

I want to have the "game" button appear after the user clicks the "next-btn" 2 times. Once the multiple choice test has been completed twice, I'd like the game button to show up and redirect the user to a separate HTML page called "agario.html." I&ap ...

What is the best way to send a distinct identifier using JavaScript or PHP?

I am looking for a way to replace "INSERT+ORDER+ID" with a unique ID when a user clicks on our "Request Information" button to improve visitor tracking. Can anyone provide guidance on how to achieve this? Your assistance is greatly appreciated, thank you ...

I'm having trouble setting up Stripe Elements in PHP. It seems like there's a communication issue between my PHP code and my JS

New to setting up Stripe Elements, I've followed the documentation closely. Installed the necessary JS modules, included the Stripe API, and connected it to the Stripe JS. In my index.php file, PHP script is at the top with HTML and JavaScript below i ...

I believe there may be a gap in the communication between TypeScript, JavaScript, Angular, Nginx, Alpine, and Docker within the network using Nginx. I am

After transitioning to Docker in order to create a virtual network to mimic a real network (using a bridge type with DNS that resolves the FQDN correctly to the corresponding IP), I encountered the following errors in the console.log - no data is being dis ...

Adjusting the width of the container <div> will automatically resize the inner <div> to match

I have a main container element. .wrapper{ border:1px solid blue; position:relative; top:20%; left:30%; height: 300px; width: 350px; } When I adjust the width of the parent container, the child box does not reposition itself accor ...

Why are there red squiggly lines appearing on properly written JavaScript code in Visual Studio Code?

Recently, I've been encountering a frustrating issue with irritating red squiggly lines appearing under my import statement. Despite the fact that the code functions perfectly and everything operates as anticipated, these lines continue to bother me. ...