Waypoints unable to display - Google Maps API issue

I am attempting to retrieve the waypoints from an AXIOS call and utilize the response to populate the city into a waypts array. Unfortunately, when I try to include the waypoints in the route, the map only shows the route from the starting point to the destination without displaying any waypoints. The console does not show any waypoints being requested. Manually adding the waypoints results in their appearance on the map. Checking the console log reveals that waypts is appropriately formatted for the waypoints field in the route. Additionally, the filterselect within the initMap() function pertains to a dropdown in the vue component's template containing all the route IDs.

overview.js

function calculateAndDisplayRoute(context, directionsService, directionsDisplay) {
  var origin, dest;
  var waypts = [];
  var stops;
  for (var i=0; i < context.routes.length; i++) {
    if(context.routes[i].id == context.filter){
      origin = context.routes[i].start;
      dest = context.routes[i].dest;
      stops = Promise.resolve(getAllStops(context.routes[i].id));
      stops.then(function(value) {
        for (var i = 0; i < value.length; i++) {
          if(!(value[i].city === dest)){
          waypts.push({
                    location: value[i].city.toString(),
                    stopover: true
                  });
              }
        }
        })
      break;
    }
  }
  console.log(waypts)
  directionsService.route({
    origin: origin,
    destination: dest,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status === 'OK') {
      console.log(response)
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

async function getAllStops(routeid){
  var stops=[];
  var thisResponse =[];
  try{
    let response = await AXIOS.get('/api/route/getStops/' + routeid + '/', {}, {});
    thisResponse = response.data;
    for (var i = 0; i < thisResponse.length; i++) {
    stops.push(response.data[i]);
    }
  }catch(error){
    console.log(error.message);
  }
  return stops;
}
//...
methods: {
      initMap: function(){
        this.$nextTick(function(){
          var directionsService = new google.maps.DirectionsService;
          var directionsDisplay = new google.maps.DirectionsRenderer;
          var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 45.49, lng: -73.61},
            zoom: 9
          });
          directionsDisplay.setMap(map);
          var thisContext = this;
          var onChangeHandler = function() {
            calculateAndDisplayRoute(thisContext, directionsService, directionsDisplay);
          };
          document.getElementById('filterselect').addEventListener('change', onChangeHandler);
        })
      }
}

Console log (waypts, then response) for route 83 https://i.sstatic.net/cfroz.png

AXIOS Response for routeid 83

[{"locationId":84,"city":"Johannesburg","street":"28th","user":{"ratings":[4.5,4.8,4.1,2.8],"username":"elle12","password":"****","firstName":"Elle","lastName":"Woods","phoneNumber":"**********","city":"Cape Town","address":"*** Trinidad","avgRating":4.05,"numTrips":4,"role":"passenger","car":null,"status":"Active","request":null},"route":{"routeId":83,"seatsAvailable":1,"startLocation":"Cape Town","date":"2018-12-04T15:00:00.000+0000","car":{"vehicleId":81,"brand":"Tesla","model":"X","licensePlate":"123456","driver":{"ratings":[4.0],"username":"nono12","password":"****","firstName":"Noam","lastName":"Suissa","phoneNumber":"**********","city":"Montreal","address":"345 road","avgRating":4.0,"numTrips":1,"role":"driver","car":null,"status":"Active","request":null},"route":null},"status":"Scheduled","stops":null},"price":13.0},
{"locationId":85,"city":"Hoedspruit","street":"Kruger","user":{"ratings":[2.8],"username":"george12","password":"****","firstName":"George","lastName":"Lasry","phoneNumber":"**********","city":"Johannesburg","address":"*** Hamt","avgRating":2.8,"numTrips":1,"role":"passenger","car":null,"status":"Inactive","request":null},"route":{"routeId":83,"seatsAvailable":1,"startLocation":"Cape Town","date":"2018-12-04T15:00:00.000+0000","car":{"vehicleId":81,"brand":"Tesla","model":"X","licensePlate":"123456","driver":{"ratings":[4.0],"username":"nono12","password":"****","firstName":"Noam","lastName":"Suissa","phoneNumber":"**********","city":"Montreal","address":"345 road","avgRating":4.0,"numTrips":1,"role":"driver","car":null,"status":"Active","request":null},"route":null},"status":"Scheduled","stops":null},"price":11.0}]

Answer №1

directionsService.route() is called prematurely, resulting in the waypts array not being filled on time.

Here's a fix:

