inability to conceal a two-dimensional marker array within Google Maps API v3

  I need some help with my marker that refuses to hide  

Even after using setMap, my marker is still visible on the map Here is the error message from the console Please assist!

Thank you in advance

markers[i][j].setMap(null);
markers.setMap(null);
var markers = [
['office', 'Albania', 42.158410, 19.940845],
['production plant', 'Albania', 40.198905, 20.039722],
['R&D service', 'Albania', 41.090835, 19.545337],
['office', 'Algeria', 28.164666, 3.160335]
];

     `Uncaught TypeError: markers[i][j].setMap`

Answer №1

It is not possible to hide a marker based on elements in an array, as they do not have the .setMap method. The markers need to be instances of google.maps.Marker objects. When creating the markers, it is recommended to store references to them in a separate array, such as "gmarkers", and then use that array to hide or show them.

For a demonstration, you can check out this proof of concept fiddle using your data.

var markers = [
  ['office', 'Albania', 42.158410, 19.940845],
  ['production plant', 'Albania', 40.198905, 20.039722],
  ['R&D service', 'Albania', 41.090835, 19.545337],
  ['office', 'Algeria', 28.164666, 3.160335]
];
var map;
var gmarkers = [];

function toggleMarker() {
  var markerId = parseInt(document.getElementById('markerid').value);
  if (gmarkers[markerId].getMap() == null) {
    gmarkers[markerId].setMap(map);
  } else {
    gmarkers[markerId].setMap(null);
  }
}

function initialize() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: new google.maps.LatLng(-33.92, 151.25),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var infowindow = new google.maps.InfoWindow();

  var marker, i;
  var bounds = new google.maps.LatLngBounds();

  for (i = 0; i < markers.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(markers[i][2], markers[i][3]),
      map: map
    });
    bounds.extend(marker.getPosition());
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(markers[i][0]);
        infowindow.open(map, marker);
      }
    })(marker, i));
    gmarkers.push(marker);
  }
  map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  height: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input type="text" id="markerid" value="2" />
<input type="button" onclick="toggleMarker()" value="toggle" />
<div id="map"></div>

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

What benefits does JavaScript offer with the strategy of storing functions within variables?

Lately I've come across some code where functions are being stored inside variables and then called in the typical way. For example: var myFunctionName = function() { Code Here... } myFunctionName(); I'm aware that there may be numerous b ...

Utilizing Prototype in Node.js Modules

Currently, I am working on a project involving multiple vendor-specific files in node. These files all follow a similar controller pattern, so it would be more efficient for me to extract them and consolidate them into a single common file. If you're ...

Waiting for a response from an API with the help of nodejs

I'm new to exploring Node.js and I'm interested in making API calls where the result is awaited before proceeding with any further actions. // defining endpoint function function getListMarket() { var deferred = Q.defer(); deferred.resolve(Q ...

What is the method to set precise values on a range slider?

Currently, I am developing a PHP website that requires a slider for displaying the years of publications. In essence, I need the slider to navigate through the different years when the publications were released. // Database connection and other PHP code ...

Deleting elements from the DOM in Vue.js

Utilizing Vue.js (version 3.x), I am dynamically rendering components. <div v-for="(i, index) in fields" > <my-component :id="index" ></my-component> <span class="delete-icon" @click="removeFi ...

Querying a collection with a bulk request using Mongoose Cursor

My current challenge involves working with rxJS and handling bulk HTTP requests from a database containing over 1 million documents. The code I have is relatively simple. I am pushing all the documents from the collection into an array called "allPlayers" ...

Setting up Redux Saga in a modular format

I am currently using create-react-app for my project. As I now need redux-saga to handle async operations, I am encountering an issue with setting up sagas in a modular manner. When I say modular, I mean having one main sagas file that exports all the comp ...

Is it redundant to use flatMap in RXJS?

I recently came across an enlightening article on RXJS which delves into the concept of flatMap. After understanding its purpose - to flatten observable of observables into a single observable sequence (similar to SelectMany in C#) - I noticed an interes ...

Is there a way to create an event listener that responds to a simultaneous click of both mouse buttons?

Despite my extensive research on the Internet, I was unable to find any examples. Interestingly, Vue only supports right and left clicks separately which I find peculiar as it seems like a basic task that can easily be accomplished with plain Javascript. ...

Concealing a div based on empty textboxes using backbone and javascript

I need assistance with displaying or hiding a div based on the length of text boxes. My project is structured using Backbone, so I am unsure about where to insert the code.. Here is my current code; <input type="text" id="txtUsername" placeholder="use ...

An Ajax call navigates to the index.html page

Could you please assist with an issue I am facing? I have written the code below to make an ajax request to a specific link. However, instead of executing the ajax call using a POST request, the page is being redirected to index.html with the link in the ...

Unable to create selected buttons in Vue.js

I'm having trouble creating buttons that can select all options when clicking on either size or color. The buttons aren't showing up at all. Can someone help me identify the issue? I've attempted various solutions but none seem to work. Any ...

Execute Validation Function on Every TextField and Radio Button

I'm new to Javascript and struggling to make my function work for both radio buttons and text fields. Here is the HTML code for the form: <form action="sendmail.php" method="post" name="cascader" onsubmit="prepareEventHandlers()" id="cascader"&g ...

"After refreshing the page, the .load() function did not run as

After loading the page and adjusting the viewport size, I am trying to retrieve the dimensions of images. While I can successfully get image dimensions after the page loads using .load, I am struggling to find a way to update the image sizes when the viewp ...

Transforming a string into a proc using Ruby and Rails

Here's the scenario I'm dealing with. The current URL appears as follows: /categories/Art Using name = location.pathname.split('/')[2], I extract the Art part of the URL. Then, I send an AJAX request to the controller with the followi ...

Having trouble getting the webpage to update after entering information?

My current project involves automating a website using selenium python. I've encountered an issue where manually entering J590 into the target textbox requires clicking or pressing tab to refresh the page, resulting in an available option in a dropdow ...

Invoke a specific script snippet by its identifier within a React single-page application, causing the content to appear only upon manual

I am currently working on a React application that utilizes a third-party JS script from OneTrust cookie scripts. Unfortunately, the scripts provided are not optimized for single-page applications (SPAs). At the moment, I am simply referencing the script s ...

Issues arise when using bootstrap-multiselect onDropdownShow

I am currently utilizing the bootstrap-multiselect plugin created by davidstutz in conjunction with twitter bootstrap 3.3.0. My goal is to have a radio button selected when I click on the dropdown, however, this functionality does not seem to be working a ...

Order of custom code and JQuery in ASP master page

Using an ASP master page to include all the Javascript and jQuery files has presented a challenge for me. Specifically, the jQuery function in OrderManagement.js $(".menu-item").click(function () { window.alert("some text"); }); fails to execute whe ...

Could you share the most effective method for implementing a live search feature using javascript or jquery?

While attempting to create a live search for a dataset containing over 10,000 rows, I specified the DOM structure that is available. Despite my efforts to check each result after a single input during the live search process, my browser keeps hanging. Is t ...