Choose all of the markers on the Google Map

for (i = 0; i < locations.length; i++) {
    var image = new google.maps.MarkerImage(
        'logo.png',
        null, // size
        new google.maps.Point( 0, 0 ), // origin 
        new google.maps.Point( 24, 48 ), // anchor (move to center of marker)
        new google.maps.Size( 48, 48 ) // scaled size (required for Retina display icon)
    );
    marker = new google.maps.Marker({
        icon: image,
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        flat: true,
        optimized: false,
        map: map,
        visible: true,
        customInfo: locations[i][0]
    });
    google.maps.event.addListener(marker, 'click', function() {
        alert('hello');
        console.log(this);
        map.setZoom(17);
        map.setCenter(this.getPosition());
        
        for (let j = 0; j < markers.length; j++) {
            markers[j].setClickable(false);
        }
        
        $('#map').append('<div class="reset" id="reset">Reset</div>');
        var office;
        if (this.customInfo == "Town A"){
            office = $('.city-a').html();
        } else {
            office = $('.city-b').html();                       
        }
        $('#map').append('<div class="office" id="office">'+office+'</div>');
        var reset = document.getElementById('reset');
        google.maps.event.addDomListener(reset, 'click', function() {
            map.setZoom(9);
            map.setCenter(new google.maps.LatLng(54.403758,-2.566102));
            $('#reset, #office').remove();
            
            for (let k = 0; k < markers.length; k++) {
                markers[k].setClickable(true);
            }
        });
    });
}

Through the code snippet above, I am able to plot multiple markers on a map successfully. However, my attempt to make all markers non-clickable using marker.setClickable(false); only affects the last plotted marker.

I would appreciate guidance on improving the code to ensure that all markers become non-clickable when

