从Google地图上的标记数组中删除单个标记

时间:2010-11-22 17:46:50

标签: google-maps google-maps-api-3

我已经通过点击事件在我的地图上放置了多个标记,现在我想通过双击特定标记来删除单个标记。但它正在做的只是删除数组的最后一个标记。有什么帮助吗?

::::::::::::::::::::: EDIT ::::::::::::::

是否可以根据按下按钮删除单个标记?这就像我有一个表格行,我已经把那个标记的lat长和一个删除按钮。如果单击“删除”按钮,则应删除与该行中该按钮关联的点。

4 个答案:

答案 0 :(得分:2)

简单方法:将添加的标记索引(在markersArray中)分配给按钮,并在该按钮上单击事件时调用deleteMarker:

function createRow(markerIndex){ // add your args like lat, lng etc
  // do the magic and create table row with button having onclick=deleteMarker(markerIndex)
}

function deleteMarker(markerIndex){
  markersArray[markerIndex].setMap(null);
}

// invoke createRow when adding new marker
function addMarker(position){
  marker = new google.maps.Marker({
    position: location,
    map: map
  });
  var markerIndex = markersArray.push(marker) - 1; // push() returns new array length
  createRow(markerIndex);
}

这适用于新标记以及从例如加载的标记。 D b。 请注意,如果要保存它们,则必须检查将在db中放入哪些标记,因为setMap(null)不会从markersArray中删除它们。

答案 1 :(得分:1)

我开始使用您的代码并进行了一些更改,它对我有用。这样做适合你吗?

<html> 
<head> 
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> 
<style type="text/css"> 
  html { height: 80% }
  html { width: 70% }
  body { height: 80%; margin: 0px; padding: 0px }
  body { width: 70%; margin: 0px; padding: 0px }
  #map_canvas { height: auto }
  #map_canvas { width: auto }
</style> 
</head> 

<script type="text/javascript"
    src="http://maps.google.com/maps/api/js?sensor=true"> 
</script> 


<script type="text/javascript"> 
   var map;
   var geocoder;
   var infowindow = new google.maps.InfoWindow(
  { 
    size: new google.maps.Size(150,50)
  });
var markersArray = [];

function initialize() {

  geocoder = new google.maps.Geocoder();
  var myLocation = new google.maps.LatLng(52.13206069538749, -106.63635849952698);
  var mapOptions = {
    zoom: 12,
    center: myLocation,
    mapTypeControl: true,
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

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

    addMarker(event.latLng);
    document.getElementById("latbox").value=event.latLng.lat();  
    document.getElementById("lngbox").value=event.latLng.lng();

//    google.maps.event.addListener(marker, 'click', function() {
//        document.getElementById("latbox").value=event.latLng.lat();  
//        document.getElementById("lngbox").value=event.latLng.lng();
//    });
    google.maps.event.addListener(marker, 'dblclick', function(event) {
        deleteMarker(marker);
    });

  });
}

// code for search address
function codeAddress() {
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var search_marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

// function to create marker

function addMarker(location) {
  marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markersArray.push(marker);
}

//function to remove a single marker

function deleteMarker(marker){
    marker.setMap(null);
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
  infowindow.close();
  document.getElementById("latbox").value="";
  document.getElementById("lngbox").value="";
}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(map);
    }
  }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }

    infowindow.close();
    document.getElementById("latbox").value="";
    document.getElementById("lngbox").value="";
    /**
    document.getElementById('street').value="";
    document.getElementById('area').value="";
    document.getElementById('pass').value="";
    document.getElementById('descr').value="";
    document.getElementById('hintimage').value="";
    document.getElementById('showimage').value="";
    document.getElementById('hint').value="";
    document.getElementById('char').value="";
    document.getElementById('icon').value="";
    document.getElementById('zid').value="";*/
}
//document.write("3");

</script> 




<body onload="initialize()"> 




