Erase the destination pin on Google Maps

I am currently working on a project that involves displaying hit markers on google maps along with a route from start to finish.

Although I have successfully displayed the route, I encountered an issue where both the origin and destination have identical co-ordinates. As a result, the destination marker (marker 'D') overlaps the origin marker, as shown below:

Waypoint markers on map

My goal is to hide only the destination marker, but I'm uncertain of how to accomplish this for an individual marker.

The displayRoute function

     displayRoute(directionsService, directionsDisplay) {
    let numberOfHits = this.geo.Data.rows.length - 1;
    let firstHit = this.geo.Data.rows[numberOfHits];
    let lastHit = this.geo.Data.rows[0];
    let wayPoint, i;
    let wayPointsArray = [];

    this.checkForDuplicates('Id', this.geo.Data.rows);

    for (i = 1; i < numberOfHits; i++) {
      wayPoint = this.geo.Data.rows[i];

      if (this.duplicatesArr.indexOf(wayPoint.Id) === -1) {
        wayPointsArray.unshift({
          location: {
            lat: wayPoint.latitude,
            lng: wayPoint.longitude
          }
        });
      } else if (this.duplicatesArr.indexOf(wayPoint.Id) > -1) {
        console.log('wayPoint', wayPoint.Id, 'has already been hit')
      }
    }

    let request = {
      origin: {
        lat: firstHit.latitude,
        lng: firstHit.longitude
      },
      destination: {
        lat: lastHit.latitude,
        lng: lastHit.longitude
      },
      waypoints: wayPointsArray,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    if((request.origin.lat == request.destination.lat) && (request.origin.lng == request.destination.lng)) {
      // Code to hide destination marker
    }

    directionsService.route(request, (response, status) => {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
    });
  }

The geo data

this.geo = {
     "Data": {
      "records": 7,
      "total": 1,
      "page": 1,
      "rows": [
        {
          "Id": 2778,
          "latitude": 51.509697,
          "longitude": -2.2
        },
        {
          "Id": 53,
          "latitude": 50.980598,
          "longitude": -1.36827
        },
        {
          "Id": 2750,
          "latitude": 51.152599,
          "longitude": -1.34676
        },
        {
          "Id": 2778,
          "latitude": 51.509697,
          "longitude": -2.2
        }
      ]
    }
  }

Any assistance with this issue would be highly appreciated!

EDIT

To provide clarification, here is where I have initialized the directionsDisplay:

  createMap() {
let directionsDisplay = new google.maps.DirectionsRenderer;
let directionsService = new google.maps.DirectionsService;

let map = new google.maps.Map(document.getElementById('map'), {
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

let bounds = new google.maps.LatLngBounds();
map.fitBounds(bounds);

directionsDisplay.setMap(map);
this.displayRoute(directionsService, directionsDisplay);

};

This snippet is utilized just before the displayRoute() function is called.

Answer №1

One feature of the DirectionsRendererOptions is the ability to suppress markers.

By setting the suppressMarkers property to true, both the origin and destination markers can be hidden.

To customize the map with your own marker at the origin coordinates, you can utilize the following example based on your provided code snippet:

if ((request.origin.lat == request.destination.lat) && (request.origin.lng == request.destination.lng)) {

  // Code for hiding the destination marker

  var rendererOptions = {
    suppressMarkers: true,
  };

  var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);

  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(request.origin.lat, request.origin.lng),
    map: map
  });

} else {

  var directionsDisplay = new google.maps.DirectionsRenderer();
}

directionsService.route(request, (response, status) => {
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
});

It's worth noting that the snippet assumes the exclusion of the initialization

var directionsDisplay = new google.maps.DirectionsRenderer();
which was not included in your shared code.

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

Angular 6 throws an error stating: "The property 'push' cannot be read of null."

The Cart model is defined as follows: //declaring a cart model for products to add export class Cart{ id:string; name:string; quantity:number; picture:string; } Below is the code for my app.service.ts: import { Injectable, Inject } fro ...

Executing jQuery function through variable reference

