【问题标题】:how to add another event listener after added once..?添加一次后如何添加另一个事件侦听器..?
【发布时间】:2010-02-21 17:50:51
【问题描述】:

我是 Javascript 和 Google 地图的新手。我的任务是:

  • 允许用户在地图上添加标记
  • 当用户点击标记时显示一个信息窗口
  • 如果标记指向吉隆坡市中心,则在信息窗口中显示“吉隆坡市中心”,而其他位置则显示“未知位置”。

我的问题是添加标记后我什至无法显示信息窗口。我可以在同一个函数中添加一个新事件吗?该代码仅适用于添加标记。下面的代码是我从谷歌地图编辑后的:

函数 MyApplication() {

 this.counter = 0;
 this.map = new GMap2(document.getElementById("map_canvas"));
  this.map.setCenter(new GLatLng(3.145423,101.696883), 13);
  var myEventListener = GEvent.bind(this.map, "click", this, function(overlay, latlng) {
     if (this.counter == 0) {
       if (latlng) {
         this.map.addOverlay(new GMarker(latlng))
         this.counter++;
       } else if (overlay instanceof GMarker) {
          //This code is never executed as the event listener is 
          //removed the second time this event is triggered
        this.removeOverlay(marker)
       }
     } else {
       GEvent.removeListener(myEventListener);
}
}); 

}

function initialize() {
var application = new MyApplication();
}

函数 createMarker(latlng) {

  var marker = new GMarker(latlng);
  GEvent.addListener(marker,"click", function() {
   marker.openInfoWindowHtml('Petronas Twin Tower');
        });
  return marker;

}

提前致谢。近 2 周以来,我一直在绞尽脑汁。 :(请帮帮我...

【问题讨论】:

    标签: javascript html google-maps


    【解决方案1】:

    不确定您要使用代码完成什么。我假设您希望用户在任何时候都只有 1 个标记在地图上。

    我已将代码更改为如下所示:

    map=new GMap2(document.getElementById("googleMap"));
    map.setCenter(new GLatLng(3.145423,101.696883),13);
    
    var myEventListener = GEvent.bind(map,"click",this,function(overlay,latlng) {
    
        // remove any markers from the map each time the user clicks on the map. This makes sure
        // the user can only have 1 marker on the map at any 1 time
        map.clearOverlays();
    
        var marker = null;
    
        if(latlng) {
            marker = new GMarker(latlng);
            map.addOverlay(marker);
        } else if(overlay instanceof GMarker) {
            //This code is now executed
            if (marker)
                map.removeOverlay(marker);
        }
    });
    

    为什么需要在第二次点击时移除点击事件处理程序?

    上面的代码没有在标记上显示气球,但至少现在标记是 当用户点击它时被移除。

    您能否提供更多关于您想要做什么以及代码的确切行为的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多