The final marker is consistently used by the click event

Currently exploring the Google Maps API for the first time and facing a challenge in Rails when trying to add a click event for each marker. I am looping through the team_locations model to extract latitude and longitude data in order to set up markers. I have placed the event listener inside the loop to associate it with each marker, but whenever I click on any marker, the map always zooms in and centers on the last item listed in my team_locations table. I suspect this issue is arising because my marker variable gets constantly updated, pointing to the last item in the list. Any suggestions for effective workarounds?

<script>
    function initialize() {
        // Center the map on the US
        var center = new google.maps.LatLng(37.09024, -95.712891);

        var mapOptions = {
            zoom: 4,
            center: center,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map-canvas"),
                mapOptions);

        <% @team_locations.size.times do |i| %>
            var teamLatLng = new google.maps.LatLng(<%= @team_locations[i].latitude %>, <%= @team_locations[i].longitude %>);
            var marker = new google.maps.Marker({
                position: teamLatLng,
                map: map,
                label: "<%= @team_locations[i].team_id %>"
            });
            google.maps.event.addListener(marker,'click',function() {
                map.setZoom(8);
                map.setCenter(marker.getPosition());
            });
            marker.setMap(map);
        <% end %>


    }
    google.maps.event.addDomListener(window, "load", initialize);
</script>

Answer №1

Look at this simple example using pure javascript. It's focused on managing markers and adding event listeners efficiently by storing them in an array.

<!DOCTYPE html>
<html>
  <head>
    <title>Custom Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <script src="https://maps.googleapis.com/maps/api/js"></script>     
    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map-container {
        width: 100%;
        height: 400px;
      }
    </style>
  </head>
<body>
    <div id="map-container"></div>
    <script type="text/javascript">
        var map;
        var marker;
        var markers = [];
        var locationData = [
                {latitude: 37.090200, longitude: -95.712882, label: 'A'},
                {latitude: 37.050710, longitude: -95.675891, label: 'B'},
                {latitude: 36.437308, longitude: -95.978816, label: 'C'}
        ];

        function initializeMap() {
            var center = new google.maps.LatLng(37.09024, -95.712891);
            var mapOptions = {
                zoom: 4,
                center: center,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("map-container"), mapOptions);

            for (var i = 0; i < locationData.length; i++) {  
                var position = new google.maps.LatLng(locationData[i].latitude, locationData[i].longitude);
                marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    label: locationData[i].label
                });
                markers.push(marker);
                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        map.setZoom(8);
                        map.setCenter(markers[i].getPosition());                    
                    }
                    })(marker, i));
            }
        }
        google.maps.event.addDomListener(window, "load", initializeMap);
    </script>   
</body> 
</html>

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

I'm curious about how to initiate a fresh Rails 7 project while incorporating Bootstrap 5 and jQuery assistance

Looking to start a new Rails project with version 7.3.1 and integrate the latest Bootstrap framework. However, I've heard that jQuery may not be compatible with the latest version of Bootstrap. I am also considering downloading the latest Bootstrap fi ...

What could be causing the discord.js command handler to malfunction?

