Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change a google maps marker after its added

Using the google maps API (v3) I can successfully add an array of markers to the map using custom icons.

Each marker represents a destination and I want to change the icon image when the respective destination name is mouse'd over elsewhere on the page.

I can add the event listener to pick up the mouse over, and I know I can use marker.setIcon("imgurl") to change the icon, however what I can't figure out is how to reference the specific marker to be changed?

I've read that I can add an "id" when defining the marker, however I can't figure out how to use this is conjunction with marker.seticon to update that specific marker.

Thanks for your help.

like image 951
Tim Hurrell Avatar asked Nov 28 '25 17:11

Tim Hurrell


2 Answers

If you have ID numbers for each destination, keep an array of the markers indexed by your destination.

For example,

var myMarkers = []
for(var i = 0; i < destinations.length; i++) {
  myMarkers[destination[i].id] = new google.maps.Marker(markerOpts)
}

and in your destination links elsewhere:

onclick = function() {
    myMarkers[destinationID].setIcon(otherIcon)
}
like image 74
erjiang Avatar answered Nov 30 '25 07:11

erjiang


I typically create an array called markersArray. Then I name each marker marker_1, marker_2, etc. using a for loop. After each one is created, I push it to the markersArray. Now you can reference each marker using markersArray[i].

like image 44
Jack Avatar answered Nov 30 '25 06:11

Jack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!