Literal Route Waypoints Guidance Service

I am currently working on an angularjs directive that utilizes the Google Maps Direction Service. In my controller, I have a getFunction that watches for changes in a scope variable. Once the scope variable changes, it triggers the calculateAndDisplayRoute function to update the directions. I am attempting to implement the waypoints feature, but I keep encountering the same issue. The waypoints array should consist of objects with "location" and "stopover" fields. I have an array named wypoints containing google.maps.Place objects retrieved from geocoding, totaling 8 waypoints.

The problem I am facing is that the waypoints do not accept a LatLng field in the location section, which is puzzling to me.

Below is the code snippet for my calculateandDisplayRoute function:

function calculateAndDisplayRoute(directionsService, directionsDisplay, waypoints) {
                var waypts = [];
                for (var i = 0; i < waypoints.length; i++) {
                        waypts.push({
                            location: waypoints[i].geometry.location,
                            stopover: true
                        });
                    }

                directionsService.route({
                    origin: waypts[0].location,
                    destination: waypts[waypts.length - 1].location,
                    waypoints: waypts,
                    travelMode: google.maps.TravelMode.DRIVING
                }, function (response, status) {
                    if (status === google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);

                    } else {
                        window.alert('Directions request failed due to ' + status);
                    }
                });
            }

The error message I continuously encounter is Zero_results.

In addition to this issue, when I remove all waypoints, I notice that the directionService.route sometimes returns either Zero_result, provides start and end points at waypoint[0] and waypoint[8], or occasionally gives start and end points at waypoint[0] and another number within the range of 0-8. I suspect this may be due to the asynchronous nature of the call. However, I believe this should not affect the outcome since the waypoints are defined before the function execution.

Any assistance would be greatly appreciated!

Answer №1

Take a look at the updated fiddle that displays the route for the provided points - http://jsfiddle.net/af6f7su0/140/

If you're getting zero results, it could be because directions for the specified region are not available. According to the documentation:

"ZERO_RESULTS" indicates that the geocode was successful but returned no results. This may occur if the geocoder was passed a non-existent address

The provided fiddle seems to have duplicate placeIds, which can cause the Direction Service API to return zero results. I've made some adjustments in the updated fiddle to fix this issue. Additionally, I corrected the location geometry of the placeIds by using formatted_address instead of location.geometry. Make sure all points fall within a land area and note that only intermediate points should be included as waypoints, not all points. Here's the revised calculateAndDisplayRoute function:

function calculateAndDisplayRoute(directionsService, directionsDisplay, waypoints) {
     var waypts = [];
     var intermediatePoints = [];

     for (var i = 0; i < waypoints.length; i++) {
         waypts.push({
             location: waypoints[i].formatted_address,
             stopover: true
         });
     }

    intermediatePoints = waypts.slice(1, -1);

    directionsService.route({
        origin: waypts[0].location,
        destination: waypts[waypts.length - 1].location,
        waypoints: intermediatePoints,
        optimizeWaypoints: true,
        travelMode: google.maps.TravelMode.DRIVING
    }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
       directionsDisplay.setDirections(response);
    } else {
       window.alert('Directions request failed due to ' + status);
    }
    });
}

I hope these changes resolve the issue. Feel free to reach out if you need further assistance.

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

Auto Start Feature for jQuery Slider Function

Hey there, I currently have an image slider on my website that allows users to navigate through images by clicking on preview and next buttons. My query is: would it be possible to implement an auto start feature instead of having to click manually? Belo ...

What is the best way to submit a Redux Form only if there have been changes made to any of the fields

I'm currently using Redux Form version 7.1.2, and I have a form that submits data when the user clicks the submit button. In the function assigned to handle the submission, I perform an action. However, I only want this action to be executed if there ...

The Google Maps API is not providing any data in response to my jQuery JSONP request

