Search code examples
gmaps4rails

What is the standard way in gmaps4rails for dynamically resetting marker icons / pictures?


All I want to do is dynamically reset a marker's icon. For example, suppose a red marker is pinned to a specific location on the map. A user-interaction occurs which requires the red marker to become yellow. In this case, I would expect to be able to do something like this:

      var icon = marker.serviceObject.getIcon();
      if ($("#chooseJobsForWorkSite ul li input:checked").size() > 0) {
        icon.url = "/assets/purple_MarkerT.png";
      } else {
        icon.url = "/assets/green_MarkerS.png";
      }
      marker.serviceObject.setIcon(icon);

This works fine for a single marker, but when I loop across this code for more than one marker, something goes wrong -- I do not get the desired colors for all markers.


Solution

  • I resolved this issue by using the replaceMarkers API method. Here's the code that worked:

    var replacementMarkers = new Array();
    for (var k = 0; k < activeMarkers.length; ++k) {
      var marker = activeMarkers[k];
    
      var iconUrl = null;
      if ($.inArray(marker, taskMarkers) >= 0) {
        iconUrl = "/assets/purple_MarkerT.png";
      } else {
        iconUrl = "/assets/green_MarkerS.png";
      }
    
      replacementMarkers.push({
        "lat": marker.lat.toString(),
        "lng": marker.lng.toString(),
        "picture": iconUrl,
        "id": marker.id,
        "description": marker.description
      });
    }
    
    // Delay the replacement operation because in some instances, we reach this branch via the Gmaps.map.callback.
    // In that case, I prefer to defer touching the gmap4rails until the current branch is done.
    
    window.setTimeout(function() {
      Gmaps.map.replaceMarkers(replacementMarkers);
      resetAddressMarkers();
    }, 25);