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

Enclose every line of the paragraph within a <span> element

My <div> element is configured to display a paragraph without any line breaks, similar to the example below: <div> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dum ...

Encountering a Selection Issue with IE8

I am encountering an issue with my script that involves a form with two select elements for region and state, allowing users to filter states based on the selected region. Everything works smoothly except for one problem - when testing in IE8, I receive th ...

Node.js has no trouble loading HTML files, however, it seems to encounter issues when trying to

Having a bit of trouble with my JavaScript skills as I try to load my index.html file (seems like it should be the 5th easiest thing to do in JavaScript). Let me get straight to the point; when I manually open my index.html, it loads perfectly WITH the CS ...

Enhanced form validation using AJAX

Currently, my aim is to implement client-side validation with AJAX in order to check for any empty fields within a basic form. If a field happens to be blank, I intend to alert the user about its invalidity. It is crucial that the form does not get submitt ...

Techniques for dynamically counting rows in a table using JavaScript

I'm working on a system to create and delete rows, and I want each row to have a unique row number displayed under "Num." However, I'm having trouble implementing this feature. EDIT I found a jQuery snippet that counts the first row but not t ...

Passing a variable as a property to a nested child component in Vue.js

I am curious about how to efficiently pass variables to nested components. Within my setup, I have a total of 3 components: Main Secondary Tertiary All of these components share a common variable (referred to as sharedVar). If I want to avoid using Vue ...

How can we implement the MUI snackbar to only show when a successful login occurs in ReactJS?

How can I display the material-ui snackbar in ReactJS only upon successful login? What approaches can be used to achieve this in ReactJS? ...

Can a file be successfully retrieved using an HTTP POST request?

Can a file be downloaded using HTTP POST method? I am aware of the "Get" method (windows.location), but in my scenario, there are many parameters that need to be sent to the server. ...

utilize text offsets to insert tags within strings

I've been facing challenges with using JavaScript string methods and regular expressions. It seems like I might be missing something obvious here. Please forgive me if I'm repeating the question asked by tofutim in more detail, which can be found ...

What are the steps to resolving an issue in a Jest unit test?

In my ReactJs/Typescript project, I encountered an issue while running a unit test that involves a reference to a module called nock.js and using jest. Initially, the import statement was causing an error in the .cleanAll statement: import nock from &apos ...

Exploring the isolate scope within a compiled directive

I successfully managed to compile a directive using this piece of code: let element, $injector, $compile, link, scope; element = angular.element(document.getElementById(#whatever)); $injector = element.injector(); $compile = $injector.get('$compile& ...

Retrieving JSON data from outside the React root directory

My current project includes an older javascript/php application with numerous JSON files used to retrieve data from the database. As I plan to migrate some modules to React, I am wondering if it's possible to still fetch data from these JSON files wi ...

One limitation is that you cannot use JQuery to make multiple rows editable simultaneously

I have a unique challenge with implementing an edit button on each row of a dynamic Bootstrap table. I am attempting to toggle the button's icons and, depending on its current state, enable the corresponding row for editing. <td><button typ ...

What is the best way to alter the header in Django when a user is authenticated?

In my project, I have two headers: header.html and headersuccess.html. When a user is logged in, I need to change the header from header.html to headersuccess.html. How can I implement that? Here is an excerpt from my views.py file where I render loginsuc ...

Build an object using a deeply nested JSON structure

I am working with a JSON object received from my server in Angular and I want to create a custom object based on this data. { "showsHall": [ { "movies": [ "5b428ceb9d5b8e4228d14225", "5b428d229d5b8e4 ...

Provide the aggregated content within d3's text() or html() function

Below is my d3 code snippet: grouping.append('foreignObject').html(function (d) { var string = '<p>hello, {{ "there" }} <some-directive></some-directive></p>'; string = $compile(string)(scope); return stri ...

Only output to the console if the data returned from an AJAX request has been

Here is a script that I created: <script type="text/javascript> $('.storage').html(""); setInterval(function(){ $.get('./playcommand.php', function(data) { if($('.storage').html() !== data){ ...

JavaScript ACTING UP -> CROSS-ORIGIN RESOURCE ACCESS ERROR

After extensive research and troubleshooting, it dawned on me that the issue was not with JavaScript itself. Instead, I was facing a cross origin resource exception, which occurred because the ajax request was unable to access my server script due to lac ...

Discovering the method to retrieve a previous month's date within a VueJs application using Javascript

Can someone guide me on how to retrieve the date of the past month using Vue? This is the code I currently have: import SomeTable from "./table/SomeTable"; export default { name: "Cabinets", components: {SomeTable}, data() { return { ...

Is it necessary to mark all checkboxes in the initial column of the gridview?

I have encountered an issue with my code that checks all checkboxes in the first column of a gridview. It seems to work only for Internet Explorer versions 5.0 to 8.0, but gives a Javascript error when running on IE 9 and above stating "Function Expected ...