Changing Marker Color in Google Maps API

There are multiple Google Maps Markers colors based on certain conditions being TRUE or not.

In addition, these Markers will change color when the mouse hovers over a division (a1,a2..ax).

I want the Markers to revert back to their original color when the mouse leaves the division.

Would it work if I save the Marker's color state before using marker.setIcon, and then recall this color on mouseleave?

Thank you for your assistance.

The code below is functioning properly except that every marker turns blue after mouseleave.

function load() {
  var map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(<?= json_encode($lat); ?>, <?= json_encode($lng);?>),
    zoom: <?php echo json_encode($zoom); ?>,
    mapTypeId: 'roadmap'
  });
  var infoWindow = new google.maps.InfoWindow;

  downloadUrl(<?= json_encode($url); ?>, function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var cf = markers[i].getAttribute("cf");
      var wh = markers[i].getAttribute("wh");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var html = "<b>" + name + "</b> <br/>" + address;
      var image1 = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
      var image2 = 'http://labs.google.com/ridefinder/images/mm_20_red.png';



      var marker = new google.maps.Marker({
        map: map,
        position: point    

      });

      if (cf == "true") 
      {
          marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_blue.png');
      }


      else if (wh == "true") 
      {
          marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_green.png');
      }

     else
     {
         marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_red.png');
     }

       hover(marker,i);
      bindInfoWindow(marker, map, infoWindow, html);      
    }
    });
  }

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

  });
}

function hover(marker, i){
document.getElementById('a'+i).onmouseover = function() {
   marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_orange.png');
}
document.getElementById('a'+i).onmouseleave = function() {
   marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_blue.png');
}
    }

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };


  request.open('GET', url, true);
  request.send(null);
}

Answer №1

One effective approach would be to leverage function closure within a createMarker function for connecting event listeners and marker properties.

function createMarker(point, cf, wh, html, i, map) {
  var marker = new google.maps.Marker({
    map: map,
    position: point,
    draggable: true

  });
  var activeIcon, idleIcon;
  if (cf == "true") {
    idleIcon = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
  } else if (wh == "true") {
    idleIcon = 'http://labs.google.com/ridefinder/images/mm_20_green.png';
  } else {
    idleIcon = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
  }
  marker.setIcon(idleIcon);

  var elem = document.getElementById('a' + i);
  if (!!elem) {
    elem.onmouseover = function() {
      marker.setIcon('http://labs.google.com/ridefinder/images/mm_20_orange.png');
    }
    elem.onmouseleave = function() {
      marker.setIcon(idleIcon);
    }
  }
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);

  });

  return marker;
}

Invocation example:

