事件侦听器上图标标记的动态变化问题(google maps JS api)

Issue on dynamical change of icon marker on event listener (google maps JS api)

 google.maps.event.addListener(newMarker, 'rightclick', ( function(newMarker){ 
        return function() {

            var icon;
            icon = newMarker.getIcon();
            newMarker.setIcon('delPin.png');

            if (confirm('Sure to delete selected marker?')) {

                 newMarker.setMap(null);      

            }else newMarker.setIcon(icon);
        }; 
    })(newMarker)); 

我需要能够显示不同的图标,以突出显示它,同时右键单击标记并且确认消息正在等待用户操作。 然后,如果答案是肯定的,代码必须明确删除标记,而如果答案是否定的,它必须将标记的图标重置为先前的值。 在页面执行中,它似乎忽略了命令 newMarker.setIcon('delPin.png');并首先执行确认命令,因此没有图标更改。 如果我删除 if 语句,侦听器会积极地更改图标,这意味着图像源或命令语法没有问题。

关于问题是什么以及如何解决有什么建议吗?在此先感谢您的支持。

看起来您需要在执行 confirm.

之前给浏览器时间来加载和呈现新图标
google.maps.event.addListener(newMarker, 'rightclick', (function(newMarker) {
  return function() {
    var icon;
    icon = newMarker.getIcon();
    newMarker.setIcon('http://maps.google.com/mapfiles/ms/micons/blue.png');

    // delay to allow new icon to load and render.
    setTimeout(function() {
      if (confirm('Sure to delete selected marker?')) {
        newMarker.setMap(null);
      } else newMarker.setIcon(icon);
    }, 1000);
  };
})(newMarker));

proof of concept fiddle

代码片段:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var newMarker = new google.maps.Marker({
    position: map.getCenter(),
    map: map,
    icon: 'http://maps.google.com/mapfiles/ms/micons/green.png'
  })

  google.maps.event.addListener(newMarker, 'rightclick', (function(newMarker) {
    return function() {
      var icon;
      icon = newMarker.getIcon();
      newMarker.setIcon('http://maps.google.com/mapfiles/ms/micons/blue.png');
      setTimeout(function() {
        if (confirm('Sure to delete selected marker?')) {
          newMarker.setMap(null);
        } else newMarker.setIcon(icon);
      }, 1000);
    };
  })(newMarker));
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>