Using Leaflet JS to implement multiple waypoints on a map

I am trying to create a route with multiple waypoints without hardcoding any data. My waypoints array should dynamically include latitude and longitude values. How can I achieve this?

    var data = [

    {
        "title": 'Chennai',
        "lat": '13.0827',
        "lng": '80.2707',
        "description": '',
        "flag":'1'
    }
  ,
  {
    "title": 'Ramapuram',
    "lat": '13.0317',
    "lng": '80.1817',
    "description": ''

  }
  ,
    {
        "title": 'Kanchipuram',
        "lat": '12.8342',
        "lng": '79.7036',
        "description": '',
        "flag":'1'
    },

  ];
var map = L.map('map');

  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

var routeControl = L.Routing.control({

}).addTo(map);
routeControl.setWaypoints(data);

I have included an image of the output, and my goal is to remove the center marker and set markers at specific locations as needed. https://i.stack.imgur.com/4AYVV.png

Can someone assist me in achieving this? I have updated my code to set waypoints dynamically, but now I want to remove the markers.

Answer №1

It seems like you're looking to create a route with specific waypoints while displaying markers only at the start and end points. You also want to restrict users from adding new waypoints. You can achieve this by implementing a custom control as shown below:

L.Routing.control({
  waypoints: yourWaypoints,
  plan: L.Routing.plan(yourWaypoints, {
    createMarker: function(i, wp, n) {
      if (i == 0 || i == n - 1) {
        return L.marker(wp.latlng, {
          draggable: false // prevent users from changing waypoint position
        });
      } else {
        return false;
      }
    }
  },
  addWaypoints: false // prevent users from adding new waypoints
});

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

Deleting a file and value in JavaScript

Can you help me figure out how to remove the value of q when the .close class is clicked? Here's my code: $(document).on('click', '.close', function () { $(this).parents('p').remove(); }) $('#Q1DocPath'). ...

What causes a TypeError (Invalid response status code) when a 204 response is returned to a fetch() call within a React Server Component?

Take a look at this straightforward Next.js application: https://codesandbox.io/p/sandbox/next-js-app-router-1bvd7d?file=README.md Here is an API route (/api/hello): export default function handler(req, res) { res.status(204).end(); } And there's ...

Adjusting webpage zoom based on different screen sizes

Hey there, I ran into an issue with my web page design. It looks great on my desktop monitors, but when I checked it on my laptop, things went haywire. Strangely, adjusting the zoom to 67% seemed to fix the problem. Both screens have a resolution of 1920 ...

What's the best way to display a bootstrap modal window popup without redirecting to a new page?

I am having trouble implementing a modal window that will display validation errors to the user when they submit a form. Currently, the window is opening as a new view instead of overlapping the existing form's view. How can I adjust my code so that t ...

Nextjs google places autocomplete not providing accurate suggestions

I'm attempting to utilize Google autocomplete to retrieve the names of mosques specifically in the United Kingdom. However, the data I am receiving is global and not limited to mosques. Here is my code: import axios from "axios"; export def ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...

What is the best way to show an array within a string using javascript?

Take a look at this code snippet : const names = ["Alex", "John", "Kit", "Lenny"]; for(let i = 0; i < 4; i++) { $("body").append("<p>" + names[i] + "</p>'); }; Can you figure out how to dynamically add each item in the 'names&a ...

Is it possible to toggle between hide and show functions using Jquery?

I have a question about two jquery functions that I've been struggling with. $(document).ready(init); function init() { $(".alphaleft").hover(function (g) { $(".boxy,.yee").show(); }, function (g) { $(".boxy,.yee").hide(); }); } ...

Is it possible to invoke an AngularJs service by clicking a button?

Recently, I've been working on some AngularJS code involving a service and controller. angular.module('myModule', []).service("AttendanceService", function ($http) { this.getdata = function () { return $http({ ...

Maximizing the potential of typescript generics in Reactjs functional components

I have a component within my react project that looks like this: import "./styles.css"; type InputType = "input" | "textarea"; interface ContainerProps { name: string; placeholder: string; as: InputType; } const Conta ...

The API is providing data, but it's being returned within an ambiguous object. What could be causing this confusion?

Utilizing https and async for simultaneous calls to retrieve two objects, then storing them in an array. The call is structured as follows: if (req.user.isPremium == false) { // Free user - Single report let website = req.body.website0; let builtWit ...

Keep the active button state when it is clicked in React JS within a functional component

When I click on a button, I want to remain in the section while also having the button stay in the background with a color that indicates my selection. This could be for breakfast, lunch, dinner, or any other section. const Categories = ({ categories, fi ...

Refresh Angular component upon navigation

I have set up routes for my module: const routes: Routes = [ { path: ":level1/:level2/:level3", component: CategoriesComponent }, { path: ":level1/:level2", component: CategoriesComponent}, { path: ":level1", component: ...

Determine whether the function name in a given string matches a JavaScript or PHP

I am currently attempting to highlight code and eventually sanitize the HTML, but I am encountering an issue with my regex not matching just the function name and parameters. Regex is not my strong suit and can be quite confusing for me. Additionally, when ...

Encountering an unusual reactivity problem involving Firebase (Firestore) when using Vue.js and Vuefire

I'm facing a strange issue and I'm completely stuck. Here is the component in question: <template> <v-card elevation="0"> <h2>Accounts</h2> <v-simple-table fixed-header height="300px"> <template v ...

What is the best way to access the original observed node using MutationObserver when the subtree option is set to

Is there a way to access the original target node when using MutationObserver with options set to childList: true and subtree: true? According to the documentation on MDN, the target node changes to the mutated node during callbacks, but I want to always ...

Learn how to synchronize global packages across multiple computers using npm

After installing several npm global packages on my work computer, I am now looking to synchronize these packages with another device. In a typical project, we utilize a package.json file to keep track of package details, making it easy to install all the ...

Does D3 iterate through the entire array every time we define a new callback?

It seems that every time a callback is set, d3 loops through the entire array. Initially, I thought that functions like attr() or each() were added to a pipeline and executed all at once later on. I was trying to dynamically process my data within d3&apo ...

Utilize the capabilities of the Dropbox Core API in Javascript to effortlessly transfer and store files on

I am currently developing a chrome-extension that has the ability to upload files to the user's Dropbox folder. I have implemented AJAX requests in my code to handle file uploads, and it is working fine for text-based file extensions such as .txt, .js ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...