代码无法从Google地图中删除所选标记

时间:2016-01-04 03:40:04

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

您好我有以下代码,我试图随机添加几个标记。然后在第二个功能中,尝试删除所选标记。但我的markerCoin [i] .setMap(null);线似乎没有效果,它不会删除选定的标记。它也不会产生任何错误。

var markerCoin=[]; // Global Variable

    function addMarker(){
  var max = Math.random() < 0.5 ? -0.0005 : 0.0005; 
  var min=Math.random() < 0.5 ? -0.0001 : 0.0001;

  for (i = 0; i < 5; i++) {
    markerCoin [i] = new google.maps.Marker({
      position: new google.maps.LatLng(myLat+ ( Math.random() * (max - min) + min), myLng+ ( Math.random() * (max - min) + min)),
      map: map
    });

    targetLat[i]=markerCoin[i].getPosition().lat();
    targetLng[i]=markerCoin[i].getPosition().lng();


  }
}

function markerDelete() {
  var distance;

  for (i = 0; i < 5; i++) {
    if (targetLat[i]!=0) {
      distance = getDistanceFromLatLonInKm(myLat,myLng,targetLat[i],targetLng[i]);
    }

    if (distance <= 30) {
      alert(distance);
      markerCoin [i].setMap(null);**//it does not remove the marker.**
      targetLat[i]=0;
    }
  }
}

任何建议,我做错了什么?

1 个答案:

答案 0 :(得分:0)

这似乎对我有用:

  var markerCoin=[];
  var targetLat=[];
  var targetLng=[];

  function addMarker(){
    var max = Math.random() < 0.5 ? -0.0005 : 0.0005; 
    var min = Math.random() < 0.5 ? -0.0001 : 0.0001;

    for (i = 0; i < 5; i++) {
      markerCoin[i] = new google.maps.Marker({
        position: new google.maps.LatLng( myLat + ( Math.random() * (max - min) + min), myLng + ( Math.random() * (max - min) + min)),
        map: map
      });

      targetLat[i]=markerCoin[i].getPosition().lat();
      targetLng[i]=markerCoin[i].getPosition().lng();


    }
  }

  function markerDelete() {
    var distance;

    if (targetLat[i]!=0) {
      distance = getDistanceFromLatLonInKm(myLat,myLng,targetLat[i],targetLng[i]);
    }

    if (distance <= 30) {

      for (i = 0; i < 5; i++) {
        markerCoin[i].setMap(null);
        targetLat[i]=0;
      }
    }
  }

  addMarker();
  markerDelete();

结帐this slightly modified JSFiddle