在更改方向时显示多个标记的地图

时间:2014-11-03 16:51:05

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

我在谷歌地图上显示方向,一切正常。问题是当我更新其中一个标记(出发或到达)时,新标记被添加到地图而不是删除前一个标记。我试图将directionsDisplay设置为全局变量,但无法解决问题。有没有办法在显示新路线之前清除地图?

这是它的样子:

我也按照api上的建议尝试了这个:

directionDisplay = new google.maps.DirectionsRenderer();
directionDisplay.suppressMarkers = true;
directionDisplay.setMap(null);![enter image description here][1]

感谢您的帮助

我的代码是

    var map = drawMap(map, mapOptions);
    var departure;
    var arrival;
    var marker = createMarker();

    function mainMap(mapOptions) {
    departure1 = '#autocomplete_departure';
    arrival1 = '#autocomplete_arrival';

    var placeDeparture = getAddress(departure1);
    var placeArrival = getAddress(arrival1);


      google.maps.event.addListener(placeDeparture, 'place_changed', function(){
        placeMarker(placeDeparture, departure1);
      });

      google.maps.event.addListener(placeArrival, 'place_changed', function(){
        placeMarker(placeArrival, arrival1);
      });
  };

function setMarkerPosition(marker, place){
  marker.setPosition(place.geometry.location);
  marker.setMap(map);
}

function drawMap(){
  return new google.maps.Map(map, mapOptions);
}

function createMarker(){
  var markerOptions = {
    map: map
  }
  return new google.maps.Marker(markerOptions);
}


function placeMarker(place, stop){
  var place = place.getPlace();
  if (place.geometry.viewport) {
    map.fitBounds(place.geometry.viewport);   
  } else {
    map.setCenter(place.geometry.location);
    map.setZoom(17);
  }

  marker.setPosition(place.geometry.location);
  marker.setMap(map);

    if (stop == '#autocomplete_departure') {
      departure = stop;
    } else if (stop == '#autocomplete_arrival') {
      arrival = stop;
    }

    if (arrival !== undefined && departure !== undefined) {
      updateRouteOnMap(arrival, departure);
    }

  function updateRouteOnMap(departure, arrival){
    var from = $(departure).val();
    var to = $(arrival).val();

    var request = {
      origin: from,
      destination: to,
      travelMode: google.maps.TravelMode.DRIVING
    };

    var directionsDisplay;
    if (directionsDisplay != undefined) directionsDisplay.setMap(null);
    directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.setMap(map);

    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
        $("#directions-panel").html()
        directionsDisplay.setPanel(document.getElementById('directions-panel'));
      }
      else{
        alert("there has been an error. Please try again!")
      } 
    });     

1 个答案:

答案 0 :(得分:0)

经过多次尝试,我设法找到了解决方案。

我将directionsDisplay和directionsService设置为全局变量,并在绘制地图之前添加这段代码:

directionsDisplay.setDirections({routes: []});

这将在每次输入新方向时重置地图。