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

In Node.js, it is essential to use req.session.save() to ensure that sessions are properly saved

While developing a website with Node.js, Express, and Redis for session management, I noticed an issue where my session variable (isLoggedIn) wasn't being saved after refreshing the page. Strangely, calling req.session.save() after setting the variabl ...

Retrieving a single object from an array in node.js utilizing elemMatch

My goal is to extract a single object from an array of objects in a data collection using elemMatch. Here is the sample data: [ { "_id": "5ba10e24e1e9f4062801ddeb", "user": { "_id": "5b9b9097650c3414ac96bacc", "firstName": "blah", ...

How can I pass the data-attribute ID from JavaScript to PHP on the same index page using ajax?

I am struggling with the title for this section. Please feel free to modify it as needed. Introduction: I have been working on setting up a datatables.net library server-side table using JSON and PHP. Most of the work is done, but I am facing challenges w ...

Performing numerous asynchronous MongoDB queries in Node.js

Is there a better way to write multiple queries in succession? For example: Space.findOne({ _id: id }, function(err, space) { User.findOne({ user_id: userid }, function(err, user) { res.json({ space: space, user: user}); }); }); It can g ...

Initiate Child Event within Parent Component

Before switching tabs in the parent component, I want the child tab to validate itself. My idea is to pass the onActive event from the parent to its children, <ClientInfo/> and <Details/>. This will allow the children to validate themselves a ...

Tips for transferring data from one asynchronous function to another in AngularJS

How to transfer a global variable value between two Angular functions? Here are the two global variables: $scope.genewtId = null; $scope.data1 = null; The two Angular functions in question are: $scope.getID = function() { Service1.getId("abc").then(f ...

Executing API calls utilizing Axios in a NodeJS environment with the Authorization Basic feature

I have developed an API to retrieve a token from PayPal. curl -v POST https://api.sandbox.paypal.com/v1/oauth2/token \ -H "Accept: application/json" \ -H "Accept-Language: en_US" \ -u "CLIENT_ID:SECRET" &b ...

Updating a nested property within an array of objects in MongoDB

Storing grades for an online education application using MongoDB. Here is a sample classRoom document stored in my mongoDB database. StudentGradeObjs are kept in an array within a GradeObject. GradeObjs are stored in an array of GradeObjects inside a class ...

Is there a way to extract both a and b from the array?

I just started learning programming and I'm currently working on creating an API call to use in another function. However, I've hit a roadblock. I need to extract values for variables a and b separately from the response of this API call: import ...

Struggling to identify the cause of the null pointer exception error

Lately, I've been working on developing an Android app and everything was running smoothly up until now. Suddenly, I encountered a null pointer error that has me stumped. The strange thing is that the app was functioning perfectly before this error po ...

Accessing array values depending on DOM response

Generate a string from selected DOM elements I have an object that contains months and their corresponding index numbers (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc} The user can input values like jan or jan,feb,march and I need to return ...

Struggling to reset the first item in an HTML select dropdown with Angular - any tips?

I am having an issue with my dropdown in a modal window. When I first open the modal, the dropdown works as expected. However, if I make a selection and then close and reopen the modal, the selected value remains instead of resetting to 'None selected ...

Ways to conceal a child div element without using any specific ID reference

I encountered an issue where I need to conceal all divs within a parent div except the first one. The challenge is that these divs do not possess any unique identifiers. Is there a way to achieve this task using CSS or pure JavaScript? <div role="list ...

Experiencing AJAX errors 403 and 404 despite successful implementation in other instances

I am facing a perplexing issue with my code that is causing a 403 error when attempting to delete a row. The strange thing is, the code works perfectly on another website I created. The concept is quite simple - attaching an event listener to a button trig ...

sass: node_modules/ionic-angular/themes/ionic.variables.scss

Encountered error during the execution of Ionic Cordova build command sass: node_modules/ionic-angular/themes/ionic.functions.scss Full Error: [11:34:50] sass started ... [11:34:51] sass: node_modules/ionic-angular/themes/ionic.functions.scss, line: 35 ...

Submitting the form may cause disruptions for others

I currently have an email subscription form for my newsletter that is managed through PHP. This form appears in the footer of every page on my website. Check out a demonstration on JSFIDDLE While the form itself functions properly, I am encountering issu ...

Is there a way to trigger an alert once the google map has finished loading?

Is there a method to trigger a function once the Google map has finished loading? My website contains a Google map accessible through this link. The Google map on my site is powered by the Google API using the following URL: http://maps.googleapis.com/map ...

Unforeseen behavior in the definition of requirejs

This first snippet of code is functional: define([ 'jquery', 'underscore', 'backbone' ], function($, _, Backbone,home_template) { var HomeView = Backbone.View.extend({ render: function() { ...

A script error occurs exclusively on dynamic routing in a static web page generated by NUXT

Currently working on a Nuxt.js website and encountering an issue. Initially, nuxt.config.js was set up as below to enable a headless CMS. export default { target: "static", ssr: true, generate: { async routes() { const pages = awa ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...