stops.then(function(value) {
  directionsService.route({
    origin: origin,
    destination: dest,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: 'DRIVING'
  }, function(response, status) {
    if (status === 'OK') {
      console.log(response)
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
});

Make sure it's Minimal. Complete. Verifiable.

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

Tips for adding content to a textarea after making manual changes to its existing content

One issue I encountered is with capturing the enter key on an input field and appending it to a textarea. While this works initially, any edits made directly on the textarea seem to disrupt the functionality. How can this be resolved? I have tested this i ...

The data shown in the C3.js tooltips

I have successfully created a chart like this on jsfiddle: http://jsfiddle.net/q8h39/111/ The chart includes customized tooltip contents for each plot. I attempted to add extra data to the tooltip using the "indexOf()" method, but unfortunately, it did no ...

Using JavaScript to Filter Arrays with Partial String Matching

I have an array of objects where the value I need to filter on is nested in a lengthy string. The array is structured as follows: { "data": { "value": & ...

Vue select component not refreshing the selected option when the v-model value is updated

Trying to incorporate a select element into a Vue custom component using the v-model pattern outlined in the documentation. The issue at hand is encountering an error message for the custom select component: [Vue warn]: Avoid directly mutating a prop as i ...

What is the best way to transfer a property-handling function to a container?

One of the main classes in my codebase is the ParentComponent export class ParentComponent extends React.Component<IParentComponentProps, any> { constructor(props: IParentComponent Props) { super(props); this.state = { shouldResetFoc ...

Is it possible to set an onmousedown event to represent the value stored at a specific index in an array, rather than the entire array call?

Apologies if the question title is a bit unclear, but I'm struggling to articulate my issue. The challenge lies in this synchronous ajax call I have (designed to retrieve json file contents). $.ajax({ url: "/JsonControl/Events.json", dataTyp ...

Enhance a DOM element using personalized functions in jQuery

Seeking advice on how to create custom widget placeholders with a "setvalue" function specific to each type of widget: $.fn.extend($(".dial"), { setval: function(val) { }); Attempting to avoid extending jQuery.fn directly since different widget type ...

How to use RegExp to locate the final return statement within a JavaScript code string

Take a look at this code snippet: cont x = 10; function foo() { return x; // ;; end of function ;; // /* here is a some text here too */ } function bar() { return 10 } return foo() + bar(); // ;;done;; // /* yolo yolo */ This string cont ...

Error: Unable to locate module '@material-ui/lab/TabContext' in the directory '/home/sanika/Desktop/Coding/React/my-forms/src/Components'

Hello everyone! I recently started working with ReactJs and I'm currently facing an issue while trying to implement TabContext using the material UI library in React. Upon debugging, I suspect that the error might be related to the path configuration. ...

Dynamically import and load components in vue.js

I am attempting to dynamically import a component from a folder with the following code. However, for some reason Vue is not importing anything or displaying an error. It's almost as if it's not detecting any changes in the computed field. What ...

Transfer the index of a for loop to another function

Can you explain how to pass the 'i' value of a for loop to a different function? I want to create a click function that changes the left position of a <ul> element. Each click should use values stored in an array based on their index posi ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...

Leveraging the power of nodejs functions within static HTML files in expressJs

Being a beginner in Javascript and Nodejs, I am uncertain about the best way to organize my project. I am currently working on creating a web interface for a C++ application using Nodejs and V8 to wrap a C++ API. My question is, can I utilize Express to se ...

Avoid displaying duplicate items from the array

Utilizing react js, I am attempting to iterate through an array of objects and display the name of each object in the array: const arr = [ { name:"Bill", age:88 }, { name:"Bill", age:18 }, { name:"Jack", age:55 }, ] ...

Monitor a nested watch property for potential undefined or default values

Currently tackling an issue in my Vue2 project related to a specific property I'm trying to watch. Here's what the code snippet looks like: watch: { 'car.wheels': function(){ ... } Sometimes, 'wheels' is undefined ...

Exploring the directories: bundles, lib, lib-esm, and iife

As some libraries/frameworks prepare the application for publishing, they create a specific folder structure within the 'dist' directory including folders such as 'bundles', 'lib', 'lib-esm', and 'iife'. T ...

Utilizing the json_encode() function in PHP and JSON.parse() method in JavaScript for handling file data interchange

Utilizing json_encode() in PHP to store an array in a file, then leveraging JSON.parse() in JavaScript on the client side to read the json encoded file and pass it as an array to a sorting algorithm: The result of my json_encode() operation in the ...

Develop fresh JavaScript code using JavaScript

Is it possible to dynamically create a new row in an HTML table by clicking on a button? Each row contains multiple input fields. <script type="text/javascript> row = 2; specific_row_id = new Array(); $(document).ready(function() { $(".change_1 ...

Exploring the use of leaflets within LitElement

I have been working on a project involving LitElement components and I am looking to incorporate Leaflet into it. However, I am encountering difficulties with displaying the map properly. After installing Leaflet through npm in my project, I created a clas ...

Comparing Embedded and Linked JS/CSS

In my experience, I understand the advantages of using linked CSS over embedded and inline styles for better maintainability and modularity. However, I have come across information suggesting that in certain mobile web development applications, it may be m ...