Markers on the map are not receiving the necessary click event handlers

The block of code below is designed to place markers on a map. However, it seems that the add Listener event is not properly attached to each marker.

    var mapDiv = document.getElementById("google-map");
    var infoWindow = new google.maps.InfoWindow({
        content: 'test'
    });

    var map = new google.maps.Map(mapDiv);
    map.setCenter(new GLatLng(53.635784, 6.943359));
    map.setZoom(5);

    for (var i = 0; i < data.length; i++) {
        var dataMarker = data[i];
        var marker = new GLatLng(dataMarker.Latitude, dataMarker.Longitude);
        map.addOverlay(new google.maps.Marker(marker, {
            title: dataMarker.Name,
            html: dataMarker.HtmlAttributes[0]
        }));
        google.maps.event.addListener(marker, 'click', function () {                
            infoWindow.setContent(this.html);
            infoWindow.open(map, this);
        });            
    }

What mistake am I making here?

By the way, I am using Maps v2.

Answer №1

No event listener was assigned to the marker.

var marker = new GLatLng(dataMarker.Latitude, dataMarker.Longitude);

The marker is not a google.maps.Marker , but rather a google.maps.LatLng , and therefore it does not handle mouse events. This is because it is not a user interface element, but rather a JavaScript object.

Answer №2

You've successfully implemented event listeners that are likely associated with the last marker.

In order to correctly link the info window with the marker, it's advisable to create a separate function. The final part of your code should look like this:

    addEventListener(marker, infoWindow, map);
}

function addEventListener(marker, infoWindow, map) {
    google.maps.event.addListener(marker, 'click', function () {                
        infoWindow.setContent(marker.html);
        infoWindow.open(map, marker);
    });            
}

For further insights, check out An array of infoWindow in Google Maps API and the explanation on closures.

Answer №3

It seems that there is a combination of v2 and v3 code within that snippet, which may cause the entire thing to not function properly.

For instance, the usage of new google.maps.InfoWindow (v3) alongside GLatLng is problematic.

My recommendation would be to update the bootstrap on the page to v3 and remove any mentions of v2 objects (such as GLatLng). Ensure that you are loading the API correctly as shown below:

<script src="//maps.googleapis.com/maps/api/js?…"></script>

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

incorporate a new component in real-time

I need help with dynamically adding components to my container in AngularJS. I have a componentA that functions as a container, and I want to add multiple instances of componentB when a button is pressed. Currently, I can successfully add a single instanc ...

Determine whether a variable is defined following the keyup() event in jQuery

I am currently working on creating a registration form using the keyup() function in JQuery. For instance, when the input is correct, I assign it to a variable called txtuname. After pressing the register button, I need to ensure that all form variables ...

Using Symfony2 to send AJAX request data to a form rendering controller

I am facing an issue with a Symfony Form that I need to prefill based on the previously viewed record. The goal is to provide a way to modify the record data. I reach the form page through javascript and send an ajax request to the controller responsible f ...

Is there a way for me to retrieve the pageProbs that I have shared with a Component in _app.js?

Upon the loading of my website, I am fetching a large amount of data using getInitialProps. MyApp.getInitialProps = async (appContext) => { // Calls page's `getInitialProps` and fills `appProps.pageProps` const appProps = await App.getInitialProps( ...

Is it possible to set client-certificate as optional with Node SSL (using rejectUnauthorized: true does not achieve this)?

I have been exploring how to enable two-way SSL authentication in Node.js, following up on a previous thread: Enabling 2-way (client-authenticated) SSL in node.js? Now that I have successfully implemented client-authentication/2-way SSL, the next step is ...

When scrolling the page, the Circle Mouse Follow feature will dynamically move with your cursor

Hey everyone! I'm currently working on implementing a mouse follow effect, but I'm facing an issue where the circle I've created moves along with the page when scrolling, instead of staying fixed to the mouse. Any suggestions or tips would b ...

Bootstrap 4: Popper not found - ReferenceError in the script

After setting up Bootstrap 4 using Node and Gulp, I encountered an error when running the application: Uncaught ReferenceError: Popper is not defined So far, I've only utilized the Bootstrap grid system and have not delved into the Bootstrap JS fu ...

A guide to implementing div wrapping in HTML

I'm in the process of using flexbox on my website. I have 10 div elements that I want to wrap around each other closely without any gaps between them. My goal is to have "4" positioned to the right of "1", instead of creating a new row and moving dow ...

What is the best way to utilize an Angular service method from a controller?

As a newcomer to Angular, I have created an 'Employee Search' Service module. Let's take a look at the code: // Employee Search Service app.service('employeeSearchService', function($http, resourceServerAddress){ this.empList ...

Using Angular, we can assign an array iteration as the value for a dropdown option in

Following the controller logic: $scope.form_data = { day: 'Day' }; $scope.days = [ 'Day',1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30, 31 ]; In the html section: <select n ...

Having trouble capturing the 'notificationclick' event in the service worker when using Firebase messaging with Nuxt.js and Vue.js?

Experiencing difficulties in detecting events other than install, activate, or push in my firebase-messaging-sw.js. Notifications are being received and displayed, but I am unable to detect the event handler for notificationclick. When a firebase notificat ...

AngularJS Chrome Extension has been flagged as potentially harmful, despite the implementation of compileProvider.aHrefSanitizationWhitelist. This has resulted

I have previously shared this issue, however, the suggested solutions did not resolve it. Therefore, I am reposting with a more widely recognized solution: I am currently working on developing a chrome extension using AngularJS. In my base directive, I am ...

Step-by-step guide to aligning layout using material design in generator-gulp-angular

I am currently using generator-gulp-angular with angular-material-design and ui-router All views are loaded into index.html in the <div ui-view></div> element However, when I attempt to center the element with material design directives insid ...

Opting for "npm ci" over "npm install" for ensuring a consistent project setup

When working on a project where the package-lock.json is managed in source control to ensure consistency among all developers, there may be confusion surrounding the use of npm ci versus npm install. According to npm documentation, developers should utili ...

Jade fails to show image in route with parameter

Currently, I am utilizing express 4 and have images saved in the uploads directory. This is a snippet of my code: app.use(express.static(__dirname + '/uploads')); //This part works app.route('/') .get(function (req, res) { ...

Collecting information from form submissions, accessing data from the database, and displaying the results

I am currently working on a project using nodejs, express, and mongodb within the cloud9 IDE. My goal is to create a page with a form that allows users to input data, search for corresponding information in the database, and display that data on the same ...

Transferring ipywidgets to a web platform

I've developed a Python program in Jupyter Notebook that leverages the interact function from the ipywidgets module. interact(my_func, filter_by=filter_by_list, format_type=format_dict.keys()) I am looking for a way to share this interactive widget ...

Exploring the option of showcasing multiple json_encode data on a pie chart

Hey there! I'm currently utilizing Chart.js to generate a pie chart by retrieving data from the database: <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> <script> var ctx = document.getE ...

Express is having trouble providing data to React

Currently, I am delving into mastering the realms of React and Express. My ongoing project involves crafting a learning application that fetches data from MySQL and renders it visually for analysis. To kickstart this endeavor, I set up a basic express ser ...

How to toggle between two background colors in a webpage with the click of a button using JavaScript

I need help with a unique website feature. I want to implement a button that cycles between two different background colors (white and black) as well as changes the font color from black to white, and vice versa. My goal is to create a negative version of ...