Is there a way to dynamically update the polyline on the map when I drag a marker to change the path, removing the previous one in the process?

I'm still fairly new to working with Javascript and the Google Maps API. I've come across various solutions to a similar issue that I'm facing, but none of them seem to work for my specific code. I'm starting to question whether the polyline should be redefined each time the function is called, effectively replacing the previous one. Am I missing something here? What steps can I take to remove the "old" polyline when the marker is dragged?

If you'd like to take a look at my code, you can find it here: https://jsfiddle.net/emvee/qqavw3gh/6/

The key lines of code to focus on are 44-53 (which handle events when the marker is being dragged) and lines 171-215 (where the function defining and drawing the polyline based on directions from directionsService is located).

//map details, i.e. creates a map of Lucca
var mapOptions = {
  center: new google.maps.LatLng(43.8430, 10.5050),
  zoom: 15,
  mapTypeId: google.maps.MapTypeId.SATELLITE
};

//create map
var map = new google.maps.Map(document.getElementById('map'), mapOptions);

//marker details and creation omitted for brevity

function calcRoute() {
  //Routing logic implementation inside this function...
}

calcRoute();

Answer №1

To ensure access to the polyline, make it global and remove it from the map (set its map property to null) before creating a new one. When you create a new polyline, you lose access to the previous one, and if it's not global, it will go out of scope when you exit the calcRoute function.

if (poly && poly.setMap) poly.setMap(null);
poly = new google.maps.Polyline({
  path: [],
  strokeColor: "#58FA58",
  strokeOpacity: 1.0,
  strokeWeight: 3
});

Check out the updated fiddle here

Here is the code snippet:

...

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

Guide on adding a personalized table or Div section in a datatable

I am looking to add a custom table above a datatable, specifically I want the custom table to be displayed above the header columns. Here is the code I have tried: columns: [ { "data": "WorkFlowType" }, { "data": "WorkflowInstanceId" } ...

Incorporate External Web Page Information by Clicking a Button

Apologies if this question has already been asked, but despite my efforts to explore the available resources, I have not found a solution to my issue. I currently have an input field where users can enter their website, keyword, or industry. When they cli ...

Is there a way for ASP.NET MVC to automatically notify when a record is edited or updated?

Having recently used the NotifyIcon class in a windows application, I found it to be quite useful. As someone who primarily works as a web developer, I am curious if there is something similar available for websites. The website that I am working on inclu ...

having difficulty with executing ajax post within a JavaScript function

While working on my project, I encountered a small issue. I am able to read the HTML image value and pass it to a JavaScript method successfully. However, when trying to pass this value via AJAX POST to the controller, an unexpected error occurs. The con ...

Tips for invoking the export function in node.js using sequelize

Need help with calling the function (search_all_user) to export in node.js using sequelize module.exports = function (sequelize, Sequelize, DataTypes) { var User = sequelize.define('user', { id: {type: Sequelize.INTEGER, unique: true, prima ...

Is there a way to include an item into a three.js environment during a mouse click event?

Is it possible to dynamically add a 3D object to a three.js scene after it has been initialized and the user triggers a click event? How can this be achieved within the existing code structure provided? You can find a prepared scene setup in this working ...

In Vue Js, the function createUserWithEmailAndPassword does not exist within _firebase_config__WEBPACK_IMPORTED_MODULE_3__.default

My createUserWithEmailAndPassword function seems to be malfunctioning. Here is the code snippet I am using - config.js import firebase from 'firebase/app' import 'firebase/firestore' import 'firebase/auth' const firebaseCon ...

What is the best way to direct users to the individual product page once they make a selection

On my main products page, I am fetching all the products from a local JSON file. interface productItem { id: number; name: string; image: string; price?: string; prices: { half: string; full: string; }; ...

Associating mongoose object with a DTO object in an Express.js application

I am looking for a way to transform mongoose result objects into DTOs for my views. Here is an example query that returns a mongoose object: const returnedData = (err, result) => { //Result object is a schema from Moongose cb(err, re ...

What is the resolution process for importing @angular/core/testing in TypeScript and what is the packaging structure of the Angular core framework?

When using import {Injectable} from '@angular/core';, does the module attribute in package.json point to a file that exports injectable? Also, for the format @angular/core/testing, is there a testing folder within @angular/core that contains anot ...

Using more than one button to activate a single Material-UI Popper component

I recently found myself in a situation where I needed to activate the Material-UI <Popper /> component from various clickable elements. According to the Popper component API on the official Material-UI website, setting the anchorEl property determine ...

Data has not been submitted to the MongoDB database

I attempted to save form data in my mongodb database (mongodb compass). However, after submitting the form, I checked the database and found that it was empty. When I clicked the sign-up button, it only displayed curly brackets. Main file - App.js co ...

Why am I receiving an undefined value when I try to log the createdAnimal?

My main goal with this code is to successfully console.log(createdAnimal) and have the objectAnimal with specific parameters printed out. The following code snippet demonstrates the desired parameters: animalMaker('cat','flying',true); ...

Upload the image data into the input file tag

Is there a way to take a string code stored in a JavaScript variable that is retrieved from the Cropit plugin (used for cropping images) and then set this information into an input file tag? I want to be able to send it via AJAX to PHP. Here is the JavaSc ...

Steps to display text in a div upon clicking on an image

I am trying to create an image with two DIVs separated by a black line. The left DIV will contain 4 images, and I want the following functionality: When a user clicks on any of the buttons in the left DIV, a corresponding text should be revealed in the ri ...

Add elements to an array following an AJAX request

On my .cshtml page, I have the following script: $(function () { var tempArray = []; var tbValue = $('#tb1').val(); $.ajax({ url: "/ControllerName/getdata", dataType: 'json', ...

Enhance your Three.js experience: Effortlessly Panning Panoramas with Smooth E

I am currently working on a 6 cube panorama project and using this demo as a reference: The dragging functionality in this demo is controlled by mouse events. I am looking to implement easing so that the panorama cube follows the mouse smoothly. I underst ...

JavaScript: Scroll Through Images Horizontally with Descriptions for Each Image

I am looking to create a horizontal scroller/slider that will display images with captions underneath each image. The data is provided in an array of objects, so I need to iterate through the data and populate each item in the scroller with the necessary i ...

Implementing translation functionality within an AngularJs controller

Utilizing angular translate for translating certain words in the controller, with translation stored in json files within the html. // LABELS var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "Septe ...

Maintain Bullet and Arrow Size with JSSOR Scaling Feature

I am currently utilizing the jssor image slider with jquery and overall, it is functioning well. However, I have encountered an issue when attempting to resize the slider. My goal is to dynamically resize the slider whenever the window width changes. The ...