Is there a way to remove or replace the existing polyline to ensure that only one is displayed at a time?

My goal is to have a single line drawn from the closest marker to a static position. I can determine which marker is the closest by sorting the distances, but if a new marker is added and is closer than the previous closest one, a new polyline is drawn with the old one still present.

    var sorted = pathArr.sort(function (a, b) {
        var aValue = Math.abs(parseFloat(a['distance']));
        var bValue = Math.abs(parseFloat(b['distance']));

        if (typeof aValue && bValue == "number") {
            return (aValue > bValue) ? 1 : ((bValue > aValue) ? -1 : 0);
        }

        return (aValue > bValue) ? 1 : ((bValue > aValue) ? -1 : 0);
    });
    console.log(sorted);

    pathCoordinate = [{lat: lat1,  lng: lon1}, {lat: sorted[0].lat, lng: sorted[0].lng}];

    line = new google.maps.Polyline({
        path: pathCoordinate,
        geodesic: true,
        strokeColor: '#FF0000',
        strokeOpacity: 1.0,
        strokeWeight: 2
    });

    line.setMap(map);

I've attempted using

    line.setMap(null);

without success.

Answer №1

If there is an existing line with a setMap method, make sure to set its map property to null (remove it from the map) before creating a new line.

var sorted = pathArr.sort(function(a, b) {
  var aValue = Math.abs(parseFloat(a['distance']));
  var bValue = Math.abs(parseFloat(b['distance']));

  if (typeof aValue && bValue == "number") {
    return (aValue > bValue) ? 1 : ((bValue > aValue) ? -1 : 0);
  }

  return (aValue > bValue) ? 1 : ((bValue > aValue) ? -1 : 0);
});
console.log(sorted);

pathCoordinate = [{
  lat: lat1,
  lng: lon1
}, {
  lat: sorted[0].lat,
  lng: sorted[0].lng
}];

if (line && line.setMap) line.setMap(null);
line = new google.maps.Polyline({
  path: pathCoordinate,
  geodesic: true,
  strokeColor: '#FF0000',
  strokeOpacity: 1.0,
  strokeWeight: 2
});

line.setMap(map);

view example on fiddle

code snippet:

var geocoder;
var map;
var pathArr = [];
var lat1 = 37.4419;
var lon1 = -122.1419;
var line;

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  /* pathArr.push({
    lat: 37.4419,
    lng: -122.1419,
    distance: google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(37.4419, -122.1419), map.getCenter())
  }); */
  google.maps.event.addListener(map, 'click', addPoint);
}
google.maps.event.addDomListener(window, "load", initialize);

function addPoint(evt) {
  pathArr.push({
    lat: evt.latLng.lat(),
    lng: evt.latLng.lng(),
    distance: google.maps.geometry.spherical.computeDistanceBetween(evt.latLng, map.getCenter())
  });
  var sorted = pathArr.sort(function(a, b) {
    var aValue = Math.abs(parseFloat(a['distance']));
    var bValue = Math.abs(parseFloat(b['distance']));

    if (typeof aValue && bValue == "number") {
      return (aValue > bValue) ? 1 : ((bValue > aValue) ? -1 : 0);
    }

    return (aValue > bValue) ? 1 : ((bValue > aValue) ? -1 : 0);
  });
  console.log(sorted);

  pathCoordinate = [{
    lat: lat1,
    lng: lon1
  }, {
    lat: sorted[0].lat,
    lng: sorted[0].lng
  }];

  if (line && line.setMap) line.setMap(null);
  line = new google.maps.Polyline({
    path: pathCoordinate,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2
  });

  line.setMap(map);
}
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map_canvas"></div>

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

Consistently encountering the message 'Error: timeout of 2000ms exceeded' while using Selenium

Good morning, Currently, I am in the process of learning how to use Selenium with JavaScript (specifically using Mocha). I have created a very basic test that is causing some issues during runtime. Whenever I run the test, a new instance of Chrome opens a ...

The AJAX call failed because the web service was not properly configured, resulting in a missing parameter value being

I'm encountering an issue with my ajax call that displays a specific message. [WebMethod(EnableSession = true)] public static string UpdateTotalPrice(List<TicketPriceAjax> jsonTickets) { // conducting server-side processing return "a u ...

Minify Magic Dreamweaver Plugin

Does anyone know of a plugin that can minify javascript or css files as they are uploaded using Dreamweaver or similar coding software? For example, if I create a file like functions-global.js, the plugin would upload the original file and also generate a ...

Incorporate Jquery Append and Each functions into Class addition

