Using Google Maps to trace a line showing the distance traveled

I want to create a 'distance traveled' polyline along a set route using V3 of the Google Maps API.

The polyline should pass through multiple waypoints/legs.

Currently, I am using the DirectionsService to draw the entire route.

In addition, I am utilizing epolys.js to obtain the marker position for the distance traveled.

Instead of copying the complete route into a new polyline, I only want to copy the route up to the marker position.

To see a demo, visit: http://codepen.io/1983ron/pen/wKMVQr

Here is where I am with the JavaScript code:

var geocoder;
var map;
var marker;
var gmarkers = [];
var METERS_TO_MILES = 0.000621371192;
var walked = (Math.round(670 * 1609.344));

// More JS code...
...
...

Any assistance would be greatly appreciated.

Answer №1

As you construct the line, calculate its length. Once it exceeds the "walked" distance, stop adding points to it.

var lengthMeters = 0;
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
    var steps = legs[i].steps;
    for (j = 0; j < steps.length; j++) {
        var nextSegment = steps[j].path;
        for (k = 0; k < nextSegment.length; k++) {
            if (lengthMeters <= walked) { 
                // Keep adding to the polyline if its length is less than "walked"
                polyline.getPath().push(nextSegment[k]);
                if (polyline.getPath().getLength() > 1) {
                   var lastPt = polyline.getPath().getLength() - 1;
                   lengthMeters += google.maps.geometry.spherical.computeDistanceBetween(polyline.getPath().getAt(lastPt - 1), polyline.getPath().getAt(lastPt));
               }
            }
            bounds.extend(nextSegment[k]);
         }
    }
}
polyline.setMap(map);

View proof of concept fiddle here

Code Snippet:

var geocoder;
var map;
var marker;
var gmarkers = [];
var METERS_TO_MILES = 0.000621371192;
var walked = (Math.round(670 * 1609.344));
// More code snippets...
html,
body,
#map,
#container {
  height: 100%;
  width: 100%;
  background: #000;
  padding: 0px;
  margin: 0px;
}
<div id="container">
  <div id="map"></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE">
</script>

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

Continuously transmitting PNG files to a server. I intend to instruct the receiving browser to automatically refresh at set intervals

I have a continuous task where my code is uploading a png to an http server every few seconds. I am looking for a way to implement some kind of marker that will trigger the browser to automatically refresh every 500ms, either through browser-side javascrip ...

"Extracting information from the axios header and passing it to a Vue component: A step-by-step

I am working with an axios apiClient and trying to retrieve the email stored in localStorage to use in the header of my component. I attempted to access the email by using response.headers['email'] and storing it in a variable called email, but ...

What is the quickest way to redirect a URL in WordPress?

Is it possible to redirect a URL instantly in WordPress using this script code? JavaScript Code: jQuery(document).ready(function() { var x = window.location.href; if (x == 'http://example.com/') { window.location.hr ...

I'm puzzled by the error message stating that '<MODULE>' is declared locally but not exported

I am currently working with a TypeScript file that exports a function for sending emails using AWS SES. //ses.tsx let sendEmail = (args: sendmailParamsType) => { let params = { //here I retrieve the parameters from args and proceed to send the e ...

Why is the body the last element in Angular modules arrays?

I have a question regarding architectural practices. When defining an Angular module, one common approach is to do it like this: angular.module('app', []) .controller('Ctrl', ['$scope', function Ctrl($scope) { //body.. ...

What are some effective methods for incorporating large JSON data into a node.js script?

What is the best way to import a large JSON file (550MB) into a node.js script? I attempted: var json = require('./huge-data-set.json') The script was run with an increased --max-old-space-size parameter node --max-old-space-size=4096 diff.js ...

Overlap one element entirely with another

Currently, I am working on a way for an element called overlayElement to completely cover another element known as originalElement. The overlayElement is an iFrame, but that detail may not be significant in this scenario. My goal is to ensure that the over ...

Neglecting the inclusion of a property when verifying for empty properties

In the code snippet below, I have implemented a method to check for empty properties and return true if any property is empty. However, I am looking for a way to exclude certain properties from this check. Specifically, I do not want to include generalReal ...

Typing the url in the address bar when using Angular's ui-router

Two distinct states are present: .state('test', { url: '/test', templateUrl: 'js/angular/views/test.html', controller: 'UserController', }) .state('test.list', { url: ' ...

Tips for making a sidebar sticky when scrolling

In order to keep the right-side bar fixed, I have implemented this javaScript function: <script type="text/javascript> $(document).ready(function () { var top = $('#rightsidebar-wrapper').offset().top - parseFloat($('#rightsideb ...

How can I determine when a WebSocket connection is closed after a user exits the browser?

Incorporating HTML5 websocket and nodejs in my project has allowed me to develop a basic chat function. Thus far, everything is functioning as expected. However, I am faced with the challenge of determining how to identify if connected users have lost th ...

Perform a check on the state of the slideToggle using an if-else function and provide a report on the slideToggle state

http://jsfiddle.net/vmKVS/ I need some help understanding the functionality of slideToggle using a small example. After toggling for the first time, the options element changes color to green. However, I expected the menu element to turn red when I togg ...

Simple Way to Show API Output in Plain Text (Beginner Inquiry)

I'm a beginner when it comes to using APIs. I'm trying to display the plain text response from this URL on my webpage: However, I'm encountering issues with getting it to work. Here's my code: <script src="https://ajax.googleap ...

Populating a Listview in jqueryMobile with dynamic elements

I am struggling with my listview. Whenever I try to add or remove items from the list, the jquery mobile styling does not get applied to the new content that is added. <ul data-role="listview" id="contributionList"> <li id="l1"><a>5. ...

I am unable to generate a vite application within WSL

My system is running node version 10.19.0 and npm version 6.14.4. Whenever I try to run create-vite@latest client, I encounter the following error: npx: installed 1 in 0.79s /home/victor/.npm/_npx/86414/lib/node_modules/create-vite/index.js:3 import &apos ...

Encountered an error while trying to download a PDF document in React

I'm currently working on adding a button to my website portfolio that allows users to download my CV when clicked. The functionality works perfectly fine on my localhost, but after deploying it to AWS Amplify, I encountered an error. The error occurs ...

Determine the height of an element within an ng-repeat directive once the data has been fetched from an

After sending an ajax request to fetch a list of products, I use angular's ng-repeat to render them. I am attempting to retrieve the height of a div element that contains one product in the list. However, the console always displays "0" as the result ...

Replicate the functionality of a backend API using AngularJS

Currently, I am in the midst of creating a GUI for an application that is still undergoing API development. Although I have a vision of how it will look, it lacks functionality as of now. Hence, I need to replicate its behavior until the API is fully funct ...

Webpack fails to resolve paths provided by a JavaScript variable

I am currently developing an application using vue and ionic, but I have encountered an issue with loading assets as the paths are not resolving correctly. <template> <div id="index"> <img :src="image.src" v-for="image in image ...

Refresh the page and witness the magical transformation as the div's background-image stylish

After browsing the internet, I came across a JavaScript script that claims to change the background-image of a div every time the page refreshes. Surprisingly, it's not functioning as expected. If anyone can provide assistance, I would greatly appreci ...