<!--------------------------------------------------HTML FORM--------------------------------------------------------------> 


<div id="map_canvas" style="width:100%; height:100%"></div> 
<div  id= "map_form"  style="display:visible" action=""> 
    <br /> 
    <br /> Write address for POIs in you desired location: <input id="address" type="text" value="Saskatoon, SK"/> 
    <input id="searhButton" type="button" value="Search Location" onclick="codeAddress()"/> <br /> 
    <br /> 
    Latitude: <input name="latitude" type="text" id="latbox" ReadOnly="True"/><br /> 
    <br /> 

    Longitude: <input id="lngbox" type="text" ReadOnly="True"/><br /> 
    <br /> 
    Zone ID: <input id="zid" type="text" /> [numbers only]
    <input type="hidden" id=zid2> 
    <br /> 
    <br /> 
    Street: <input id="street" type="text" /><br /> 
    <br /> 
    Area: <input id="area" type="text" /><br /> 
    <br /> 
    Password: <input id="pass" type="text" /><br /> 
    <br /> 
    Description: <input id="description" type="text" /><br /> 
    <br /> 
    Image for hint: <input id ="hintimage" type="file" /><br /> 
    <br /> 
    <br /> 
    Image to show: <input id ="showimage" type="file"  /><br /> 
    <br /> 
    Hint: <input id="hint" type="text" /><br /> 
    <br /> 
    <br /> 
    3D Character: <input id="char" type="file" /><br /> 
    <br /> 
    <br /> 
    Icon: <input id="icon" type="file" /><br /> 
    <br /> 
    <!--<input type="button" onclick="alertfunction()" value="show alert"/>--> 

    <input type="reset" value="Reset"  onclick="deleteOverlays()"/> 
    <input  onclick="showOverlays();" type=button value="Show All POIs"/> 
    <input type="button" onclick="alertfunction()" value="Save Data" /> 


</div> 





<!----------------------------Database Connection code----------------------------------------------------------------------> 

<script language="javascript" type="text/javascript"> 

function alertfunction(){

   if (validateFormOnSubmit(map_form) == false){
        alert("Some fields need correction:\n" + reason);
    }

    else{

       // alert("else in....");

        var req;

        try{
             // Opera 8.0+, Firefox, Safari
                req = new XMLHttpRequest();
                //document.write("2");
                }catch (e){
              // Internet Explorer Browsers
              try{
                 req = new ActiveXObject("Msxml2.XMLHTTP");
                  }catch (e) {
                 try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
                 }catch (e){
                // Something went wrong
                   alert("Your browser broke!");
                    return false;
                 }
              }
            }



        req.onreadystatechange = function() {
          //Is request finished? Does the requested page exist?
          if(req.readyState==4 && req.status==200) {   
            //Your HTML arrives here
            //document.write("state is 4");
            alert(req.responseText);
            document.getElementById('ajaxDiv').innerHTML = req.responseText;
          }
          /*
          else if (req.readyState==0){
            document.write("state is 0");
          }
           else if (req.readyState==1){
            document.write("state is 1");
          }
          else if (req.readyState==2){
            document.write("state is 2");
          }
          else if (req.readyState==3){
            document.write("state is 3");
          }*/
        }


        var latitude=document.getElementById('latbox').value;
        var longitude=document.getElementById('lngbox').value;
        var zid=document.getElementById('zid').value;
        var zid2=document.getElementById('zid').value;
        var street=document.getElementById('street').value;
        var area=document.getElementById('area').value;
        var pass=document.getElementById('pass').value;
        var description=document.getElementById('description').value;
        var hintimage=document.getElementById('hintimage').value;
        var showimage=document.getElementById('showimage').value;
        var hint=document.getElementById('hint').value;
        var char=document.getElementById('char').value;
        var icon=document.getElementById('icon').value;



    // MIGHT NEED SOME MODIFICATION ON PATH


       var queryString= "?latitude="+latitude;
       //var queryString= "?latitude="+latitude;
       queryString+="&longitude="+longitude+"&zid="+zid+"&zid2="+zid2+1+"&street="+street+"&area="+area+"&pass="+pass+"&description="+description+"&hintimage="+"http://aiworker2.usask.ca/passimagemodels/"+hintimage+"&hint="+hint+"&char="+char+"&icon="+icon+"&showimage="+showimage;
    //porpoise/image/
       //req.open("GET","http://aiworker2.usask.ca/dbload/db_server2.php"+ queryString,true)  //true indicates ASYNCHRONOUS
       req.send(null);

    }

}


