Bing Maps API: The function directionsManager.getAllWaypoints() does not provide latitude and longitude information

I am currently utilizing the Bing map AJAX control in my code, which looks something like this -

function getMap()
      {
 map = new Microsoft.Maps.Map(document.getElementById('mnMap'), {
 credentials: 'MyKey', 
 mapTypeId: Microsoft.Maps.MapTypeId.road
          });
          map.setView({
 zoom: 4, 
 center: new Microsoft.Maps.Location(defaultLat, defaultLan)
          });
          Microsoft.Maps.loadModule('Microsoft.Maps.Directions', {
callback: createDirectionsManager
          });

      }

      function createDirectionsManager()
      {
          if (!directionsManager) 
          {
              directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
          }
          directionsManager.resetDirections();
          directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsPanel') });
          directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', displayRouteError );
          directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', displayUpdatedRoute );
      }

      function displayUpdatedRoute(status){
// Update waypoint text inputs based on dragged markers
          var legs = directionsManager.getAllWaypoints();
// Perform some validation
      }

 function displayRouteError(error){

         // If the error is a viapoint error, display an error
         if (error.responseCode == Microsoft.Maps.Directions.RouteResponseCode.noSolution){
 directionsManager.resetDirections();
         }else if (error.responseCode == Microsoft.Maps.Directions.RouteResponseCode.dataSourceNotFound || error.responseCode == Microsoft.Maps.Directions.RouteResponseCode.tooFar){
directionsManager.resetDirections();
         }else{
directionsManager.resetDirections();
         }
      }
function getDirections(submit, send) {

directionsManager.resetDirections();
if (some test condition) {
          start = new Microsoft.Maps.Directions.Waypoint({ location: new Microsoft.Maps.Location(locInputs.first().attr("data-lat"), locInputs.first().attr("data-lng")) });
        } else {
          start = new Microsoft.Maps.Directions.Waypoint({ address: locInputs.first().val() });
        }
directionsManager.addWaypoint(start); 
directionsManager.addWaypoint(waypoint);
directionsManager.addWaypoint(end);

directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsPanel') });
        directionsManager.calculateDirections();
}
function saveTrip(){

 var legs = directionsManager.getAllWaypoints();

 // Perform some validations
 // Ajax call to backend
}

