最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Clear Route in Google Maps directions - Stack Overflow

programmeradmin4浏览0评论

I have a set of markers loaded from an XML; when clicked on a marker, I have directions rendered from current location to the marker position. However, I'd like to be able to clear a route, preferably when the user clicks on a different marker. Currently all the routes show up together. I can't figure out where I'm messing up. I've tried the directionsDisplay.setMap(null) but that doesn't clear them. Please let me know if you notice what the issue is. Thank you.

function loadGoogleMap(){
    // load google map
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = '.exp&sensor=false&' +
        'callback=MyMap';
    document.body.appendChild(script);
}


var map = ''

function MyMap(){

/* 

document.getElementById('finddate').value

 */

var im = '.png';
var CustomMarker = '.png';

if(navigator.geolocation){

    navigator.geolocation.getCurrentPosition(locate, noPos());
} else { 

noPos();

}

function locate(position){


      var directionsDisplay = new google.maps.DirectionsRenderer();
      var directionsService = new google.maps.DirectionsService();

    var myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var mapOptions = {
      zoom: 12,
      center: myLatLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoomControl: false,
      streetViewControl: false,
      mapTypeControl: false,
      panControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT},
      zoomControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT }
    }
    var map = new google.maps.Map(document.getElementById('map-canvas'),
                                  mapOptions);
    var userMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: im
    });
var infoWindow = new google.maps.InfoWindow;



  // Change this depending on the name of your PHP file

    downloadUrl("phps/xmltest.php", function(data) {
    var xml = data.responseXML;         
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var dt1 = markers[i].getAttribute("date1");
      var dt2 = markers[i].getAttribute("date2");
      var dt3 = markers[i].getAttribute("date3");
      var tm1 = markers[i].getAttribute("time1");
      var tm2 = markers[i].getAttribute("time2");
      var tm3 = markers[i].getAttribute("time3");
      var pid = markers[i].getAttribute("PID");
      var d = new Date();
      var raw = pid * d.getFullYear();
      var jshtml = '<a href='+'phps/info.php?raw='+ raw +'>More Info</a>'
      var html = "<b>" + name + "</b> <br/>" + "Date of Yard Sale: " + dt1 + '&nbsp;' + tm1 + '&nbsp;' + dt2 + '&nbsp;' + tm2 + '&nbsp;' + dt3 + '&nbsp;' + tm3 + '&nbsp;' + "<br/>" + address + "&nbsp;" + "Click this for: " + jshtml;
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: CustomMarker
      });



      bindInfoWindow(marker, map, infoWindow, html, directionsDisplay);
    }


   });




function bindInfoWindow(marker, map, infoWindow, html, directionsDisplay) {


  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker, html);
    center: position;

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



                          directionsDisplay = new google.maps.DirectionsRenderer();
                          directionsDisplay.setMap(map)
                          var start = myLatLng;
                          var latitude = marker.getPosition().lat().toFixed(6) 
                          var longitude = marker.getPosition().lng().toFixed(6)
                          var end = new google.maps.LatLng(latitude, longitude);
                          var request = {
                            origin:start,
                            destination:end,
                            travelMode: google.maps.TravelMode.DRIVING
                          };
                          directionsService.route(request, function(result, status) {

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

                                directionsDisplay.setMap(null)
                                directionsDisplay.setMap(map);  
                              directionsDisplay.setDirections(result);  

                            }
                          });


  });
}

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };


     request.open('GET', url, true);
  request.send();
}
     function doNothing() {}
}

I have a set of markers loaded from an XML; when clicked on a marker, I have directions rendered from current location to the marker position. However, I'd like to be able to clear a route, preferably when the user clicks on a different marker. Currently all the routes show up together. I can't figure out where I'm messing up. I've tried the directionsDisplay.setMap(null) but that doesn't clear them. Please let me know if you notice what the issue is. Thank you.

function loadGoogleMap(){
    // load google map
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://maps.googleapis./maps/api/js?v=3.exp&sensor=false&' +
        'callback=MyMap';
    document.body.appendChild(script);
}


var map = ''

