editgoogle-maps-advanced-marker-element

Edit pinElement of an advacedMarkerElement without creating a new PinElement


I save all my advancedMarkersElements in an array and I want to change their Pinelements and specifically their glyphcolor with maptypeid_changed event.

I want to keep all the other properties the same. So, I would like to do something like this

for (var j in markersDB2) 
{
    let mark = markersDB2[j];                
    mark.content.glyphColor = labelColor;
}

But the only way that I found is to create a new PinElement and attach it to the advancedMarkerElement.

But how can I retain the same properties to the new PinElement as the existing ones in the original advanceMarkerElement?

Any idea?


Solution

  • You can store the PinElement in a custom attribute of the marker itself and update it later without creating a new PinElement. You'd need to adapt it to what you already have, but something like this should work:

    //create new marker
    var newMarker = new google.maps.marker.AdvancedMarkerElement({
      map: map,
      position: new google.maps.LatLng(lat, lng)
      });
    
    //create a new pin
    let myPin = new google.maps.marker.PinElement({
      background: "Green",
      glyphColor: "Red"
      });
    
    //save the entire PinElement as a custom element of the marker
    newMarker.myPinElement = myPin;     
    newMarker.content = myPin.element;      
    

    ....

    //To update the pin:
    //change only the pinelement attributes you need to update
    newMarker.myPinElement.glyphColor= "Blue";           
    //update the marker
    newMarker.content = newMarker.myPinElement.content;