<!--------------------------------------Validation Code---------------------------------------------------------->

    function validateNum(fld) {
        //alert("validateNum");
        var val = fld.value;
        var numericExpression = /^[0-9]+$/;
    if(val.match(numericExpression)){
            //alert("true");
        return true;
    }else{
            fld.style.background = "Yellow";
            alert("POI id must be numeric");
        return false;
    }
    }
// checking of an empty field
    function validateEmpty() {

        var error = "";

        var latVal = document.getElementById('latbox').value;
        var longVal=document.getElementById('lngbox').value;
        var idVal=document.getElementById('zid').value;
        var hint=document.getElementById('hint').value;
        var char=document.getElementById('char').value;
        var pass=document.getElementById('pass').value;



        if (latVal.length == 0) {
            error += "latitude";
            document.getElementById('latbox').style.background = 'Yellow';                                    
        }
        if (longVal.length == 0) {
            error += " longitude";
            document.getElementById('lngbox').style.background = 'Yellow';                                    
        }        
        if (idVal.length == 0) {
            error += " POI id";
            document.getElementById('zid').style.background = 'Yellow';                                    
        }        

        if (hint.length == 0) {
            error += " Hint";
            document.getElementById('hint').style.background = 'Yellow';                                    
        }

        if (char.length == 0) {
            error += " 3D Character";
            document.getElementById('hint').style.background = 'Yellow';                                    
        }

        if (pass.length == 0) {
            error += " Password";
            document.getElementById('pass').style.background = 'Yellow';                                    
        }



        if(error.length != 0){
            error += " should not be empty";        
        }

        return error;

        //return "something";
    }


    function validateFormOnSubmit(theForm) {
        var reason = "";
        reason += validateEmpty();
        if (reason != "") {
            alert(reason);
            return false;
        }
        //return true;
        return validateNum(document.getElementById('zid'));    
    }





</script> 


<div id='ajaxDiv'>Your result will display here</div> 
</body> 
</html> 

基本上,我摆脱了deleteMarker()回调并用匿名函数替换它。匿名回调使用this而不是marker来确保删除正确的标记。您可以在deleteMarker()回调中执行相同的操作,或者像我一样使用匿名回调。

我还评论了单击事件上标记的回调,但我认为你可以把它放回去而没有任何不利影响。 (请注意,当dblclick事件触发时,click事件也会触发,或者至少是文档引导我相信的那样。)

答案 2 :(得分:0)

试试这个。变化

function deleteMarker(marker){
    marker.setMap(null);
}

function deleteMarker(marker){
    return function() {
        reallyDelete(marker);
    };
}

function reallyDelete(marker) {
    marker.setMap(null);
}

答案 3 :(得分:0)

尝试以下哪些应该有效。我只保留了相关部分。

<script type="text/javascript">

var map;

function initialize() {

  var myLocation = new google.maps.LatLng(52.13206069538749, -106.63635849952698);
  var mapOptions = {
    zoom: 12,
    center: myLocation,
    mapTypeControl: true,
    navigationControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

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

    marker = new google.maps.Marker({
        position: event.latLng,
        map: map
    });
    addClickEvent(marker);
  });
}

function addClickEvent(marker){
    google.maps.event.addListener(marker, 'dblclick', function(event) {
        marker.setMap(null);
    });
}

</script>