I've encountered an issue while trying to retrieve information in JSON format and add an ID to each element. Despite my efforts, my code is not functioning as intended. Although the appending process is successful and I can see all my results in JSON ...

Transformer Class: An object containing properties that are instances of another class

class ClassA { x: number; y: number; sum(): number { return this.x + this.y; } } class ClassB { @Type(() => ClassA) z: {[key: string]: ClassA}; } const b = transformObject(ClassB, obj); const z = b.z[key]; const s = z.s ...

Can you share the outcomes of executing a Node.js program in real-time?

Is there a method to execute a program (such as tcpdump) and have nodejs capture the console output in real-time to display in an HTML format without saving it? I am interested in running a program that displays information in the console, with the capabi ...

Compatibility of Typescript with local storage

Can Typescript interact with local storage in any way? I have been setting items using the following code: localStorage.setItem('someString', JSON.stringify(MyTypescriptObject)); This method stores the object as a plain string. For example: ...

How to style the background color of the selected option in a <select> element using

Is there a specific style I can use to change the color of a selected option in a dropdown menu? For example: <HTML> <BODY> <FORM NAME="form1"> <SELECT NAME="mySelect" SIZE="7" style="background-color:red;"> <OPTION>Test 1 &l ...

Enhancing TypeScript Types with a custom method within an Angular 2 context

I am working on an Angular 2 project using the CLI. Currently, I am trying to add a custom method to the String type as shown below. interface String { customMethod(): number; } String.prototype.customMethod = function() { return 0; } Despite my ...

Animating object on display and returning it with keyframes

Given the code snippet below: <div class="leftBox"> <div class="mainNode" ></div> </div> <script type="text/javascript"> $('.mainNode').click(function() { var element = $('.mainNode'); if (!ele ...

Issue with jQuery ajax in Internet Explorer 6

Hey there, I'm dealing with a strange issue: The success handler in my $.ajax call looks like this: function(data){ alert(data); } Seems pretty straightforward, right? The problem I'm facing is that the data sent by the server is ALW ...

Bot on Discord engaging in a gaming session

I recently developed a Discord bot with the status of ""playing a game"" and here is the code that I implemented: bot.on('ready', () => { console.log('Client is online!'); bot.user.setActivity('osu!'); Th ...

Unable to display canvas background image upon webpage loading

Currently working on a JavaScript project to create a captcha display on a canvas. The issue I'm facing is that the background image does not load when the page initially opens. However, upon hitting the refresh button, it functions as intended. Here& ...

When changing recipients in Firebase, the Javascript code fetches the same message multiple times even though there is only a single message stored in the database

In the process of developing a chat application using Firebase and JavaScript, I have come across an issue. Whenever I switch receivers multiple times, the message I send is fetched multiple times even though it is only sent once to the database. var selec ...

Creating beautifully formatted PDFs using pdfmake in AngularJS

I have a HTML popup displaying data retrieved from the server, and I am attempting to download this data as a PDF using the pdfmake plugin. While I am able to generate the PDF file, the challenge lies in replicating the HTML page layout in the PDF. Here is ...

issue with transparent html5

Here is the code snippet I am struggling with: function clear(){ context2D.clearRect(0, 0, canvas.width, canvas.height); } function drawCharacterRight(){ clear(); context2D.setTransform(1, 0.30, 1, -0.30, 10, 380);//having issues here c ...

What is the best way to incorporate and execute a separate JavaScript file in a Node application using Express JS?

I am attempting to configure a javascript file that is responsible for grabbing an RSS feed and storing the information in a database. Originally, I had this file called by the HTML page, but now I want it to continuously run in the back-end (constantly re ...

Prevent unnecessary image resizing during parallax scrolling animation

Check out my demonstration where the image scaling results in the margin-top of the parallax wrapper being unable to dynamically adjust. Demonstration: http://jsfiddle.net/KsdeX/12/ .wrapper-parallax { margin-top: 150px; margin-bottom: 60px; } W ...

Retrieving JSON information from a lone field in a MySQL table

I am currently working with a PHP REST Web service that is being accessed from JavaScript. Everything works fine when I run a MySQL SELECT statement to select text fields and then use json_encode to convert the returned array into JSON objects. However ...

After saving any HTML, SCSS, or TS file, Angular 12 does not compile immediately

Recently I upgraded my Angular project from version 8 to 12 and then migrated to eslint. However, I have encountered an issue where the compilation does not begin immediately after saving a file. There is a delay of approximately 2 minutes before the compi ...