Adjust the itinerary's color using leaflet-routing-machine

Is there a way to change the color of the itinerary from red to a different color using the Leaflet routing machine library? I need to modify the styles option with the L.Routing.Line, but I'm not sure how to do it.

import L from 'leaflet';

class MapController {
  /* @ngInject */
  constructor($http) {
    this.name = 'map';
    this.$http = $http;

    this.map = L.map('map');

    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}{r}.png', {
      attribution: '© OpenStreetMap contributors'
    }).addTo(this.map);

    const control = L.Routing.control({
      waypoints: [
        L.latLng(45.750000, 4.850000),
        L.latLng(45.188529, 5.724523999999974),
        L.latLng(45.00, 5.74)
      ],
      routeWhileDragging: true,
      geocoder: L.Control.Geocoder.photon()
    });
    control.addTo(this.map);
    control.on('waypointschanged', () => {
      console.log(control._routes[0].summary.totalDistance);
      this.distance = `${Math.round(control._routes[0].summary.totalDistance / 1000)} km`;
      this.time = this.secondsToHm(control._routes[0].summary.totalTime);
    });

    new L.Routing.Plan({
      geocoderPlaceholder: (i, numberWaypoints) => {
        return i === 0 ?
          'Starting Point' :
          (i < numberWaypoints - 1 ?
            `Via ${i}` :
            'Destination');
      }
    }).addTo(this.map);
  }

  secondsToHm(d) {
    console.log(d);
    d = Number(d);
    const h = Math.floor(d / 3600);
    const m = Math.floor(d % 3600 / 60);
    return ((h > 0 ? h + " h " + (m < 10 ? "0" : "") : "") + m + " min"); // eslint-disable-line
  }
}

export default MapController;

Answer №1

As per the documentation:

L.Routing.line(yourRoute, {
   styles:[{color: 'black', opacity: 0.15, weight: 9}, {color: 'white', opacity: 0.8, weight: 6}, {color: 'green', opacity: 1, weight: 2}]
});

For more details, refer to

You can also experiment with Control:

L.Routing.control({
   waypoints: waypoints,
   lineOptions: {
      styles: [{color: 'white', opacity: 1, weight: 5}]
   }
}).addTo(this.map)

Check out this resource for customization:

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

An issue arises with ReactJS MaterialUI Stepper when there is an overflow

My struggle with the Material UI Stepper component persists as I attempt to make it suit my requirements, specifically to display multiple steps and handle overflow. However, it stubbornly continues to misbehave by showing unusual separators when there is ...

Karma Jasmine: No executions and no errors detected

I recently started diving into Angular Testing using Karma and Jasmine. However, I encountered an issue after running karma init and creating my first test for a home controller - the result showed Executed 0 of 0 ERROR. It seems like the files are not bei ...

What causes the scrollTop to appear erratic?

There is a simple issue that I find difficult to explain in text, so I have created a video demonstration instead. Please watch the video at this link: The functionality on my page works perfectly when scrolling down, as it replaces images with the next i ...

When using async functions in iterative processes

In my current setup, I am utilizing a for-each loop to handle a list and specifically require element n to be processed only after element n-1 has completed: let elements = ["item1", "item2", "item3"]; elements.forEach(function(element){ someAsyncFun ...

An issue arises in Slate.js when attempting to insert a new node within a specified region, triggering an error

A relevant code snippet: <Slate editor={editor} value={value} onChange={value => { setValue(value); const { selection } = editor; // if nothing is currently selected under the cursor if (select ...

Having trouble figuring out the reason my JavaScript code isn't functioning properly. Any ideas?

Just starting out with javascript and running into an issue, This snippet of code seems to be working as expected: function test(args){ return "12345 - "+args; } console.log(test("678910")); However, this other piece of code is ...

Browsing through a JSON document

Currently, I am attempting to extract schedule information from a JSON file called js/schedule.json. The format of this file is as follows: [ {"date":"12/06/2014","day":"Thursday","kick-off":"21:00","team1":"Brazil","team2":"Croatia","group":"A","stage":" ...

The set for generating dgeni documents is not currently specified

I am facing issues with the dgeni document generation tool where I encounter an error stating that 'Set is not defined', which leads me to believe the error is related to this issue. I have installed dgeni using npm install on both Windows 7 and ...

I possess a pair of arrays, and I aim to transfer certain elements from Array1 to Array2 while maintaining their references

Looking to implement two JavaScript arrays using AngularJS. My goal is to transfer elements from Ar1 to Ar2, and then have any changes made to the values in Ar2 automatically update the values in Ar1 as well. ...

Issue: Module "expose?Zone!zone.js" could not be located

Just started experimenting with Angular 2 and encountering an issue when importing zone.js as a global variable: https://i.stack.imgur.com/gUFGn.png List of my packages along with their versions: "dependencies": { "angular2": "2.0.0-beta.3", "es ...

Leveraging Discord.JS to seamlessly transport users in Discord to their designated voice channel by assigning roles

I'm attempting to transfer all users with a specific role from a voice channel using a command like: !summon @role This command should bring only the users with that specific role to the voice channel where the command was entered My current code is ...

Executing javascript whenever a page is updated

Looking for a solution to ensure that my userscript runs every time an AJAX call modifies any page it is attached to. Is there a way to listen for XMLHttpRequests and trigger the script accordingly? ...

Creating a personalized <select> filter in Angular.js with two different JSON choices

I am working with a Q&A JSON feed that includes the following: "questions": [ { "answer": "Ea et non sunt dolore nulla commodo esse laborum ipsum minim non.", "id": 0, "poster": "Chelsea Vang", "question": "Ex ex elit cu ...

What is the best way to use jQuery ajax to send various row identifiers when updating table data on another PHP page by selecting checkboxes?

When I select both of the green checkboxes, only the most recent table id is sent. The code below includes both the checkbox markup and jQuery function. Checkbox: <div class='md-checkbox has-success'> <input type='checkbox&apo ...

Update the designated dropdown menu using its identification number

I have discovered a way to change the selected dropdown item by value, but I am interested in doing it by the option ID instead. The reason for this is that the values are dynamically generated. Currently, I am working on creating a questionnaire that incl ...

Interact with embedded elements in JavaScript by using the onClick event

Here is a JavaScript code snippet I've been working on: <div> <tr onClick="click1()"> <td> click 1 </td> <td onClick="click2()"> click 2 < ...

The consistent failure of the 201 status node express API is causing major

I am currently working on creating an API using Express. However, when I receive a response from the server, it shows '201 created'. The issue arises when I attempt to make an HTTP request through promises and encounter a false interpretation of ...

Enhancing time slot height on Fullcalendar V5: A step-by-step guide

Curious about adjusting the height of time slots in Fullcalendar V5 - any tips? ...

Converting RGBA to Hex Color Code with Javascript: A Step-by-Step Guide

I attempted to change the rgba color representation to hexadecimal, but I encountered difficulty in converting the opacity value while successfully converting the remaining colors. Here is the snippet of my code: var colorcode = "rgba(0, 0, 0, 0.74)"; ...

The addEventListener method fails to respond to changes in input

Can someone assist me with this issue? I am facing a problem where the input.addeventlistener is not detecting files on change. My setup involves using Vue with Rails. I am looking to trigger the event listener in the mount hook of a Vue component. mo ...