Utilize Mapbox-GL.JS to animate several points along designated routes

I'm encountering issues with the following example:
Animate a point along a route My goal is to add another point and routes in the same map container.
Here's what I've tried so far:

mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t0IiwiYSI6ImNqa2k3azQ1dzA1Zmgza3B1czIxOGhhaW4ifQ.h5OT3NaQf0vcxx3g1q1cXw';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v9',
    center: [118.0148634, -2.548926],
    zoom: 4.1
});
/**
* Similar routes and points code from original text goes here...
*/
// A single point that animates along the route.
// Coordinates are initially set to origin.
/**
* More points and routes code from original text goes here...
*/

// Calculate distance between start/end points in kilometers.
for(i=0;i<2;i++) {
   var lineDistance = turf.lineDistance(route.features[0], 'kilometers');
}
   console.log(lineDistance) 

/**
* Animation and other map functionalities code from original text goes here...
*/


.overlay {
    position: absolute;
    top: 10px;
    left: 30px;
}

.overlay button {
    font:600 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
    background-color: #3386c0;
    color: #fff;
    display: inline-block;
    margin: 0;
    padding: 10px 20px;
    border: none;
    cursor: pointer;
    border-radius: 3px;
}

.overlay button:hover {
    background-color:#4ea0da;
}
body { margin:0; padding:0; }
#map { top:0; bottom:0; width:100%;height: 600px }
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>Animate a point along a route</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.50.0/mapbox-gl.css' rel='stylesheet' />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.50.0/mapbox-gl.js'></script>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

   
</head>
<body>
<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/turf/v2.0.0/turf.min.js' charset='utf-8'></script>
<div class="col-md-12">
    <div class="card text-white">
      <h5 class="card-header bg-info">Featured</h5>
      <div class="card-body">
        <div class="col-md-12">
            <div id='map'></div>
            <div class='overlay'>
                <button id='replay'>Replay</button>
            </div>
        </div>    
      </div>
    </div>
</div>

</body>
</html>

Nevertheless, after numerous attempts, Point 1 and Line 1 reach the end successfully while Point 2 and Line 2 stop after Point 1 and Line 1 reach the end. This is my 10th attempt and in previous attempts there were errors in the loop structure. What steps should I take next?

Answer №1

One issue arises from the difference in lengths between the two routes, causing a deviation in the coordinates for the shorter route while still progressing through the longer one. The modification I made below addresses this problem and upon testing it, my edit was successful without any errors.

To achieve uniform speeds between the routes, adjustments are needed. Currently, the shorter route completes much faster and moves at a quicker pace than the longer one. To equalize their speeds, fewer steps should be used for the shorter route. If aiming for completion in the same timeframe, more points must be added to the shorter route or decrease the refresh rate of the shorter one.

mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t0IiwiYSI6ImNqa2k3azQ1dzA1Zmgza3B1czIxOGhhaW4ifQ.h5OT3NaQf0vcxx3g1q1cXw';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v9',
    center: [118.0148634, -2.548926],
    zoom: 4.1
});
var route = {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "LineString",
                "coordinates": [
                   // Coordinates for the first route
                ]
            }
        },
        {
          "type": "Feature",
          "properties": {},
          "geometry": {
                "type": "LineString",
                "coordinates": [
                      // Coordinates for the second route
                ]
            }
        }
    ]
};

// Additional JavaScript code provided...

// CSS styles for overlay button

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>Animate a point along a route</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />

    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.50.0/mapbox-gl.css' rel='stylesheet' />
    // Other included libraries...
   
</head>
<body>
    <div id='map'></div>
    <div class='overlay'>
        <button id='replay'>Replay</button>
    </div>
    <!-- Additional HTML body content here -->

</body>
</html>

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

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...

A guide on adjusting a function to pause execution until a line is complete

In the code snippet below, there is an angularJS function named myFunc: $scope.myFunc = () => { myModule.getConfig().update(params); myModule.go(); myModule.log('ok'); }; Additionally, there is a go function defi ...

Having difficulties in storing the checkbox selections

Whenever I switch components and return back, the checkboxes do not persist. I want to ensure that the checked checkboxes stay checked. For more information and code samples, you can visit this CodeSandbox link: CodeSandbox Link. courses.js import React ...

Tips for refreshing views with Angular JS

