Tips for retrieving the location of a draggable waypoint in the Google Directions output

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Location Partner</title>

  <!--styles for map elements-->
  <style type="text/css">
    html {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 15px;
      height: 100%;
    }
    
    body {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
    }
    /*start styles for the ContextMenu*/
    
    .context_menu {
      background-color: white;
      border: 1px solid gray;
    }
    
    .context_menu_item {
      padding: 3px 6px;
    }
    
    .context_menu_item:hover {
      background-color: #CCCCCC;
    }
    
    .context_menu_separator {
      background-color: gray;
      height: 1px;
      margin: 0;
      padding: 0;
    }
    /*end styles for the ContextMenu*/
    
    #map_container {
      height: 100%;
    }
  </style>


  <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=quarterly&key=#YOURAPIKEY#&sensor=false"></script>
  
  <script type="text/javascript">
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map_container'), {
        zoom: 4,
        center: {
          lat: -24.345,
          lng: 134.46
        } // Australia.
      });

      var directionsService = new google.maps.DirectionsService;
      var directionsDisplay = new google.maps.DirectionsRenderer({
        draggable: true,
        map: map,
        panel: document.getElementById('right-panel')
      });

      directionsDisplay.addListener('directions_changed', function() {
        computeTotalDistance(directionsDisplay.getDirections());
      });

      displayRoute('Perth, WA', 'Sydney, NSW', directionsService,
        directionsDisplay);
    }

   ...

</html>

Capturing the location of a draggable waypoint in Google Maps API to save it in the database and load the same directions later.

Efforts to access the waypoint's location via

result.routes[0].legs[0].via_waypoints[0]
show an empty response for lat and lng. Same goes for
result.routes[0].legs[0].via_waypoint[0].location
.

A suggestion in the code to use

result.routes[0].legs[0].via_waypoints[0].k
and
result.routes[0].legs[0].via_waypoints[0].D
did not yield results. Forum discussions propose using location.wa and location.ya, which also failed to provide geolocation data.

Remember to replace #YOURAPIKEY# with your Google API key in the code snippet for it to work. This example is based on Google's documentation.

Any assistance or insights on this issue would be greatly appreciated.

Answer №1

Every segment of your journey consists of a series of steps, and in the scenario you provided, each segment corresponds to directions between one of your stops (origin, waypoints, destination).

  • leg[0] from Perth to Adelaide
  • leg[1] from Adelaide to Broken Hill
  • leg[2] from Broken Hill to Sydney

Therefore, there will be no entries in the via_waypoints property.

If you wish for the waypoints not to be treated as actual stops, you must set stopover: false in your waypoints. This way, the via_waypoints property will be populated for each segment (if there is more than one).

waypoints: [{
  location: 'Adelaide, SA',
  stopover: false
}, {
  location: 'Broken Hill, NSW',
  stopover: false
}],

You can then loop through via_waypoints to retrieve the coordinates.

lat and lng are methods, not properties, so they need to be invoked like so:

let firstWaypointLat = result.routes[0].legs[0].via_waypoints[0].lat();

Below is an example of how to obtain the coordinates of the waypoints:

function initMap() {

  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 4,
    center: {
      lat: -24.345,
      lng: 134.46
    } // Australia.
  });

  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true,
    map: map,
    panel: document.getElementById('right-panel')
  });

  directionsDisplay.addListener('directions_changed', function() {
    computeTotalDistance(directionsDisplay.getDirections());
  });

  displayRoute('Perth, WA', 'Sydney, NSW', directionsService,
    directionsDisplay);
}

function displayRoute(origin, destination, service, display) {
  service.route({
    origin: origin,
    destination: destination,
    waypoints: [{
      location: 'Adelaide, SA',
      stopover: false
    }, {
      location: 'Broken Hill, NSW',
      stopover: false
    }],
    travelMode: 'DRIVING',
    avoidTolls: true
  }, function(response, status) {
    if (status === 'OK') {
      display.setDirections(response);
    } else {
      alert('Could not display directions due to: ' + status);
    }
  });
}

function computeTotalDistance(result) {

  let leg = result.routes[0].legs[0];
  for (let i=0; i<leg.via_waypoints.length; i++) {
  
    console.log('Waypoint ' + i + ' coords: ' + leg.via_waypoints[i].lat() + ', ' + leg.via_waypoints[i].lng());
  }
}

initMap();
#map-canvas {
  height: 180px;
}
<div id="map-canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</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

Create Vuetify components dynamically through programming

My goal is to dynamically create Vuetify components and insert them into the DOM. I've had success with simple components like v-card or v-dialogue, but I'm running into issues with v-data-tables. To demonstrate the problem, I set up a codesandb ...

Observing Node.js processes to track the peak memory usage of each process

Is there existing monitoring software that can track newly spawned node.js processes on my machine and display the maximum memory usage when the process ends? If not, how can this be achieved effectively? I have identified the specific Node.js processes I ...

