Deleting graphic lines from google maps

After using the DirectionsRenderer to display a path, I'm struggling to remove the polyline and move on. It seems like I have no control over the markers and polylines created by this function.

Does anyone have a solution for removing such polylines? If not possible, are there any alternative suggestions?

I know that the suppress property can be used, but since I need the polylines initially, it doesn't really help in my case.

Feeling incredibly frustrated... Cheers!

Answer №1

One possible solution to solve your issue is either utilizing the suppressPolylines option or eliminating 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
    }
    // Create an instance of a directions service.
  directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

  // Generate a map and set its center to 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 action "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>

Answer №2

Here is a helpful guide on how to remove a polyline from Google Maps version 3. Hopefully, this solution will assist you.

var drawing = [];
 var pathway = new google.maps.Polyline({
        path: coordinates, //generate an array of LatLng objects
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 2
    });
 drawing.push(pathway);

At this point, all the polyline features are being stored in an array called "drawing". To make them disappear or delete them from the map, you can iterate through them using the following loop:

for (i=0; i<drawing.length; i++) 
{                           
  drawing[i].setMap(null); //or drawing[i].setVisible(false);
}

Answer №3

Employ

[self.polyline removeMap];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

transferring information back and forth between a javascript array and php

Currently, I am developing a design website that allows users to create designs on an HTML5 canvas and save them on the server. All user information is stored in a MySQL database, while the designs are saved in a JavaScript array. My goal is to seamlessly ...

Removing jQuery error label from an HTML block

I need a single command that will remove an error label from my HTML when the field content is changed. It currently works on input and select elements, but not within an input-group. I am looking for a solution that will work universally across all instan ...

Simple Steps to Use JavaScript for Copying Text from Corresponding Address Field to Permanent Address Field

Currently, I am working on creating the address field for a form. One of the features I have implemented is a City List that depends on the selected State through the use of Ajax. However, when I check the checkbox, the corresponding address value does not ...

Unexpected changes are observed in the size of DIV elements when adjusting the SVG viewBox

My aim is to make the <svg> element have the same dimensions for the viewBox as the <div> it is inside. This means that the viewBox values need to match the dimensions of the containing <div>. Here is an example: <div style="width ...

Obtaining the contents of a local directory with JavaScript

Currently, I am attempting to access the contents of a local folder using JavaScript. Despite my efforts with the Filesystem API, an error is consistently appearing: DOMException: It was determined that certain files are unsafe for access within a Web app ...

Using jasmine with Array.from is not a compatible combination

Attempting to utilize Jasmine for testing my code has presented a challenge. The code functions properly in the browser, and Array.from() also works seamlessly in node, as demonstrated below: > t = [1, 2, 3] [ 1, 2, 3 ] > Array.from(t) [ 1, 2, 3 ] ...

Error Encountered While Serializing Products in getServerSideProps in Next.js v14

I am using Next.js version 14.2.3 and I am currently trying to retrieve a list of products from Firestore by utilizing the getProducts function from @stripe/firestore-stripe-payments within getServerSideProps. However, I am facing a serialization error: ...

Tips for swapping out a specific string in an HTML webpage with a different string using JavaScript

For my HTML website, I am trying to replace one string with another using JavaScript. Specifically, within the nodeList "AuthorList," there is a string called "Test String" that needs to be changed to "new test." I have attempted various modifications of ...

How can TypeScript leverage the power of JavaScript libraries?

As a newcomer to TypeScript, I apologize if this question seems simplistic. My goal is to incorporate JavaScript libraries into a .ts file while utilizing node.js for running my program via the console. In my previous experience with JavaScript, I utilize ...

Interpreting Multilayered JSON Objects using JQuery

Hello everyone! I've posted my sample json data below. While I am proficient in PHP, I am relatively new to jQuery. "data":{ "cipher":"true", "size":[ "2.2 Mb", "6.11 Mb", "9.25 Mb", ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

The functionality of updating input values via jQuery AJAX in HTML response is currently not functioning as expected

Hello, I need some assistance. I'm encountering difficulty with jQuery in modifying HTML values that are dynamically inserted through an AJAX response. Here is the link to the JSFiddle. Below is the HTML on the page: <button id="test">test&l ...

What is causing this code to run immediately upon the addition of Promise logic?

The coding scenario written below was supposed to have two 4-second delays. However, when the code is run, it executes immediately. It seems that there might be a lack of understanding on my part regarding some basic concept, or perhaps there's a hidd ...

Are there any events in JavaScript or with jQuery that will detect when the content inside a div is modified?

Possible Duplicate: Detecting changes in element content using jQuery My current challenge involves manipulating the selected option in a select element that only appears after a file upload within a module window. I have struggled to find a way to acce ...

Encountering Undefined Object Error in Angular Framework

I just completed an upgrade to Angular and encountered an issue with the error message 'object is possibly undefined'. I have tried multiple solutions after doing some research online, including using 'if' statements, null coalescing, i ...

Using v-model in Vue 3 will result in modifications to the table class in Bootstrap 5

Below is a snippet of the code I wrote: <table class="table table-striped"> <tr class="table-dark"> <th>#</th> <th>Column 1</th> <th colspan="3">Column 2</th> </tr> <tr ...

Issue with Bootstrap 4 .active class not updating after click

In my ASP.NET MVC core website, I am utilizing bootstrap v4.3.1. The navbar has the .active class on the first li tag: <nav class="navbar navbar-expand-md navbar-toggleable-md navbar-dark bg-navbar fixed-top mb-3"> <div class="con ...

Displaying a dynamic splash screen during the resource-loading process on an Android application

I would like to implement an animated image (currently using a set of PNGs) as a splash screen while my resources are loading. I have successfully displayed the splash screen using this method. However, the issue I am facing is that the splash screen appe ...

Step-by-step guide on implementing a real-time data array counter in React js

I am attempting to create a function that continuously generates new data arrays with an increasing counter. Each second, a new array should be added with the next number in sequence. data={[ { x: 1, y: 1 }, { x: 2, y: 2 }, ...

Angular 2's Implementation of Hierarchical Dependency Injection

I'm encountering a problem with my Angular 2 application. I have a root component, AppComponent, where I've injected a service called ProductService. Now, I am trying to resolve this service in one of the child components, ProductList, but I keep ...