javascriptgoogle-mapsgoogle-maps-api-3

how to change color of a google maps v3 Marker icon


I'm placing a series of google maps Markers on a page using an array of points and a circle as an icon.

Once all the markers are on the page, I want to change the fill color of one of the Marker circles. How do I identify, say, the third Marker in my series so I can make that change? And how do I change the fillColor? I'm not using a google map event to identify the marker.

let map;

async function initMap() {
    // The location of the point
    const position = { lat: 40.44396002705076, lng: -80.00466302883518 };
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary("marker");
     
      // The map, centered at the point
    map = new Map(document.getElementById("map"), {
        zoom: 15,
        center: position,
        mapId: "6366bc12ac68e27f",
        
    });

 var arrMuralPositions = [
    { lat: 40.44215080214157, lng: -80.00194178463394 }, //stop 1
    { lat: 40.44219643284648, lng: -79.99723183193605 },//stop 2
    { lat: 40.44147920270817, lng: -79.99549375400392 },//stop 3
];

var myLabel;
     for (var i = 0; i<arrMuralPositions.length; i++) {
        myLabel = i+1;
         new google.maps.Marker({
        //new google.maps.marker.AdvancedMarkerElement({
            position: arrMuralPositions[i],
            label: {text: myLabel.toString(), color: "white"},
            icon: {
              path: google.maps.SymbolPath.CIRCLE,
              scale: 10,
             // fillColor: "#D8896D",
              fillColor: "#376cb9",
              strokeColor: "#376cb9",
              fillOpacity: 1,
              strokeWeight: 1,
            },
            map: map,
          }); 
     }

}

initMap();

//now how do I change the fillColor of the second Marker that I placed?

Solution

  • To change the color of the marker, change it's icon's fill and stroke colors:

      function highlightMarker(marker) {
        var icon = marker.getIcon()
        icon.fillColor = "black";
        icon.strokeColor = "black";
        marker.setIcon(icon);
      }
    

    To change the color back for this simple case, where they are all fixed to be the same, change it back to the original value:

      function unhighlightMarker(marker) {
        var icon = marker.getIcon();
        icon.fillColor = "#376cb9";
        icon.strokeColor = "#376cb9";
        marker.setIcon(icon);
      }
    

    Simplest way to keep track of the markers is to add them to an array.

    Related questions:

    proof of concept fiddle

    screenshot of resulting map with one marker modified

    code snippet:

    let map
    let gmarkers = []
    
    async function initMap() {
      // The location of the point
      const position = {
        lat: 40.44396002705076,
        lng: -80.00466302883518
      }
      const {
        Map
      } = await google.maps.importLibrary("maps")
      const {
        AdvancedMarkerElement,
        PinElement
      } =
      await google.maps.importLibrary("marker")
    
      // The map, centered at the point
      map = new Map(document.getElementById("map"), {
        zoom: 15,
        center: position,
        mapId: "6366bc12ac68e27f",
      })
    
      var arrMuralPositions = [
        {lat: 40.44215080214157,lng: -80.00194178463394}, //stop 1
        {lat: 40.44219643284648,lng: -79.99723183193605}, //stop 2
        {lat: 40.44147920270817,lng: -79.99549375400392}, //stop 3
      ]
    
      var myLabel
      for (var i = 0; i < arrMuralPositions.length; i++) {
        myLabel = i + 1
        gmarkers.push(
          new google.maps.Marker({
            position: arrMuralPositions[i],
            label: {
              text: myLabel.toString(),
              color: "white"
            },
            icon: {
              path: google.maps.SymbolPath.CIRCLE,
              scale: 10,
              // fillColor: "#D8896D",
              fillColor: "#376cb9",
              strokeColor: "#376cb9",
              fillOpacity: 1,
              strokeWeight: 1,
            },
            map: map,
          }),
        )
      }
      highlightMarker(gmarkers[1]);
      setTimeout(function() {
        unhighlightMarker(gmarkers[1])
      }, 5000);
      setTimeout(function() {
        highlightMarker(gmarkers[2])
      }, 10000);
      setTimeout(function() {
        unhighlightMarker(gmarkers[2])
      }, 15000);
    
    
      function highlightMarker(marker) {
        var icon = marker.getIcon()
        icon.fillColor = "black";
        icon.strokeColor = "black";
        marker.setIcon(icon);
      }
    
    
      function unhighlightMarker(marker) {
        var icon = marker.getIcon();
        icon.fillColor = "#376cb9";
        icon.strokeColor = "#376cb9";
        marker.setIcon(icon);
      }
    }
    
    initMap()
    #map {
      height: 100%;
    }
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <!doctype html>
    <html>
    
    <head>
      <title>Default Advanced Marker</title>
    
      <!-- jsFiddle will insert css and js -->
    </head>
    
    <body>
      <div id="map"></div>
    
      <!-- prettier-ignore -->
      <script>
            (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
            ({key: "AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk", v: "weekly"});
      </script>
    </body>
    
    </html>