downloadUrl(<?= json_encode($url); ?>, function(data) {
  var xml = data.responseXML;
  var markers = xml.documentElement.getElementsByTagName("marker");
  for (var i = 0; i < markers.length; i++) {
    var name = markers[i].getAttribute("name");
    var address = markers[i].getAttribute("address");
    var cf = markers[i].getAttribute("cf");
    var wh = markers[i].getAttribute("wh");
    var point = new google.maps.LatLng(
      parseFloat(markers[i].getAttribute("lat")),
      parseFloat(markers[i].getAttribute("lng")));
    var html = "<b>" + name + "</b> <br/>" + address;
    createMarker(point, cf, wh, html, i, map);
  }

Explore proof of concept fiddle here

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

Positioning the label for a Material-UI text field with an icon adornment when the shrink property is set

https://i.stack.imgur.com/E85yj.png Utilizing Material-UI's TextField, I have an Icon embedded within. The issue arises when the label "Your good name here" overlaps the icon instead of being placed beside it. This problem emerged after I included ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

Looking to maintain the value of a toggle button in a specific state depending on certain condition checks

I have a situation where I need to keep a toggle button set to "off" if my collection object is empty. Previously, I was using v-model to update the value of the toggle button. However, now I am attempting to use :value and input events, but I am strugglin ...

Utilize underscore's groupBy function to categorize and organize server data

I am currently utilizing Angular.js in conjunction with Underscore.js This is how my controller is structured: var facultyControllers = angular.module('facultyControllers', []); facultyControllers.controller('FacultyListCtrl', [' ...

What is the best way to eliminate a trailing backslash from a string?

Currently, I am iterating through a list of Discord server names in node.js. The goal is to create a php file that contains an array structured like this: <?php $guildLookup = array( "164930842483761" => "guildName1", "56334 ...

mandating the selection of checkboxes

Currently, I am exploring the possibility of automatically selecting a checkbox when an option is chosen from a dropdown menu. Below is a code snippet that demonstrates what I am aiming to tweak: $('.stackoverflow').on('change', func ...

Raspberry Pi encountering a TypeError with Node.js async parallel: "task is not a function" error

I am new to nodejs, so I kindly ask for your understanding if my questions seem simple. I am attempting to use nodejs on a Raspberry Pi 3 to control two motors, and I keep encountering the error message "async task is not a function." Despite searching fo ...

Unable to persist information in Firebase's real-time database

I'm having trouble saving data to my firebase database. Although I don't see any errors on the site, the data in firebase remains null and doesn't change no matter what I do. Here is the code snippet. HTML <html> <head> ...

Upgrade your development stack from angular 2 with webpack 1 to angular 6 with webpack 4

Recently, I have made the transition from Angular 2 and Webpack 1 to Angular 6 and Webpack 4. However, I am facing challenges finding the best dependencies for this new setup. Does anyone have any suggestions for the best dependencies to use with Angular ...

difficulty with displaying the following image using jquery

I have referenced this site http://jsfiddle.net/8FMsH/1/ //html $(".rightArrow").on('click',function(){ imageClicked.closest('.images .os').next().find('img').trigger('click'); }); However, the code is not working ...

What is the process of assigning data, in JSON format, from an HTML form to a variable?

I have the coding below in my abc.html file, which converts form data to JSON format: <body> <form enctype='application/json' method="POST" name="myForm"> <p><label>Company:</label> <input name=& ...

Ways to display "No records" message when the filter in the material table in Angular returns no results

How can I implement a "No Records Message" for when the current table is displaying empty data? Check out this link for examples of material tables in AngularJS: https://material.angular.io/components/table/examples ...

Ways to make the background color white in Bootstrap 5

Can someone assist me in changing the background color of my portfolio to white? I attempted to use global CSS, but the black background on both sides of the page is preventing the change. return ( <> <Navbar /> <main className= ...

Using await outside of an async function is not allowed

When working with a rest api in node.js, I have implemented functionality to automatically resize any uploaded images that are too large. However, I am encountering an error when trying to call my await method. Here is the code snippet: ': await is o ...

jQuery: Repeated Triggering of Button Click Event

At my website, I am facing an issue with multiple buttons being loaded twice via ajax from the same file. The problem arises when the event associated with a button fires twice if that same button is loaded twice. However, it functions correctly if only o ...

Get the PDF in a mobile app using HTML5 and Javascript

For my HTML5/JavaScript-based mobile application, I am in need of implementing a feature that enables users to download a PDF file. The PDF file will be provided to me as a Base64 encoded byte stream. How can I allow users to initiate the download proces ...

Allow access to the configuration file for a JavaScript file located in the public directory of an Express application

I have a specific question regarding the folder structure of my Express app. app │ │ └───config │ │ config.js │ │ └───public │ │ │ └───javascripts │ │ exportable.js │ ...

Having trouble signing out in Nextjs?

As a newcomer to Reactjs and Nextjs, I am currently working on developing an admin panel. To handle the login functionality, I have implemented the following code in my index.js/login page using session storage: const data = { name: email, password: pa ...

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

Is relying on getState in Redux considered clunky or ineffective?

Imagine a scenario where the global store contains numerous entities. Oranges Markets Sodas If you want to create a function called getOrangeSodaPrice, there are multiple ways to achieve this: Using parameters function getOrangeSodaPrice(oranges, s ...