Verify whether the value is considered false, true, or null

When dealing with variables in JavaScript, I often need to determine if a variable is false, true, or null. If the variable is null or undefined, I want to assign an array to it by default. While this syntax works well in other languages, in JS assigning a ...

The Xero Node OAuth Authorize Callback URL is malfunctioning after granting access

When utilizing the xero-node library to produce a Request Token using the getRequestToken function, the URL provided does not automatically redirect the user to the designated callback address specified in the configuration. Instead, a screen displaying a ...

Node.JS 3DES encryption encountering an issue with IV length validation

I'm new to working with Node.js and I've encountered an issue with the encryption object: var des3_key = new Buffer("redacted", "base64"); // obtained from another source var des3_iv = new Buffer("alsoredacted", "base64"); // obtained from anoth ...

Incorporate different courses tailored to the specific job role

https://i.stack.imgur.com/iGwxB.jpg I am interested in dynamically applying different classes to elements based on their position within a list. To elaborate: I have a list containing six elements, and the third element in this list is assigned the class ...

Error message: Issue with TypeScript and cleave.js - 'rawValue' property is not found on type 'EventTarget & HTMLInputElement'

I am encountering an error with the onChange event while implementing cleave in typescript. TypeScript is throwing an error indicating that 'rawValue' is not present in event.target. Here is my code: import React, { useCallback, useState, useEff ...

Prevent Buttons from Being Clicked While Another is Active in Angular

I am facing a challenge with my Angular functions that enable search features. My goal is to allow only one feature to be selected at a time. /* Trauma Search functionality */ $scope.traumaSearch = false; $scope.traumaText = "Trauma Center"; $scope.togg ...

Passing the contents of a datatable as parameters to a PHP script

I am facing a challenge with my datatable that has two columns, "Name" and "Age". After populating the datatable using Ajax, I create a button for each row. The goal is to send the "Name" and "Age" fields of the clicked row to a PHP script, which will then ...

Observing exceptional inquiries

Can I check what requests Protractor is waiting for? I'm working on fixing inconsistent state testing, but it's difficult to determine if a button didn't initiate a response or if Protractor simply didn't wait. In short: How do I see t ...

What is the best way to save inputted names as properties of an object and assign the corresponding input values as the values of those properties?

I am searching for a way to dynamically build an object where each property corresponds to the name of an input field and the value of that property is the input's value. Here is the HTML structure: <form> <fieldset> ...

Using the HTML select tag to choose an integer value with AngularJS

Looking to utilize AngularJS for the first time. One of the tasks at hand is selecting an integer value using the HTML <select> tag. <select ng-model="foo.bar"> <option ng-repeat="option in options" value="{{option}}">{{option}}</ ...

JavaScript encountered an error stating "phone is not defined" due to an uncaught ReferenceError

Whenever I click on the Phone Number, it displays an error message saying that the function is not defined. How can I fix this issue? Thank you in advance! Here's the code snippet: <div class="product-label"> <h4><?php echo $p["Fu ...

Retrieve the information from the recently completed request

When the user inputs 'id' into the text field, I want to fetch a post based on the specific id entered by the user. If no id is provided, I would like to fetch the entire array of posts and then retrieve an id from the fetched data for testing pu ...

Simplify nested JSON data

I'm struggling with a JSON object that looks like this: const people = { name: 'My Name', cities: [{city: 'London', country: 'UK'},{city: 'Mumbai', country: 'IN'},{city: 'New York', country: ...

Surprising outcome from the glob-fs glob.readdirSync function

Below is some nodejs code that I am working with. The client initially calls /api/demosounds and then calls /api/testsounds. var glob = require('glob-fs')({ gitignore: true }); app.get('/api/demosounds',function(req,res){ var d ...

Enhance the speed of AJAX search within a UL LI list containing over 5000 objects

Dear Stack community, I've been working on a simple Ajax js search using .addClass and .removeClass as I discovered it's faster than using .show() and .hide(). However, the speed is still not up to par and I'm feeling quite lost. You can ...

The complexity surrounding various versions of jQuery, the .noConflict method, and the jQuery migrate feature

I was tasked with making a large-scale website responsive, and decided to utilize Bootstrap as the framework. However, I encountered issues due to the jQuery version (v1.8.2) being used. In my development environment, I resolved this by including the follo ...

What could be causing my Vue component to not refresh?

Can anyone help me figure out why this component isn't re-rendering after changing the value? I'm attempting to create a dynamic filter similar to Amazon using only checkboxes. Here are the 4 components I have: App.vue, test-filter.vue, filtersIn ...

Select from a variety of backgrounds using the dropdown menu on the site

I seem to be struggling with javascript and php, but I know that in order to make this function properly, I need to utilize both languages. My goal is to set up a "select box" featuring 4 different images. There will be a default image displayed, but user ...