Search code examples
javascriptbing-mapsdriving-directions

Bing: directionsManger.getAllWaypoints() doesn't return latitude/longitude


I am using Bing map ajax control. In my code i have something as below -

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();
// Do 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); // waypoint values come from UI based on user input string address
directionsManager.addWaypoint(waypoint);
directionsManager.addWaypoint(end);

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

 var legs = directionsManager.getAllWaypoints();

 // do some validations
 //ajax call to backend
}

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

        }

getMap() is properly initialized, i can see the directions correctly being displayed. In the waypoints returned by directionsManager.getAllWaypoints(), none of the waypoint has location object inside it - as a result i am not getting lat/long. All i need is lat/long of each waypoint in savetrip() method, before calling the back-end code, which i do not see.

I am using a Developer key as of now. Let me know if i need to provide any more information.

Thanks in advance

Roshan


Solution

  • Use the getLocation method on the Waypoint object to get it's location coordinates: http://msdn.microsoft.com/en-us/library/hh312838.aspx

    Here is a working code sample:

    <!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>