I am looking to refresh all the views displayed on my page. The layout consists of a Header, Footer, and Body view. Within the Header view, there is a dropdown menu where users can choose their preferred language. Upon selecting a language, I want all the ...

Initialization of Angular provider $get is missing

Within my 'app.js' file, I have the following code that is used in my config to set up $navigationProvider.doSomething(). When running this code, Test1 and Test3 are alerted correctly, but I'm having trouble with getting my this.$get method ...

Tips for maintaining an open ng-multiselect-dropdown at all times

https://www.npmjs.com/package/ng-multiselect-dropdown I have integrated the ng multiselect dropdown in my Angular project and I am facing an issue where I want to keep it always open. I attempted using the defaultOpen option but it closes automatically. ...

How to change class names dynamically in Vue.js?

I am looking for a way to dynamically change the background color based on a review rating using Vue.js. Ideally, I would like to achieve this with the following code: <div class="review" :style="reviewColor(hotel.average)"> In my methods section, ...

How can you move away from using the url:port scheme with socket.io?

Recently, I've been delving into node.js and socket.io, but I'm struggling to eliminate the need to type "url:port" in the browser. Instead, I want users to simply enter the URL and have everything load up, similar to my work-in-progress single p ...

The mark-compacts were not efficient enough, they approached the heap limit and as a result, the allocation failed. The JavaScript

Currently working with Angular version 7.2 and encountering an issue when running ng serve: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory What does this error mean? How can it be resolved? The ...

Imagine a complex JSON structure with multiple levels of nesting

Take a look at this JSON data : { department_1 : [{ id : 1, name = Joe Smith, email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660c150b0f120e2613150048030213">[email protected]</a>}, ...., { id : 500, name ...

What is the best way to manipulate and update individual counters in React components?

I developed a ticket ordering system for a project, but encountered an issue where increasing the quantity of one ticket also resulted in the incrementation of the other ticket's counter. I suspect this occurs because only one value is stored in the s ...

Is it a wise decision to provide the client with a new token just one minute before the expiration of the old one?

When monitoring my backend, I constantly check the remaining time before the JWT expires, which is set to 15 minutes. If there is only one minute left or less, I generate a new JWT and include it in the response header as a setToken. The front-end can then ...

Assigning index values to child rows in AngularJS: a step by step guide

One of my requirements involves assigning index values to child rows. The structure includes group rows with child rows underneath. Currently, I am using ng-repeat along with $index for the children as shown below: HTML code: <table ng-repeat="nod ...

Cool ways to showcase HTML content in AngularJS

I am completely new to AngularJS. My goal is to display HTML content on the view using AngularJS. I initially tried using ng-model, but it displayed HTML content as a string on the view. After that, I attempted to use ng-bind-html which worked for the in ...

Using the attribute data-ng-repeat along with the <option> tag allows for dynamic iteration and

Hello there, I am a beginner with AngularJS and I am struggling to understand how to create my <option> list. I would like my output to resemble the example in this fiddle: http://jsfiddle.net/XdpJv/ This is what my current code looks like: <se ...

How can I ensure that my HTML form inputs are consistently displayed in the browser when using jQuery/AJAX and SQL queries without needing to

My goal is to show all textarea inputs in the browser even after a page refresh, as currently when I send data from homepage.php using jQuery/AJAX, it disappears upon refresh. The information is sent from homepage.php to data.php via the #textarea input an ...

Dynamically loading an iFrame source and automatically populating input forms using Javascript explained

My current challenge involves retrieving URL parameters successfully and using them to decide which iframe src to populate. Additionally, I need to autofill the form created via the form src with other parameters. However, I am faced with two main issues. ...

Having difficulty generating dynamic rows and tree dropdowns in AngularJS

Struggling to implement dynamic row functionality with Angular JS. The rows are working well, but I also need to incorporate a tree dropdown within each row. Unfortunately, clicking the "add row" button populates the same data in all rows. I have shared m ...

What could be causing issues with angularjs ng-include not functioning properly in Chrome at times?

<html ng-app="myApp1"> <head> <title>NG-Include</title> <script src="angular.js"></script> <script src="filter.js"></script> </head> <body> <div ng-controller="myController"> ...

The html() method is not functioning correctly in ajax requests

I would like to implement a feature where users can like and unlike a book. However, I am facing an issue where the code only executes once without refreshing the page. JAVASCRIPT <script type="text/javascript"> $(document).ready(function() { ...