As I was working on developing a Discord Bot, I encountered an issue with the Command Handler while using a for loop. This is the code in Index.js: client.commands = new Collection(); const commandFiles = fs.readdirSync('./commands').filter(fil ...

A guide on resolving the TypeError 'download property of undefined' issue when using Puppeteer with browser.downloads.download

Using puppeteer, I am automating the login process to access my account on a content provider's site and download multiple zip files. After obtaining an array of links to download, I go through each link in a loop and utilize the browser.downloads.dow ...

In Javascript, merge two arrays together in a specific format

Can we transform two arrays into a specific format so I can create my D3 graph? Here are the two arrays I have: date = ["sept,09 2015","sept, 10 2015","sept, 11 2015"] likes = [2,4,5] I need to convert them to this format: [{ date: '...', lik ...

"Getting an 'Undefined index' error while accessing a JavaScript variable in PHP

Every row in my table contains an Edit button. I managed to fetch the row number by clicking on the Edit button using JavaScript, but I am unsure how to do it in PHP. My attempt to pass the variable from JS to PHP resulted in an error: Undefined index ...

When it comes to utilizing the method ".style.something" in JavaScript

Here is some javascript code that I am working with: function createDiv(id){ var temp = document.createElement('div'); temp.setAttribute("id", id); document.getElementsByTagName('body')[0].appendChild(temp); } c ...

What is the best way to incorporate white-space:normal within the text of a jQuery Mobile grid button?

Below is the code for my jQuery Mobile Grid buttons: <div class="ui-grid-b my-breakpoint"> <div class="ui-block-a"><button type="button" data-theme="c"> <img src="res/icon/android/business.png" height="45"><br>Business</ ...

Utilizing pixel values for Material-UI breakpoints rather than using the default sm, md, lg, xl options

Below is the code snippet that I am using: [theme.breakpoints.only('lg')]: {} The above code works perfectly and shifts at the desired breakpoint. However, when I implement the following: [theme.breakpoints.between('1200', '1021&a ...

Loading JSON data from a file in an AngularJS service

Looking to retrieve JSON data from a file named driverStandings.json, which can be found in the structure from the provided image. I am utilizing a service API to fetch this information by using the code displayed below (refer to image). https://i.sstatic ...

What is the best way to transfer a list from aspx to javascript?

When populating a table by looping through a list, I aim to pass a row of data to my JavaScript code. If that's not an option, I'd like to pass the list and the ID number for the specific row. How can I achieve this? <%foreach(var item in Mod ...

Tips for parsing form values using jQuery AJAX:

Is there a way to extract form values and check if 15 objects have values or not? I attempted to do this using jQuery.parseJSON() but it didn't work as expected. [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Obj ...

What is the best way to include temporary attributes on a mongoose object solely for the purpose of a response, without saving them to the database

I am looking to add extra temporary properties with additional data to the response but have encountered some difficulties. 'use strict'; var mongoose = require('mongoose'); var express = require('express'); var app = expres ...

Determine the necessary adjustment to center the div on the screen and resize it accordingly

Currently, I am in a situation where I must develop a piece of code that will smoothly enlarge a div from nothing to its final dimensions while simultaneously moving it down from the top of the screen. Each time this action is triggered, the final size of ...

Fixed position not being maintained after clicking the button

Looking for some help with a fixed header issue on my website. The header is supposed to stay at the top while scrolling, which works well. However, when I switch to responsive view, click the menu button, and then go back to desktop view, none of the po ...

Learn how to easily alter the background color of a div in real-time by utilizing a color picker or color swatches feature in your

Would it be feasible to dynamically alter the background color of the .hasPicked class? I am interested in adjusting the background color using an input color picker and color swatches. I have already included the necessary code on Codepen. Check it out h ...

HighStocks should show categories instead of dates

The zoom function in HighCharts is what drew me to it initially. Everything was working perfectly until I encountered an issue that I can't seem to resolve. Here's my code snippet: http://jsfiddle.net/ma50685a/16/ $(function() { // Crea ...

Issue with Next.js Button not displaying expected result

I am in the process of developing a todo list application using next.js. The issue I am facing is that when I input data into the field, it correctly displays in the console. However, upon clicking the button, instead of the input displaying like a norma ...

Having difficulties achieving successful API requests in Next.js and Snipcart

I'm currently diving into the world of Snipcart, and I'm encountering some issues connecting to your API. I'm using Next.js and haven't been able to find any solutions on the forum or in the documentation that address my specific proble ...

Using a diverse class for enhancing the PrimeVue dialog's maximizable feature

I'm currently working with the PrimeVue Dialog component. My goal now is to apply different styles depending on whether the dialog is maximized or not. Let's keep it simple by saying I want to change the text to bold or red when the dialog is max ...

Resolve Redux-Firestore issue #45: Possible Solutions?

I'm facing an issue where deleting a document from Firestore results in my Redux store showing it as null instead of removing it. Even though the document is deleted in Firestore, this inconsistency causes frontend issues because my .map functions can ...