8

I have created a Google Maps Multiple locations page, using Advanced Custom Fields Google Map field.

I have managed to make the marker icon change when clicked on, but I want it to be changed back when clicking on other icons.

here is an example of the code:

    for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map,
    icon: iconBase + 'Stock%20Index%20Up.png'
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0], locations[i][6]);
      infowindow.open(map, marker);
      marker.setIcon("https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Down.png");
    }
  })(marker, i));

Better look of the working code here: http://jsfiddle.net/gargiguy/s8vgxp3g

gargi
  • 249
  • 1
  • 8
  • 17

3 Answers3

16

What duncan said: What you want to do is add all your markers to an array. In your click event handler, loop over that array, updating each marker's icon. Then finally set the icon for just the marker that's been clicked.

google.maps.event.addListener(marker, 'click', (function (marker, i) {
  return function () {
    infowindow.setContent(locations[i][0], locations[i][6]);
    infowindow.open(map, marker);
    for (var j = 0; j < markers.length; j++) {
      markers[j].setIcon("https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Up.png");
    }
    marker.setIcon("https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Down.png");
};

working fiddle

working code snippet:

var markers = [];
var map;

function initialize() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    // center: new google.maps.LatLng(-33.92, 151.25),
    center: new google.maps.LatLng(36.8857, -76.2599),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var infowindow = new google.maps.InfoWindow();
  var iconBase = 'https://cdn3.iconfinder.com/data/icons/musthave/24/';
  var marker, i;

  for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),
      map: map,
      icon: iconBase + 'Stock%20Index%20Up.png'
    });

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        infowindow.setContent(locations[i][0], locations[i][6]);
        infowindow.open(map, marker);
        for (var j = 0; j < markers.length; j++) {
          markers[j].setIcon("https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Up.png");
        }
        marker.setIcon("https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Down.png");
      };
    })(marker, i));
    markers.push(marker);

  }
}
google.maps.event.addDomListener(window, 'load', initialize);
var locations = [
  [
    "New Mermaid",
    36.9079, -76.199,
    1,
    "Georgia Mason",
    "",
    "Norfolk Botanical Gardens, 6700 Azalea Garden Rd.",
    "coming soon"
  ],
  [
    "1950 Fish Dish",
    36.87224, -76.29518,
    2,
    "Terry Cox-Joseph",
    "Rowena's",
    "758 W. 22nd Street in front of Rowena's",
    "found"
  ],
  [
    "A Rising Community",
    36.95298, -76.25158,
    3,
    "Steven F. Morris",
    "Judy Boone Realty",
    "Norfolk City Library - Pretlow Branch, 9640 Granby St.",
    "found"
  ],
  [
    "A School Of Fish",
    36.88909, -76.26055,
    4,
    "Steven F. Morris",
    "Sandfiddler Pawn Shop",
    "5429 Tidewater Dr.",
    "found"
  ],
  [
    "Aubrica the Mermaid (nee: Aubry Alexis)",
    36.8618, -76.203,
    5,
    "Myke Irving/ Georgia Mason",
    "USAVE Auto Rental",
    "Virginia Auto Rental on Virginia Beach Blvd",
    "found"
  ]
];
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div>
  <div id="map" style="width: 500px; height: 400px;"></div>
</div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • 2
    I would not suggest looping through every marker and updating each icon if you only need to change the previous icon. – RPL Mar 26 '17 at 12:27
3

Since it sounds like you only need to change the previous icon back to the original, I wouldn't recommend looping through every marker. In a map with a lot of markers, this could become quite heavy.

Instead, I would store the active marker in a variable on the click event, and just update that one when it changes.

var marker;
var activeMarker;
var iconDefault = iconBase + 'Stock%20Index%20Up.png';
var iconSelected = 'https://cdn3.iconfinder.com/data/icons/musthave/24/Stock%20Index%20Down.png';

for (i = 0; i < locations.length; i++) {  
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map,
    icon: iconDefault
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0], locations[i][6]);
      infowindow.open(map, marker);

      // check to see if activeMarker is set
      // if so, set the icon back to the default
      activeMarker && activeMarker.setIcon(iconDefault);

      // set the icon for the clicked marker
      marker.setIcon(iconSelected);

      // update the value of activeMarker
      activeMarker = marker;
    }
  })(marker, i));
}
RPL
  • 3,500
  • 2
  • 21
  • 28
2

You can do same like below:

var prevMarker = "";
var markers = [];
var image = { url: "your_png.png",
              scaledSize: new google.maps.Size(38, 40) // If you want to resize it.
            };

For creating marker,

var marker = createMarker(coordinate, map, image, id);  
// coordinate = {lat:float value,long:float value} and 'map' your map
function createMarker(lat, long, map, image, marker_id) {

    var coordinates = {lat: lat, lng: long};
    var marker = new google.maps.Marker({
                position: coordinates,
                icon: image,
                id: "marker_" + marker_id,
                map: map
    });

    return marker;
}

For marker action you can use.

marker.addListener('click', function() {
        console.log(this.id);

        if(prevMarker !== "") {
            prevMarker.setIcon({
                url: "your_image.png",
                scaledSize: new google.maps.Size(38, 40)
            });
        }
        prevMarker = this;
        this.setIcon({
            url: "your_image.png",
            scaledSize: new google.maps.Size(48, 50)
        });
        map.panTo(this.getPosition());
    });

loop marker code for all markers available.

Nahush Sarje
  • 137
  • 2
  • 3
  • 16
  • Warning. Same marker can be clicked multiple times, this may need extra coding. – Jaider Sep 23 '18 at 06:14
  • @Jaider, If same marker clicked, it will execute same line of code but on UI there won't be any effect. If you don't want to execute same marker code then you can write ignore code. ex. prevMarker === this then return. – Nahush Sarje Sep 24 '18 at 06:02