function MyMap(){

/* 

document.getElementById('finddate').value

 */

var im = 'http://www.robotwoods./dev/misc/bluecircle.png';
var CustomMarker = 'http://findmyyard./images/MarkerIcon.png';

if(navigator.geolocation){

    navigator.geolocation.getCurrentPosition(locate, noPos());
} else { 

noPos();

}

function locate(position){


      var directionsDisplay = new google.maps.DirectionsRenderer();
      var directionsService = new google.maps.DirectionsService();

    var myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var mapOptions = {
      zoom: 12,
      center: myLatLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      zoomControl: false,
      streetViewControl: false,
      mapTypeControl: false,
      panControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT},
      zoomControlOptions: { position: google.maps.ControlPosition.TOP_RIGHT }
    }
    var map = new google.maps.Map(document.getElementById('map-canvas'),
                                  mapOptions);
    var userMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: im
    });
var infoWindow = new google.maps.InfoWindow;



  // Change this depending on the name of your PHP file

    downloadUrl("phps/xmltest.php", function(data) {
    var xml = data.responseXML;         
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {
      var name = markers[i].getAttribute("name");
      var address = markers[i].getAttribute("address");
      var dt1 = markers[i].getAttribute("date1");
      var dt2 = markers[i].getAttribute("date2");
      var dt3 = markers[i].getAttribute("date3");
      var tm1 = markers[i].getAttribute("time1");
      var tm2 = markers[i].getAttribute("time2");
      var tm3 = markers[i].getAttribute("time3");
      var pid = markers[i].getAttribute("PID");
      var d = new Date();
      var raw = pid * d.getFullYear();
      var jshtml = '<a href='+'phps/info.php?raw='+ raw +'>More Info</a>'
      var html = "<b>" + name + "</b> <br/>" + "Date of Yard Sale: " + dt1 + '&nbsp;' + tm1 + '&nbsp;' + dt2 + '&nbsp;' + tm2 + '&nbsp;' + dt3 + '&nbsp;' + tm3 + '&nbsp;' + "<br/>" + address + "&nbsp;" + "Click this for: " + jshtml;
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: CustomMarker
      });



      bindInfoWindow(marker, map, infoWindow, html, directionsDisplay);
    }


   });




function bindInfoWindow(marker, map, infoWindow, html, directionsDisplay) {


  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker, html);
    center: position;

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



                          directionsDisplay = new google.maps.DirectionsRenderer();
                          directionsDisplay.setMap(map)
                          var start = myLatLng;
                          var latitude = marker.getPosition().lat().toFixed(6) 
                          var longitude = marker.getPosition().lng().toFixed(6)
                          var end = new google.maps.LatLng(latitude, longitude);
                          var request = {
                            origin:start,
                            destination:end,
                            travelMode: google.maps.TravelMode.DRIVING
                          };
                          directionsService.route(request, function(result, status) {

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

                                directionsDisplay.setMap(null)
                                directionsDisplay.setMap(map);  
                              directionsDisplay.setDirections(result);  

                            }
                          });


  });
}

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };


     request.open('GET', url, true);
  request.send();
}
     function doNothing() {}
}
Share Improve this question edited Jun 14, 2014 at 20:53 017Bluefield 1612 silver badges13 bronze badges asked Jun 14, 2014 at 20:26 AlexAlex 1221 gold badge3 silver badges13 bronze badges 3
  • 1 var directionsDisplay = directionsDisplay = new google.maps.DirectionsRenderer();? – Anto Jurković Commented Jun 14, 2014 at 20:36
  • I just noticed that, I'll edit the post. – Alex Commented Jun 14, 2014 at 20:39
  • Possible duplicate of remove route with google map – Keith Commented Aug 8, 2018 at 15:30
Add a ment  | 

3 Answers 3

Reset to default 6

Remove this from the click-callback:

directionsDisplay = new google.maps.DirectionsRenderer();

This line always creates a new DirectionsRenderer-instance, but when you only want to show 1 route at a time you only need a single instance(which has already been initialized in locate).

There will be no need to clear anything when you use a single instance. A single directionsRenderer will never show more than 1 route, as soon as you call setDirections the previously drawn route will be removed automatically.

Neither of the existing answers worked for me. Discarding directionsDisplay or calling setMap(null) just disconnected the DirectionsRenderer from the map.

Instead keep hold of the DirectionsRenderer instance, and call directionsDisplay.set('directions', null); to reset the directions.

Didn't work for me - I needed this:

// Clear past routes
    if (directionsDisplay != null) {
        directionsDisplay.setMap(null);
        directionsDisplay = null;
    }
发布评论

评论列表(0)

  1. 暂无评论