2012-09-17 43 views
-1

由于我正在处理面向对象的JavaScript,因此我创建了一个地图对象,并且因为我需要保留以前的所有路线和标记,所以我不会创建新的Map对象。我的代码如下从地图中删除Google地图标记正在工作,现在它不是

function map() { 

    this.defaultMapOption = { 
     center : new google.maps.LatLng(0, 0), 
     zoom : 1, 
     mapTypeId : google.maps.MapTypeId.ROADMAP 
    }; 

    this.map = null; 

    this.marker = []; 

    this.directionsDisplay = null; 
} 

map.prototype.init = function() { 


    this.map = new google.maps.Map(document.getElementById("map"), this.defaultMapOption); 

    var map1 = this.map; 
    var marker1 = this.marker; 

    var count = 0; 

    google.maps.event.addListener(this.map, 'click', function(event) { 

     count++; 

     $(".tabNavigation li").find("a[href=markers]").trigger('click'); 

     if (marker1[count]) { 
      marker1[count].setPosition(event.latLng); 
     } 
     else 
     { 
      marker1[count] = new google.maps.Marker({ 
       position: event.latLng, 
       map: map1, 
       draggable : true 
      }); 

      //by clicking double click on marker, marker must be removed. 
      google.maps.event.addListener(map.marker[count], "dblclick", function() { 

       console.log(map.marker); 

       map.marker[count].setMap(null);//this was working previously 
       map.marker[count].setVisible(false);//added this today 

       $("#markers ul li[rel='"+count+"']").remove(); 

      }); 

      google.maps.event.addListener(marker1[count], "dragend", function(innerEvent) { 
       var geocoder = new google.maps.Geocoder(); 

       geocoder.geocode({'latLng': innerEvent.latLng}, function(results, status) { 

        if (status == google.maps.GeocoderStatus.OK) { 
         map.addMarkerData(results, count); 
        } 
        else 
        { 
         alert("Geocoder failed due to: " + status); 
        } 
       }); 
      }); 

      var geocoder = new google.maps.Geocoder(); 

      geocoder.geocode({'latLng': event.latLng}, function(results, status) { 

       if (status == google.maps.GeocoderStatus.OK) { 

        map.addMarkerData(results, count); 
       } 
       else 
       { 
        alert("Geocoder failed due to: " + status); 
       } 
      }); 
     } 
    }); 

} 

只有上面的代码只适用于一个标记。意味着第一次标记被双击删除。之后,它不会工作。

任何想法,为什么它停止工作!

回答

1

您的计数值正在增加新的标记,并且在addListener(map.marker[count],...)中,计数将包含最新值。所以只有那个标记会被删除。

因此,您应该在addListener函数末尾递减count值。

+0

ups ..你是对的..我的愚蠢......需要以不同的方式完成......非常感谢。 :) – KuKu

0

您正在添加标记[1],但您尝试删除标记[0]。将您的count++;从功能的开始移动到结束。

+0

nope ..我已经为他们每个绑定了'double click'事件。它不是问题。 – KuKu

+0

Cdeez的答案和我说的完全一样。 – Marcelo

+0

可能是,但我很容易理解@Cdeez答案然后你的答案。但你的回答意味着'marker'数组必须从0开始,而根据我来说那不是问题。问题是绑定功能。而@Cdeez明确表示,由于包含最新值的'count'将被删除。# – KuKu