【问题标题】:Issue on dynamical change of icon marker on event listener (google maps JS api)事件监听器上图标标记的动态变化问题(google maps JS api)
【发布时间】:2017-03-24 13:11:48
【问题描述】:
 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语句,监听器会积极改变图标,那么就意味着图像源或命令语法没有问题。

关于问题是什么以及如何解决问题的任何建议?提前感谢您的支持。

【问题讨论】:

    标签: javascript google-maps-api-3 icons listener google-maps-markers


    【解决方案1】:

    在执行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

    代码 sn-p:

    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>

    【讨论】:

    • 它工作正常!我认为它不需要超时,因为图标更改指令在确认之前,谢谢你的例子。
    猜你喜欢
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2011-10-30
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多