Similar Topic: Unpacking Google Geo API (Reverse Geocoding) using jQuery $(window).load(function() { var purl = "http://maps.googleapis.com/maps/api/geocode/json?latlng=32.759294499999996,-97.32799089999999&sensor=false"; $.getJSON(purl,f ...

JavaScript code to copy a specified column through the last column, and then paste it down to the last row

I have limited experience with JavaScript and I've been putting together the code I need by searching online resources and watching videos. My goal is to set multiple columns in row 4, starting from column 18 to the last column, as the active cells fo ...

Leveraging Enjoyhint within nextJS

I am attempting to create a code tour using EnjoyHint, but encountered an error after installing the xbs-enjoyhint library. The error reads: Server Error - ReferenceError: CanvasRenderingContext2D is not defined. This issue is within the jquery.enjoyhint ...

Testing Jest with NodeJS involves simulating input from standard input (stdin)

I'm currently working on a command-line application that takes user input from standard input using the following code: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, }); rl.on('li ...

The functionality of scope.$observe is unavailable within an AngularJS Directive

Consider the snippet below: appDirectives.directive('drFadeHighlight', ['$animate', '$timeout', function ($animate, $timeout) { return { scope: { isWatchObject: '=' }, restric ...

Hiding Properties in NodeJS with MongoDB

My quest is to fetch a user object from my mongodb database : router.get('/', async (req, res) => { var user = await User.findOne({ _id: '5fe30ba2d8f18b353ce6c7c2' }).select('+password +token'); // it's ok, I can r ...

Fixing the error message stating 'Argument of type '{}' is not assignable to parameter of type 'any[]'. [ng] Property 'length' is missing in type '{}'. Here are steps to resolve this issue:

Currently, I am in the process of developing an Ionic Inventory Management application that incorporates a Barcode Scanner and SQLite database by following this tutorial: Upon adding the following code snippet: async createTables(){ try { awa ...

The process of generating vue-cli-plugin-prerender-spa encountered an issue where the error was not found within the

I have successfully integrated this plugin into my laravel-vue application and configured it within the laravel mix's webpack.mix.js file. After running it via npm (using watch, dev, and prod modes), I encountered no errors. However, upon inspecting ...

What is the reason behind the Placeholder not functioning in IE8?

Whenever I trigger the onblur event on an input of type "password", it will hide both the placeholder text and the input itself. Check out the GitHub link for this plugin ...

Simulation of loopback session

Currently, I am utilizing loopback in conjunction with express session to store cartId. However, for the purpose of making my tests function properly, it is essential that I inject cartId into the request session. Within my remote method, I have implemen ...

Compiling Typescript with module imports

In my project, I am working with two files named a.ts and b.ts. The interesting part is that file b exports something for file a to use. While the TypeScript compiler handles this setup perfectly, it fails to generate valid output for a browser environment ...

Contrasting gatsby-theme-material-ui and gatsby-plugin-material-ui

I'm in the process of creating a website using Gatsby, and I'd like to incorporate Material UI, but I'm unsure about which plugin I should use. Here are my questions: What is the difference between these two options, and how can I integra ...

Upon running the command "React + $ npm start," an error occurred with the code 'ERR_OSSL_EVP_UNSUPPORTED' related to opensslErrorStack

When running $npm start, an error is being thrown: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'digital envelope routines', reason: 'unsupported', code: 'ERR_OSSL_EVP_ ...

Displaying elements above my React sidebar

I am working on developing a Login application with a landing page using React Router and Redux. In order to have a Sidebar that is always present in all the components within the application, I have setup the Sidebar component as a route that is constantl ...

What is the best way to navigate to a specific location on a web page?

After clicking the "Add comment" link, a comment form popped up using Ajax. I now need assistance with scrolling to it, can you please help me out? ...

Dealing with dynamic CORS settings in Apache and PHP

Dealing with CORS has been quite a challenge for me. My javascript is sending AJAX Put/Fetch requests to an Apache/PHP script. In this particular scenario, the javascript is being executed on CodePen while the Apache/PHP script is hosted on a local serve ...

Bootstrap: Display a single product on the Carousel Product Slider for the smallest view

I found an example I'm using at this link: I noticed that when I resize my BrowserWindow, the boxes start to shrink. However, when the width reaches about 990px, the single products are rearranged in a 4-block layout from the initial width. Is there ...

Determine the Number of Table Columns Using jQuery

I'm curious, with jQuery how can one determine the number of columns in a table? <script> alert($('table').columnCount()); </script> <table> <tr> <td>spans one column</td> <td ...