Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing polylines from google maps [duplicate]

I'm using the DirectionsRenderer to display a path, though after I'm done with that I'd like remove the polyline and carry on with things. I don't seem to have control over markers and polylines created by this function.

Does anyone know how to remove such polylines, if it's not possible, other suggestions?

I now you can use the suppress property, though since I'm using the polylines in the first phase, this doesn't really solve anything.

Severely frustrated.. Cheers!

like image 777
user594388 Avatar asked Jan 28 '11 21:01

user594388


People also ask

How do I remove a polyline from Google Maps?

You have to do polyline. setMap(null) , that will remove the line from the map. Documentation.

How do you remove a polyline?

map. clear(); To clear all the polylines, markers etc.. and add the markers again, then drawn the path.


1 Answers

Here is a solution to your problem: either use the suppressPolylines option or remove the renderer from the map

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

var pointA = new google.maps.LatLng(48.86, 2.35);
var pointB = new google.maps.LatLng(33.7167, 73.0667);

function initialize() {

  var rendererOptions = {
      map: map,
      draggable: true
    }
    // Instantiate a directions service.
  directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

  // Create a map and center it on islamabad.
  var islamabad = new google.maps.LatLng(33.7167, 73.0667);
  var mapOptions = {
    zoom: 13,
    center: islamabad
  }
  map = new google.maps.Map(document.getElementById('map'), mapOptions);
  directionsDisplay.setMap(map);
  calcRoute();
}

function calcRoute() {
  var start = pointA;
  var end = pointB;
  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 removeRoute() {
  directionsDisplay.setOptions({
    suppressPolylines: true
  });
  // this "refreshes" the renderer
  directionsDisplay.setMap(map);
};

function removeRouteNull() {
  directionsDisplay.setMap(null);
};
google.maps.event.addDomListener(window, 'load', initialize);
#map {
  height: 280px;
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<button onclick="removeRoute()">Remove route (suppressPolylines)</button>
<button onclick="removeRouteNull()">Remove route (setMap(null))</button>
<button onclick="initialize()">Undo all</button>
<section id="map"></section>
like image 116
user2314737 Avatar answered Oct 23 '22 06:10

user2314737