My goal is to modify the jQuery function being used based on the value of a switch statement. In this scenario, I want to select the element and then apply the appropriate jQuery function depending on the 'direction' parameter. $('#'+t ...

Sharing and displaying images on Sails JS platform

Using Sails JS, I am attempting to upload an image and display it in a view. Queries: The uploaded image is located in .tmp/uploads, how can I retrieve it from a view? Is there a method to access the uploaded image? The image's name is altered in ...

Is it necessary for me to set up @types/node? It appears that VSCode comes with it pre-installed

Many individuals have been adding @types/node to their development dependencies. Yet, if you were to open a blank folder in VSCode and create an empty JavaScript file, then input: const fs = require('fs'); // <= hover it and the type display ...

Exploring front-end AJAX functionality within a WordPress plugin

As a newcomer to WordPress development, I have been working on writing an AJAX request within a WordPress plugin. To test this functionality, I initially sent the request to an external non-WP server where it worked without any issues. Following the guidel ...

Position the button at the bottom of the page with MUI v5 in a React application

How can I ensure the button is always positioned at the center bottom of the page, regardless of the content height? This is a snippet from my code: const useStyles = makeStyles({ button: { bottom: 0, right: 0, position: "absolute" ...

Is there a simple method I can use to transition my current react.js project to typescript?

I am currently working on a project using react.js and am considering converting it to typescript. I attempted following an article on how to make this conversion but have run into numerous bugs and issues. Is there a simpler method for doing this conver ...

Check for equality with an array of objects when reacting to changes

I have an input field and an array of objects. I want the object with a property named "airplaneCompany" to be displayed as I type. Each character should be checked, and if the object's "airplaneCompany" property starts with 'a', it should b ...

The art of connecting Javascript commands in succession

I'm struggling to grasp the concept of chaining and return in JavaScript. For example, consider the following code snippet: let array = [1, 2, 3] let newArray = array.map(val => val * 10).map(val => val * 10) console.log(newArray) // [100, 200, ...

Having issues with Exit Property functionality in Framer Motion when using react js

Help Needed: Framer Motion Exit Property Not Working I've been trying to get the exit motion to work on Framer Motion with React JS for over a week now, but everything else seems to be functioning correctly. I have installed the latest version of Fra ...

The absence of certain attributes in TypeScript

class DeploymentManager { import { observable, action, makeAutoObservable } from "mobx" public deploymentQueue = observable<IDeploymentProject>([]); public inProgressProjects = observable<IDeploymentProject>[]; public s ...

Creative Solution for Implementing a Type Parameter in a Generic

Within my codebase, there exists a crucial interface named DatabaseEngine. This interface utilizes a single type parameter known as ResultType. This particular type parameter serves as the interface for the query result dictated by the specific database dr ...

Providing static content within the generated code structure by Yeoman for the Angular Fullstack framework

I'm sticking to the code structure generated by Yeoman for an Angular fullstack application. The issue I'm facing is how to include a script called core.js in a file named app.html. <script src="core.js"></script> I can't fi ...

Angular repeatedly executes the controller multiple times

I have been working on developing a chat web app that functions as a single page application. To achieve this, I have integrated Angular Router for routing purposes and socket-io for message transmission from client to server. The navigation between routes ...

Using Vanilla Javascript to implement a dark mode toggle button

I've been struggling with getting a button to properly switch a website to dark mode. I already have a night mode that works based on the user's location and time, so I know the issue lies within my JavaScript... Initially, I tried adding ' ...

Using <span> tags to wrap sentences within <p> tags while maintaining the rest of the HTML formatting

In order to achieve my goal, I have utilized the following code to extract content within tags and encapsulate each sentence in tags for easier interaction. $('p').each(function() { var sentences = $(this) .text() ...

Ensuring the existence of a MySQL database prior to executing a Node.js application

I am currently working on a Node.js/Express application that communicates with a MySQL server using Sequelize. I want to make sure that a particular database is created before the app starts running when using npm start. I think I need to create a one-ti ...

Configuring Next-auth CredentialProvider and setting up redirection

I'm feeling a bit lost when it comes to understanding how the credentials provider and redirects work. The documentation mentions that the credentials provider doesn't support a callback and is specifically for OAuth providers, which I understand ...

Tips for migrating an AngularJS application to Angular

My current project involves implementing a basic search function using AngularJS (link). I want to integrate this feature into an existing Angular application. To do this, I created a new Angular app and transferred the view to app.component.html. <hea ...

Discover how to capture and process POST form data in Angular originated from external sources

I am currently building a website that utilizes Java for the backend and Angular for the frontend. I have encountered a scenario where external websites may transmit data to my site via POST form submissions. For example, ▼ General    & ...