Manipulate Google Maps v3 markers to select or remove based on specified ID from an external link using HTML and JS

I'm a beginner when it comes to working with Google Maps and JavaScript. My goal is to interact with the map using external links or lists.

One issue I am facing is the inability to select markers on the map by their id.

I don't want to have to store all markers in a list or array and iterate through them because I don't know how many there will be at any given time.

All I want is to be able to select markers by their unique ids so that I can manipulate them, like opening info windows or removing them.

In my `changeIcon()` function, I've attempted different methods but none have been successful so far.

<html>

....

<div id="mapview"></div>

<a class="test-link" onmouseover="changeIcon()">Link</a>

<script>

function changeIcon()
    {
        //marker = map.selectMarker("4");
        //marker = markers[4];
        //infowindow.open(map,marker);

        //$("#mapview").map.removeMarker(4);
    }

var map = new google.maps.Map(document.getElementById('mapview'), 
        {
            center: {lat: 44.540, lng: -78.546},
            zoom: 16
        });

function initMap() 
{
  var marker = new google.maps.Marker({
          position: userPosition,
          map: map,
          id: 4
        });
}

</script>

</html>

............................................

Answer №1

Unfortunately, there is no available API that allows you to retrieve a marker directly from the map. For more information, you can check out the following reference: "https://developers.google.com/maps/documentation/javascript/reference"

If you want to avoid using an array due to the mismatch between IDs and indexes, I recommend utilizing a dictionary instead:

var markers = {};  // Use "{}" for dictionary allocation instead of "[]" for arrays

Simply add the created marker to the dictionary like this:

markers[4] = marker;   // Assigning the marker to ID 4

To retrieve the marker later on, you can do so by accessing it through the dictionary:

var currentMarker = markers[4];

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

Refreshing a PNG file without the need to refresh the entire page

Developed a captcha using imagestring imagestring($image, 5, 5, 30, $text, $text_color); imagepng($image,"captcha_image.png"); imagepng($image,"captcha_image.png"); The code snippet above shows part of the implementation. <img ...

Issue of flickering/flashing in Next js when using conditional rendering

I've been attempting to implement localstorage for storing authentication with Next.js. I am using conditional rendering to ensure that localstorage is accessible before displaying the content. However, I am facing an issue where the page flickers or ...

What is the maximum file size for an AJAX POST request?

Many queries have been raised regarding the process of uploading large strings of data via AJAX to PHP. However, most inquiries are related to uploading strings of approximately 3MB. I am looking to upload a significantly larger string. In my scenario, I ...

Refresh element once AJAX call is completed successfully

Issue Despite a successful AJAX request, I am encountering difficulties updating an element on the webpage. JavaScript Code $(function() { $(".upvote").click(function() { var id = $(this).parent().find("input").val(); $.ajax( ...

Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text: The Component class: import {sayHello} from './helloworld-servi ...

React.js Form Validation issue: When using input type "number", the text field remains a single value even after attempting to delete characters with the backspace key

Experiencing difficulty in clearing the input field value, even after pressing backspace the value remains constant. One particular value persists in the input field. import * as React from "react"; import { Button, Form } from "react-boots ...

What is the best way to designate unique custom login redirects based on user type?

I am facing a challenge that I can't seem to overcome. Part of the issue is my struggle to articulate it effectively with the right terminology. As a newcomer in this field, please forgive me for posing such a clumsy question. Below is an outline of ...

Learn how to run javascript code using Nodejs child_process and Meteor

Is it possible to use the child_process module to execute Meteor server-side code instead of just Linux commands? I am interested in using spawn to create a separate process for running my loop. The loop involves logging a message every minute. myLoop(){ ...

I'm experiencing an issue where my express-session is being reset with every new request, leading me to question if this is related to the development environment I am using (REACT + EXPRESS)

UPDATE - I have ruled out a development environment issue as the same problem persists in production. Thank you for taking the time to look into this. I've searched through numerous questions and attempted various solutions with no success. To give ...

Merge two JavaScript functions

I've been attempting to merge two if functions together but I keep encountering errors. Despite trying different methods, I have not been successful in combining them. My goal is to check if the body has a specific class and if it does, I want to unc ...

Tips for using jQuery to create a delete functionality with a select element

I'm relatively new to utilizing jquery. I decided to tackle this project for enjoyment: http://jsbin.com/pevateli/2/ My goal is to allow users to input items, add them to a list, and then have the option to select and delete them by clicking on the t ...

Utilize Tailwind CSS in React to dynamically highlight the active navigation item on click

Check out my navigation bar code: <nav className="bg-white shadow dark:bg-gray-800"> <div className="container flex items-center justify-center p-6 mx-auto text-gray-600 capitalize dark:text-gray-300"> <Link ...

Vanishing line element in Three.js

I seem to have encountered a peculiar issue that may either be a bug in three.js or a result of my own error with curve handling. In the scene I've created, there are several meshes (such as transparent cubes and small spheres) along with a line o ...

Tips for setting a select list to have no elements pre-selected when using the jQuery bsmSelect plugin

Looking for a way to have the jQuery bsmSelect plugin start with nothing selected by default? This handy plugin makes it easy for users to choose multiple options from a dropdown list, but you need it to begin blank. Any suggestions on how to achieve this? ...

Clearing Input Values in Text Boxes, Dropdowns, and Checkboxes in ASP.NET MVC

Currently, I am working with Asp.net MVC 4 using C#. On one of my pages, I have a Text box, Drop down, and checkbox all together as search filters. There is also a "Clear" button to reset the values. When this button is clicked, I want the textbox value to ...

"Troubleshooting: Issues with message passing between popup.html and content.js in Chrome Extension

I'm facing a challenge in creating an Extension that transfers data from popup.html to the tab dome. Unfortunately, I am having trouble with getting the sendMessage function to work and I can't figure out why. I'm using the following guideli ...

Problem with BehaviorSubject: next() method is not functioning as expected

My goal is to utilize an angular service for storing and communicating data via observables. Below is the implementation of my service: public _currentLegal = new BehaviorSubject({ name: 'init', _id: 'init', country: 'init& ...

A guide on integrating a submission button that combines values from multiple dropdown forms and redirects to a specific URL

Is there a way to make the submit button on this form act based on the combined values of two different dropdown menus? For instance, if "west" is selected from the first dropdown and "winter" is selected from the second dropdown, I want it to navigate to ...

What is the best way to trim a string property of an object within an array?

I am seeking a solution to access the "description" property of objects within an array and utilize a string cutting method, such as slice, in order to return an array of modified objects. I have attempted using for loops but have been unsuccessful. Here ...

Comparing Vue JS Promise Execution in Sequential and Parallel fashion

In my VueJS code, I have a working block that needs to be executed sequentially: return Promise.all(this.vm.multipleActions.run.map(function (testRun) { return self.initiateTest(testRun); })) Currently, it appears that this block runs in parallel ...