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

Switch between showing the Font Awesome TitleText and its associated Class with a single click

Can the value of the title attribute for <i> be toggled? For example, if the title is set to <i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true"> within <div class="postoption"> I would like to toggle both the title te ...

Converting JSON POST data in Mocha test for an Express application

When I run my Express code from Postman, everything works perfectly. However, when I try to call it from Mocha, I encounter issues specifically with setting data in the header of a POST request. This problem only occurs with POST requests containing parame ...

Proper syntax for SVG props in JSX

I have developed a small React component that primarily consists of an SVG being returned. My goal is to pass a fill color to the React component and have the SVG use this color. When calling the SVG component, I do so like this: <Icon fillColour="#f ...

Arranging div containers with nested content

Within my application, I am dynamically displaying images side by side to users. Users have the ability to assign points to these images, and I would like to give them the option to sort the images based on points, with the highest points displayed first i ...

Is it possible to trigger an event just once?

Is there a way to ensure an event only fires once? I recently discovered that using .one seems to do the trick. ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Having trouble with an endless GET request loop in NextJS 13 while utilizing the Next-Auth middleware. Experiencing difficulties fetching the RSC payload

UPDATE: The issue has been identified! It seems that the bug is caused by using the beta turbopack. I have reported this problem and we are awaiting a resolution. Query: I recently delved into a project in NextJS 13 with the new app directory setup. Afte ...

Is there a way to highlight today's working hours with a different color using Vue.js?

Here is the script I have created to display the working hours: const workHour = "Monday :9:00AM to 5:00PM,Thursday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM ...

Unable to sign out user from the server side using Next.js and Supabase

Is there a way to log out a user on the server side using Supabase as the authentication provider? I initially thought that simply calling this function would work: export const getServerSideProps: GetServerSideProps = withPageAuth({ redirectTo: &apos ...

Run a PHP script that creates a PDF file using jQuery AJAX

I am currently working with a form that looks like this: <form action="tcpdf/examples/example_0611.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="subm ...

Troubleshooting issue with Onchange in select HTML element within Django

I'm working with a Problems model in my project. In my Models file models.py class Problems(models.Model): Easy = 'Easy' Medium = 'Medium' Hard = 'Hard' NA = 'NA' DIFFICULTY = [ (NA ...

Initiating Internet Explorer using the APTool application for Selenium automation

Have you ever encountered a situation where you needed to open Internet Explorer from the start menu with the right-click option open with *apptool and then navigate to a specific webpage? I wonder, is it possible to automate this process using Selenium W ...

What is the significance of incorporating 'Actions' as data within the Redux framework?

According to Redux documentation, creating actions and action creators is necessary. Here's an example: function addTodo(filter) { return { type: SET_VISIBILITY_FILTER, filter } } Next step is to write reducers, like this: function t ...

Leveraging AngularJS and ng-map to incorporate interactive dynamic heatmap displays

Greetings everyone! I am completely new to frontend development and have embarked on my first journey with AngularJS. I must admit, it's quite challenging and I'm still trying to wrap my head around how it all works. Currently, I'm working o ...

`How to prevent Query parameters from being lost upon reloading in Nextjs Router while maintaining a clean URL structure?`

My challenge lies in sending data via router.push to a page with dynamic room id (src/pages/editor/[roomid].tsx) in Next.js. I want the URL to stay clean so users can easily edit their username in the URL if needed. When initially loaded, router.query suc ...

transmitting error messages from a service to a controller in AngularJS

Controller.js var vm = this; vm.admin = {}; vm.add = function () { API.addAdmin(token, vm.admin) .then(function (resp) { vm.hideForm = true; vm.showButton = true; Notify.green(resp); }, function (re ...

Increase value continuously when button is pressed down using Material UI

I am looking for a way to continuously increment a value while holding down a button. I have already managed to make it increment on click, but now I want to keep it increasing as long as the button is held down. How can this be achieved using material u ...

Guide on properly documenting custom function types in JSDoc or TypeScript to ensure accurate referencing for VSCode IntelliSense functionality

I am currently working on documenting custom function types within an object and would greatly appreciate any assistance: A Closer Look at the Issue Consider this basic object declaration with several function properties (addCoordinate, addCoordinateOne, ...

The error message "TypeError: Trying to access properties of an undefined object (reading '800')" is being displayed

Every time I launch my application, I encounter the error message: "TypeError: Cannot read properties of undefined (reading '800')". import React, { useState } from 'react'; import { Menu, MenuItem, Avatar, Box, ThemeProvider} ...

Revamp List Model through Ajax Integration in ASP .NET MVC5

Could someone please provide a hint on how to update the Model list in the view page after calling the Action Result with an Ajax request? Specifically, how can I refresh the current list model with the result of the Ajax call back? Here is the code for m ...