如何清除当前地图上的标记

时间:2014-07-11 13:00:49

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

我正在使用google api v3网络应用。加载地图时,它会使用地理定位服务显示我当前的位置,并在该位置放置标记。现在当我搜索一个地方或试图找到两个地方之间的方向时,我想删除之前在地图上的所有标记,以便唯一的当前标记就是那些位置的起点和终点。但这是我遇到问题的地方,无论何时我搜索一个新的地方或尝试获得新的方向,以前的标记,尤其是当页面加载时仍然显示的地理位置标记。

我查看了地图api,我看到他们用来移除先前标记的标记数组。我把它放在我的代码中,它仍然无法正常工作。我会粘贴我的代码,以便您自己查看。

--------------------------------- MAPS.JS ----------- ------------------------------

var directionsDisplay;
var geocoder;
var map;
var markers = [];
var directionsService = new google.maps.DirectionsService();

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  geocoder = new google.maps.Geocoder();

  var mapOptions = {
    zoom: 15
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

   // Try HTML5 geolocation
  if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = new google.maps.LatLng(position.coords.latitude,
                                       position.coords.longitude);

      var marker = new google.maps.Marker({
         position: pos,
         map: map
      });

       markers.push(marker);
       map.setCenter(pos);
   }, function() {
        handleNoGeolocation(true);
      });
   } else {
    // Browser doesn't support Geolocation
    handleNoGeolocation(false);
   }

  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById('directions-panel'));

  var control = document.getElementById('control');
  control.style.display = 'block';
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(control);
}


function calcRoute(start, end) {
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

function handleNoGeolocation(errorFlag) {
  if (errorFlag) {
    var content = 'Error: The Geolocation service failed.';
  } else {
    var content = 'Error: Your browser doesn\'t support geolocation.';
  }

  var options = {
    map: map,
    position: new google.maps.LatLng(60, 105),
    content: content
  };

  var infowindow = new google.maps.InfoWindow(options);
  map.setCenter(options.position);
}

$("#search").click(function() {
    var start = $.trim($("#start").val());
    var end = $.trim($("#end").val());
    if (start==="" && end === "") {
        alert("Enter a valid address");
    } 
    else {
         if (end.length === 0)
           searchPlace(start);
          else
            calcRoute(start, end);
    }

});

//search for a place
function searchPlace(start) {
    geocoder.geocode( { 'address': start}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
          setAllMap(null);
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
        markers.push(marker);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
}

//remove all current markers that are on the map
function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
  }
}



google.maps.event.addDomListener(window, 'load', initialize);

---------------------------- INDEX.HTML ---------------- --------------------------------

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Google Direct</title>
<link rel="stylesheet" href="css/style.css" />
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
</head>

<body>


    <div id="control">
      <strong>Start:</strong>
      <input id="start" type="text" />
      <strong>End:</strong>
      <input id="end" type="text" />
      <button id="search">Find place</button>
    </div>
    <div id="directions-panel"></div>
    <div id="map-canvas"></div>
    <script src="js/jquery-1.9.1.js"></script>
    <script src="js/maps.js"></script>
</body>
</html>

请查看代码并告诉我哪里出错了。

1 个答案:

答案 0 :(得分:0)

我认为这是您尝试删除标记的地方

//remove all current markers that are on the map
function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
  }
}

要删除标记,您需要将地图设置为null,我就是这样做的。

function RemoveAllMarkers() {
    while (markers.length > 0) {
        markers.pop().setMap(null);
    }
    markers.length = 0;
}