The Google Maps directions stay visible even when new routes are generated

Utilizing the Google Maps Javascript API V3 in my Android WebView has presented a new issue. When I request directions from point A to B, it displays correctly. However, when I switch the endpoints to go from A to C, the route from A to B does not disappear and ends up overlapping with the newly generated route from A to C.

A to B

A to C

Button to proceed with directions

direction.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        button.setVisibility(View.INVISIBLE);
        infowindow.setVisibility(View.INVISIBLE);
        String centerUrl = "javascript:direction(" + Lat + "," + Lng + "," + LatNew + "," + LngNew + ")";
        webView.loadUrl(centerUrl);
    }
});

HTML

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  #map {
    height: 100%;
  }
</style>
</head>
<body>
<div id="map"></div>
<script>
    var myLatLng,endLatLng;
    var map;
    var marker,beachMarker,eatMarker,drinkMarker;
    var location;

    function initMap() {

        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 17,
          center: myLatLng
        });

        // Marker initialization code continues here...

    }

    // Additional functions like centerAt and direction continue as before...

</script>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&callback=initMap"></script>

How can I remove the old route display when changing destination points?

Answer №1

It is recommended to utilize a global variable for directionsDisplay instead of a local one within the direction function. Within the direction function, you should first set directionsDisplay to null and then assign it to the new instance.

<script>
var myLatLng,endLatLng;
var map;
var marker,beachMarker,eatMarker,drinkMarker;
var location;
var directionsDisplay;

function direction(latitude,longitude,latitudeNew,longitudeNew) {
    var directionsService = new google.maps.DirectionsService;
    if (directionsDisplay != null) {
       directionsDisplay.setMap(null);
    }
    directionsDisplay = new google.maps.DirectionsRenderer;

    .....

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

Iterating through a JavaScript object

Just starting out with JavaScript and trying to figure out how to iterate through a JSON result that has been converted into a JavaScript object. const url = 'https://api.mybitx.com/api/1/tickers?pair=XBTMYR'; fetch(url) .then(res => re ...

The process of transferring ViewBag value as a parameter in an AngularJS function

I'm facing an issue where the viewbag value is not being passed as a parameter in ng-init. Can someone guide me on how I can successfully pass the viewbag value as a parameter? angular.js { $scope.detail = function (Id) { ...

Dynamic anime-js hover animation flickering at high speeds

I have implemented the anime-js animation library to create an effect where a div grows when hovered over and shrinks when moving the mouse away. You can find the documentation for this library here: The animation works perfectly if you move slowly, allow ...

Guide on how to choose a radio button in IONIC with the help of angularJS

<ion-list> <ion-radio ng-model="choice" ng-value="'A'" ng-click='usedGNG("yes")'>Yes</ion-radio> <ion-radio ng-model="choice" ng-value="'B'" ng-click='usedGNG("no")'>No</ion-radio> </ ...

Creating custom markers with an API in Vue-2-Leaflet

I'm having trouble displaying markers using an API. I can retrieve the data from the API and store it in a variable, but for some reason the markers aren't showing up when I try to display them using a v-for loop. Any assistance would be greatly ...

Error Received While Attempting to Log in using Ajax

Having an issue with logging in using ajax and php. I am able to log in successfully, but when trying to display an alert message and refresh the page upon login, it gives me an error without refreshing. However, upon manually refreshing the page, I can se ...

The text field is unable to receive input by clicking a button, only registering values when physically typed into the field

I have three text fields with buttons to increment or decrement the value, and a final text field that displays the calculation of the values in each field. Everything is functioning correctly, however, the issue arises when I try to add values using the ...

What is the optimal strategy for incorporating both useLazyQuery and useQuery within the Apollo-client based on specific conditions?

In the navigation menu, I have options for "foods" and "cakes." The Foods page displays a list of all food items url: /foods When the user clicks on cakes, they are redirected to /foods?food=cakes, which is essentially the same page as the foods above. ...

Is the three.js.master folder necessary for utilizing OBJLoader2.js? I keep getting a 404 error when trying to access it

As I venture into using three.js, I am attempting to import an OBJ file using OBJLoader2.js locally (without npm). However, I am encountering a 404 error for three.module.js, MeshReceiver.js, and OBJLoaderParser when trying to add import {OBJLoader2} from ...

What is the process for retrieving the value of `submit.preloader_id = "div#some-id";` within the `beforesend` function of an ajax call?

In my JavaScript code, I have the following written: var formSubmit = { preloaderId: "", send:function (formId) { var url = $(formId).attr("action"); $.ajax({ type: "POST", url: url, data: $(formId).serialize(), dataTy ...

Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Goog ...

A step-by-step guide on how to insert an image URL into the src attribute using the

The source of my image is -> src/assets/images/doctor1.jpg I would like to use this image here -> src/components/docNotes/docNotes.js In the docNotes.js file, I attempted -> <Avatar className={classes.avtar} alt="Remy Sharp" src ...

Troubleshooting: Resolving the error message "SyntaxError: Unexpected token '<'"

I am currently facing an issue with my code that is supposed to use LAT&LONG data saved in a txt file and display it as a Google Map in HTML. However, the PHP function to import the txt file is not working at all. Any suggestions on what might be causi ...

A guide to generating dynamic table headers using JSON in React

Looking to create a dynamic table with columns/headers in React based on a JSON array of objects. The data: example = [ { id: 0, city: 'New York', }, { id: 1, city: 'Paris', }, ] Currently, I'm iterating ...

Experiencing memory issues with small programs in Node on macOS?

Currently, I am in the process of learning JavaScript and making use of node to execute JS programs directly from the terminal using this command: node program1.js The issue that I am encountering involves a simple JavaScript program that is supposed to ...

Vue.js does not support animation for the Lodash shuffle function

I'm having trouble getting the lodash's shuffle method to animate properly in Vue.js. I followed the code from the documentation, but for some reason, the shuffle occurs instantly instead of smoothly. When I tested the animation with actual item ...

Empty Ajax array sent to PHP

I am encountering an issue with my ajax form where the values in an array are coming out as null in my PHP response. I suspect that there may be a mistake in my .ajax call. Can anyone provide suggestions or insights on how to resolve this issue? My code sn ...

In what situations is it beneficial to utilize inherited scope, and when is it best to avoid it

Is it better to use inherited scope (i.e scope:true) when creating a directive, or is it more appropriate not to use it (i.e scope:false)? I grasp the distinction between scope types and their respective functionalities. However, I am uncertain about whic ...

Tips for showcasing a restricted amount of data with Angular.js

I've been exploring different ways to limit the results using limitTo, but unfortunately, I'm encountering unexpected issues. Currently, the entire list is being displayed when I only want to show 8 key-value items in a 4/4 block format. You can ...

Accessing Firebase data using randomly generated keys

I need to extract the values associated with each key from my JSON file named cardInfo. "cardInfo" : { "-KF3fzOc3e68jRpCkLRb" : 6869098993309203, "-KF3g0fQUJHcexwAFzxz" : 6764366404306628, "-KF3hHOdj-siBxLMNgLa" : 4368998299921 ...