Username
Username

Reputation: 3663

How do I change stroke color of a Google Maps circle marker icon inside a listener?

I created a Google Maps object and added this marker to it. I want the stroke color to change on mouseouver.

var circle = new google.maps.Marker({
  map: myGmapObject,
  position: {lat,lng},
  icon: {
    strokeColor: "#000",
    path: google.maps.SymbolPath.CIRCLE,
    scale: 7.5,
    anchor: new google.maps.Point(0,0)
  }
});

circle.addListener("mouseover",function(event){
      this.icon.strokeColor = "#fff";
});

But when I mouseover the icon, the stroke color fails to change.

Upvotes: 1

Views: 1225

Answers (2)

geocodezip
geocodezip

Reputation: 161384

You need to get the existing icon, change its stroke, then set the new icon on the marker.

circle.addListener("mouseover", function(event) {
  var icon = this.getIcon();
  icon.strokeColor = "#fff";
  this.setIcon(icon);
});

proof of concept fiddle

code snippet:

function initMap() {
  // Create the map.
  var lat = 37.090
  var lng = -95.712;
  var myGmapObject = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {
      lat: lat,
      lng: lng
    },
    mapTypeId: 'terrain'
  });

  var circle = new google.maps.Marker({
    map: myGmapObject,
    position: {
      lat,
      lng
    },
    icon: {
      strokeColor: "#000",
      path: google.maps.SymbolPath.CIRCLE,
      scale: 7.5,
      anchor: new google.maps.Point(0, 0)
    }
  });

  circle.addListener("mouseover", function(event) {
    var icon = this.getIcon();
    icon.strokeColor = "#fff";
    this.setIcon(icon);
  });
  circle.addListener("mouseout", function(event) {
    var icon = this.getIcon();
    icon.strokeColor = "#000";
    this.setIcon(icon);
  });
  myGmapObject.fitBounds(circle.getBounds());
}
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Upvotes: 1

Danielle Lpz
Danielle Lpz

Reputation: 322

So since circle is declared as a new google maps marker I think the listener has to be declared in this way, it has to be passed from google maps to the dom.

  google.maps.event.addListener(circle, "mouseover", function() {
      this.icon.strokeColor = "#fff";
  });

You may try to take a look to this answer that I've come across

Change color of google maps v3 marker on mouseover of element out side of map

Upvotes: 0

Related Questions