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

Is there a way to dynamically replace a section of a link with the current URL using JavaScript or jQuery?

I have a link that appears on multiple pages, and I want to dynamically change part of the link based on the current URL* of the page being visited. (*current URL refers to the web address shown in the browser's address bar) How can I use JavaScript ...

Harvesting the local image file

Currently, I have implemented a form that allows users to upload images and crop them. The process flow has been established as follows: 1. User uploads the image 2. Server processes the image and sends it back to the browser 3. User crops the image a ...

Trouble with ES6 Arrow Functions, Syntax Error

I am encountering an issue with my JS class structure: class Tree { constructor(rootNode) { this._rootNode = rootNode; rootNode.makeRoot(); } getRoot() { return this._rootNode; } findNodeWithID(id) ...

After clicking multiple times within the modal, the modal popup begins to shift towards the left side

I successfully implemented a modal popup in my project, but encountered an issue where the popup moves to the left side if clicked multiple times. Despite searching extensively online, I have not been able to find a solution to this problem. Below is the ...

Save information for each session with a set expiration time

Currently, I am working on a mobile application using Angular (specifically Ionic 5) and I am in need of a solution to maintain session data for my users throughout their workflow. Initially, I thought about utilizing the sessionStorage feature for this p ...

An easy way to activate the save button automatically

Is there a way to automatically enable the save button when a user checks the checkbox and enters text in the input field? I'm not sure what steps are needed or if there is an alternative approach to achieve this. jQuery("input[type='text&apos ...

Gaining entry to specialized assistance through an occasion

Having trouble accessing a custom service from a custom event. Every time the event is fired, the service reference turns out to be null. @Component({ selector: "my-component", template: mySource, legacy: { transclude: true } }) export class myComponent { ...

Unable to import local npm package due to an error

We are in the process of migrating multiple websites, each with its own project, to Vue.js. As we transfer files over and bundle them using Webpack, we have encountered a need to consolidate similar components and core JavaScript files into a shared librar ...

Emphasizes the P tag by incorporating forward and backward navigation options

My goal is to enable users to navigate up and down a list by pressing the up and down arrow keys. For example, if "roma" is currently highlighted, I want it to change to "milan" when the user presses the down arrow key. Here is the HTML code I am working w ...

Issue with JavaScript Date.parse function not functioning as expected

I have implemented a date validation method in my application to check if a given date is valid or not. myApp.isValidDate = function(date) { var timestamp; timestamp = Date.parse(date); if (isNaN(timestamp) === false) { return true; } return ...

Every time I employ window.location, the Iframe becomes nested

I am experiencing an issue with my HTML structure: <html> <body> This is the container of the iframe <iframe src="/foo.html"> </iframe> </body> </html> (/foo.html) <html> <script type="text/javascript"> $( ...

What is the process for executing mocha tests within a web browser?

Am I the only one who thinks that their documentation lacks proper instructions on running tests in the browser? Do I really need to create the HTML file they mention in the example? How can I ensure that it runs the specific test cases for my project? I ...

Can Cell be rendered into a targeted element?

Can a Cell from CellJS be rendered into a specific HTML element? For example, including a Cell alongside some static HTML that is not managed by cell. Or having two separate Cell apps on a single page. <!DOCTYPE html> <html> <header> ...

What is the process for incorporating custom controls into the Mantine Embla Carousel within a Next.js environment?

Check out this code snippet: import React from "react"; import { Container } from "@mantine/core"; import { Carousel } from "@mantine/carousel"; import { ArticleCard } from "@/components"; import { cards } from " ...

A guide on extracting keywords from the tynt API using JavaScript

Looking to extract the inbound keyword from an API: What would be the best way to use JavaScript to extract and display the value of the inbound keyword from this API? ...

What is the best way to apply multiple array filters to an object list in react.js?

Looking to filter an array of items using multiple filter arrays in order to display only the items that match all selected filters. For example: The main array contains a table with the following data: ID TypeID LocationID Name 1 2 ...

Can one button be clicked to trigger the activation of another button through a click?

Just as the title suggests, I am wondering how to make this happen? Any guidance would be greatly appreciated! $('.notVisible').click (function(){ alert("I'm the invisible button") }); $('.visible').click (function(){ al ...

Does Koa.js have a nested router similar to Express?

Are there any libraries available that offer Express-style nested routers? For example: var koa = require('koa'); var app = koa(); var Router = require('???'); var restApiRouter = Router(); restApiRouter.get('/', function*() ...

Setting up Quill in a Nuxt project (a VUE component)

I'm struggling to remove the toolbar in Quill despite my efforts. This is the HTML snippet I am working with: <template> <quill v-model="content" :config="config"></quill> </template Here's what I have inside the scri ...

Is JavaScript's setTimeout 0 feature delaying the rendering of the page?

Based on information from this StackOverflow post The process of changing the DOM occurs synchronously, while rendering the DOM actually takes place after the JavaScript stack has cleared. Furthermore, according to this document from Google, a screen r ...