google.maps.event.addListener(marker, 'click', function() {
is executed.

Thank you in advance.

Answer №1

Explore more about closures in javascript programming. See below for a functioning version.

function listenToEvent(marker) {
    google.maps.event.addListener(marker, 'click', function() {
        alert('hello');
        console.log(this);
        map.setZoom(17);
        map.setCenter(this.getPosition());
        marker.setClickable (false);
        $('#map').append('<div class="reset" id="reset">Reset</div>');
        var office;
        if (this.customInfo == "Town A"){
            office = $('.city-a').html();
        } else {
            office = $('.city-b').html();                       
        }
        $('#map').append('<div class="office" id="office">'+office+'</div>');
        var reset = document.getElementById('reset');
        google.maps.event.addDomListener(reset, 'click', function() {
            map.setZoom(9);
            map.setCenter(new google.maps.LatLng(54.403758,-2.566102));
            $('#reset, #office').remove();
            marker.setClickable (true);
        });
    });
}

for (i = 0; i < locations.length; i++) {
    var image = new google.maps.MarkerImage(
        'logo.png',
        null, // size
        new google.maps.Point( 0, 0 ), // origin 
        new google.maps.Point( 24, 48 ), // anchor (move to center of marker)
        new google.maps.Size( 48, 48 ) // scaled size (required for Retina display icon)
    );
    marker = new google.maps.Marker({
        icon: image,
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        flat: true,
        optimized: false,
        map: map,
        visible: true,
        customInfo: locations[i][0]
    });
    listenToEvent(marker);
}

Alternate approach

for (i = 0; i < locations.length; i++) {
    var image = new google.maps.MarkerImage(
        'logo.png',
        null, // size
        new google.maps.Point( 0, 0 ), // origin 
        new google.maps.Point( 24, 48 ), // anchor (move to center of marker)
        new google.maps.Size( 48, 48 ) // scaled size (required for Retina display icon)
    );
    marker = new google.maps.Marker({
        icon: image,
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        flat: true,
        optimized: false,
        map: map,
        visible: true,
        customInfo: locations[i][0]
    });
    google.maps.event.addListener(marker, 'click', function(marker) {
        return function() {
            alert('hello');
            console.log(this);
            map.setZoom(17);
            map.setCenter(this.getPosition());
            marker.setClickable (false);
            $('#map').append('<div class="reset" id="reset">Reset</div>');
            var office;
            if (this.customInfo == "Town A"){
                office = $('.city-a').html();
            } else {
                office = $('.city-b').html();                       
            }
            $('#map').append('<div class="office" id="office">'+office+'</div>');
            var reset = document.getElementById('reset');

            google.maps.event.addDomListener(reset, 'click', function() {
                map.setZoom(9);
                map.setCenter(new google.maps.LatLng(54.403758,-2.566102));
                $('#reset, #office').remove();
                marker.setClickable (true);
            });
        }
    })(marker));    
}

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

Struggling to retrieve JSON data from the MercadoLibre API while consistently encountering the CORS error?

I have been attempting to access a mercadolibre API that provides JSON data I need to utilize. However, whenever I make an AJAX GET request, I keep receiving the same error: "Response to preflight request doesn't pass access control check: It does n ...

Effortlessly stream a series of video files in consecutive order using HTML's <video> tag

Having experimented with various approaches: I attempted to utilize hidden video tags and toggle their visibility, but encountered flickering issues. Another strategy involved modifying the src attribute of the video. However, I found that I needed to ...

It is not possible for ReactJS to disable a button that has been created dynamically

Incorporating ReactJS, I dynamically generate a form using customized JSON data. render() { return ( <div> <ShowForm src={this.state.data} /> </div> ); } After updating with componentDidUp ...

What is the best method for returning the AJAX outcome to the JSP page?

Using AJAX, I am able to post data from my JSP page to my servlet. $.ajax({ url: 'myServlet?action=FEP', type: 'post', data: {machine: i, name: txt}, // where i and txt hold certain values success: f ...

Creating a nested datatable from a JSON array object response is a valuable skill to have in

My API response is in JSON format with nested arrays. I am trying to parse it into a nested datatable, but I can't seem to get it working. Can someone please point out where I went wrong? The JSON data contains passenger information and each passenger ...

Angular state correctly maps to the controller but is not reflected in the HTML

I'm currently in the process of setting up a basic Angular application, something I've done many times before. I have defined a home state and another state for a note-taking app, but I am facing an issue where neither state is displaying or inje ...

Resolving Uncaught ReferenceError: require is not defined - Learn the solution here!

While working on my electron app, I encountered the error message Uncaught ReferenceError: require is not defined This is the relevant section of my code: const remote = require('electron').remote var minimise = document.getElementById('mi ...

The $or operator in mongoose falls short in providing complete data when paired with the find() method

I am currently utilizing the find method in conjunction with the $or operator to search the database for any duplicate data within this specific line. const duplicate = await NewItemsData.find({ $or: newItems }); Upon inspecting the variable in the consol ...

Issues with Angular 5 components not functioning properly

I am experimenting with a way to show/hide a div based on a boolean value from an observable. After looking at the second answer in this Stack Overflow thread, I implemented the following code snippet that retrieves the document body width and uses it in a ...

My attempt to execute the JavaScript code was unsuccessful

Recently, I have been experimenting with the three.js library, a powerful javascript 3D library... Here is the code snippet I have been working on: var segments = 16, rings = 16; //var radius = 50; <-- original // Creating a new mesh with sphere geo ...

Is there a way to automatically execute a node script using cron in a bash environment?

My cron job on Ubuntu is not working correctly 02 12 * * * quigley-user /mnt/block/alphabits/start.sh >> /mnt/block/alphabits/start.log Even though the cron job runs on schedule, I am facing issues. In my start.sh script, I have the following snipp ...

Tips on displaying a div element using jQuery

What is required: I simply need to display a div. Code snippet: <a href="javascript:void(0);" id="viewdetail" onclick="$(this).show();" style="color:green">View Detail <div class="speakers dis-non"> </div> </a> After ...

Can you identify the distinctions between these two lines?

As a beginner in React, I recently learned how to create a timer counter following a tutorial. However, I am slightly confused about the difference between these two lines of code. Can someone please explain what is occurring in the first line below? lin ...

Creating input fields dynamically within Yii2 framework

I'm currently facing a challenge with forms in Yii2. My objective is to design a form that includes three dropdown menus, inquiring about the user's preferred time(s) during the week. The first menu will focus on selecting days of the week, while ...

Troubleshooting Angular JS Module Injection Issues

Lately, I've been exploring the wonders of angular JS and it has truly impressed me. However, one concept that still eludes my full understanding is injection. Despite this, I have successfully employed this technique across numerous pages in my proje ...

Ways to update a component from another in React

My React code includes an Employees page that renders both a Table component and a Filter component. The Filter component manipulates some data stored in the Employees page, updates the Filter's state through useEffect, and passes the data as a prop t ...

Encountering difficulties in JavaScript while trying to instantiate Vue Router

After following the guide, I reached the point where creating a Vue instance was necessary (which seemed to work). However, it also required providing a Vue Router instance into the Vue constructor, as shown below. const router = new VueRouter({ routes }) ...

Electron-Updater identifies a new update, yet refrains from downloading it

The concept: electron-updater is designed to automatically update my electron software whenever a new version is released. The issue: electron-updater identifies the new version, but fails to download and install it. I utilize <a href="/cdn-cgi/l/ema ...

Learn the process of encoding a string in JavaScript or jQuery and then decoding it with PHP

I am facing an issue with updating a field in the database using Ajax and PHP. Everything runs smoothly except when there are special characters present, like this: اللهم اني اشكو اليك ضعف قوتي وقلة حيلتي وهواني عل ...

Converting camera space coordinates to scene space in three.js

I want to position a cube relative to the camera instead of relative to the scene. However, in order to display it in the scene, I need to determine the scene coordinates that align with the cube's camera space coordinates. I came across the function ...