$("#saveTripBtn").click(function() {
getDirections();
                saveTrip();

        }

Upon initialization of getMap(), I observe that the directions are correctly displayed. However, when I retrieve the waypoints using directionsManager.getAllWaypoints(), none of them contain a location object, resulting in a lack of latitude/longitude information. In the savetrip() method, I require the lat/long of each waypoint before calling the backend code, but unfortunately it is not present.

Currently, I am using a Developer key. Please let me know if any additional information is required.

Thank you in advance

Roshan

Answer №1

Utilize the getLocation method within the Waypoint object to retrieve its location coordinates: http://msdn.microsoft.com/en-us/library/hh312838.aspx

Check out this functioning code example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <head>
      <title></title>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
      <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>

      <script type="text/javascript">
        var map, directionsManager;

        function GetMap() { 
           map = new Microsoft.Maps.Map(document.getElementById('myMap'), { 
               credentials: 'YOUR_BING_MAPS_KEY'
           }); 

           Microsoft.Maps.loadModule('Microsoft.Maps.Directions', {
            callback: getDirections
           });
       }

       function getDirections() {
            if (!directionsManager) 
            {
               directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
            }

            directionsManager.resetDirections();

            var start = new Microsoft.Maps.Directions.Waypoint({ address: "Seattle, WA" });
            var end = new Microsoft.Maps.Directions.Waypoint({ address: "Portland, OR" });

            directionsManager.addWaypoint(start); 
            directionsManager.addWaypoint(end);
            directionsManager.calculateDirections(); 
        }

        function getWaypoints(){
            var wp = directionsManager.getAllWaypoints();

            var text = '';

            for(var i=0;i<wp.length;i++){
                var loc = wp[i].getLocation();
                text += 'waypoint ' + i + ': ' + loc.latitude + ', ' + loc.longitude + '\r\n';
            }

            document.getElementById('output').innerText = text;
        }
      </script>
   </head>
   <body onload="GetMap();">
    <div id='myMap' style=";width:600px;height:400px;"></div><br/>
    <input type="button" onclick="getWaypoints()" value="Get Waypoints" /><br/>
    <div id="output"></div>
   </body>
</html>

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

Utilize the lodash times method for indexing

I have a requirement to duplicate a component "n" number of times. I achieved this by utilizing the lodash method called "times". However, I encountered an issue with assigning an index as a key for the generated components. Below is the snippet of code t ...

Delivering a Logo to a Remote Website Based on Specific Conditions

I am in the process of creating a code snippet for a specific user group that has earned the privilege to display our seal on their website. The concept initially appeared straightforward, but when I attempted to implement it on a different site for testin ...

Does Three.js lighting adjust according to the bundler used?

Today, I decided to streamline my portfolio project by transitioning it from standard HTML to the Vite bundler for easier dependency management. I simply copied and pasted the existing code, making adjustments to the imports since I had been using relative ...

Angular 2 System.config map leading to a 404 error message

I am encountering a 404 error in the browser console while attempting to map the Auth0 module from node_modules in my Angular 2 project using the system.config in the index file. Index File <!-- 2. Configure SystemJS --> <script> System.con ...

An issue of "SignatureDoesNotMatch" arises while trying to send an email using Node AWS SDK for the Simple Email Service

I am facing an issue while attempting to send an email using the @aws-sdk/client-ses SDK in Node. The error I encounter is: SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access ...

Error message: "The getJSON call is missing a semicolon before the statement."

Can someone please explain the following. I've been searching online for a long time trying to find assistance and I think I am following all the correct steps but still receiving errors. Here is the script in question on my webpage: function GetPag ...

The issue of jQuery's .last() function triggering multiple times with just a single click on the last

I currently have a set of tabs containing radio buttons and I need to trigger an event when the last option is selected (meaning any radio button within the final tab, not just the last radio button). Below is the HTML code: <div id="smartwizard" clas ...

What is an alternative way to use mobx-react 'observer' that does not involve the decorator syntax?

I've been working on integrating `mobx` into a virtual reality application built with React 360. Initially, I attempted to use the decorator syntax without success, so I decided to switch to the non-decorator syntax. While going through the mobx docum ...

submission of form data and automatic redirection to another page

Seeking advice on managing form submissions and page redirection. I have a landing page with a basic form, where users select criteria and are then redirected to page2 displaying tabular data and query information. When submitting the form on Page1, data ...

If function is called after x seconds

Here is a JavaScript code snippet that triggers different functions based on the number of clicks. For instance, clicking once triggers function1, while clicking twice triggers function2. Now, how can I modify this code so that if I am in the stop_autosli ...

Utilizing Vue JS for applying multiple filters on a single array

I'm currently facing challenges in optimizing my code. I've successfully created dynamically generated objects from an array, implemented a search function, and had a working filter (just one) at some point. However, my attempt to chain the filte ...

Creating an array of JSX elements or HTMLElements in a React TypeScript rendering

Currently in the process of developing a custom bootstrap card wrapper that allows for dynamic rendering of elements on the front and back of the card based on requirements. Here is the initial implementation: import React, { useState, ReactElement } from ...

Converting JSON to Array: A Step-by-Step Guide

Greetings, StackOverflow community! This is my inaugural question here. I believe the answer is not overly complex, but my knowledge of Javascript is quite rudimentary. Currently, I have a JQuery AJAX function that processes this JSON object: { "Users" ...

Is there a way to utilize two onChange functions within one component?

I'm having trouble utilizing two onChange functions within the same component. I attempted to combine them, but I ran into an issue because one is using useState and the other is a const function. Below is my code snippet: const signup = () => { ...

Is there a way to make my modal appear only when the "New" option is clicked?

Is there a way to make my modal in VueJS open only when I click on the "New" option? <select v-model="input.des" @change="$refs.modalName.openModal()"> <option value="A">A</opt ...

Tips for updating the data value of a specific block using Vue.js

I am looking to develop a basic Vue.js application. Within this app, I have multiple counter blocks that are rendered using the v-for directive. In my data object, I initialize a 'counter: 0' instance. My goal is to increment and decrement only o ...

Results don't align with search parameters

const searchClientes = (event) => { if (event.target.value === '') { getClientes(); return; } else { const searchTerm = event.target.value; const filteredClients = clientes.filter(cliente => { return cliente.nome ...

Using jQuery to input a value that returns the [object Object]

While working with jQuery in asp.net, I encountered an issue where the value assigned to a hidden field (hfstockcode) is returning [object Object]. The console output shows v.fn.v.init[1]. How can I retrieve the correct value for the hidden field? $(docum ...

Is there a way to remove any incomplete information from the output (window.alert) in JavaScript when a user does not fill in all the prompts?

I am seeking input for 8 pieces of information to be displayed in an alert box, only if the user enters something in each field. All the gathered data will be shown in a single alert box once the user confirms their desire to review it. If the user choos ...

Personalize the Facebook like button to suit your preferences

I have posted my code on jsfiddle. You can find the link here: http://jsfiddle.net/QWAYE/1/. I have also included another sample code in this link: http://jsfiddle.net/MCb5K/. The first link is functioning correctly for me, but I want to achieve the same a ...