2009-10-18 83 views
0

我打電話成功向GDirections得到的地圖與A點和B點,我已指定之間的路線。但是,我似乎無法獲得某些返回值。谷歌地圖API:麻煩與GDirections對象文字

calculateDistanceFromRoute.js:

var map = new GMap2(document.getElementById("map_canvas")); 

function initialize() { 
     if (GBrowserIsCompatible()) { 
     var map = new GMap2(document.getElementById("map_canvas")); 
     map.setUIToDefault(); 

     var route = new GDirections(map); 
     route.load("from: 500 Memorial Drive, Cambridge, MA to: 4 Yawkey Way, Boston, MA 02215 (Fenway Park)"); 
     var distance = route.getDistance(); 
     $("#dist").text(distance['html']); 
     $("#moar").text(route.getStatus().code); 
     $("#moar").append(route.getSummaryHtml()); 
     } 
} 

mileage.htm:

的作品是 route.load()
<!DOCTYPE html "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/> 
    <title>Google Maps JavaScript API Example</title> 
    <script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script> 
    <script src="calculateDistanceFromRoute.js" type="text/javascript"></script> 
    <script 
    src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAcockAALI9IMRhHpfZzqs20rOLzZhRabMQb63ObuLzgNixJdxkMB1n4URRmY9m2gxwNKKyf2Dx5JWJ5dwyADQ" 
    type="text/javascript"></script> 

    </head> 
    <body onload="initialize()" onunload="GUnload()"> 
    <div id="map_canvas" style="width: 500px; height: 300px"></div> 
    <p>The distance is <span id="dist">unknown</span></p> 
    <p id="stuff">here is some stuff</p> 
    <p id="moar"></p> 
    </body> 
</html> 

唯一route電話。一切都失敗了。

回答

1

您需要訂閱路由的加載事件,因爲路由的加載是異步發生的。這裏是帶有負載事件的新的初始化函數:

function initialize() { 
    if (GBrowserIsCompatible()) { 
    var map = new GMap2(document.getElementById("map_canvas")); 
    map.setUIToDefault(); 

    var route = new GDirections(map); 
    GEvent.addListener(route, "load", function() { 
     var distance = route.getDistance(); 
     $("#dist").text(distance['html']); 
     $("#moar").text(route.getStatus().code); 
     $("#moar").append(route.getSummaryHtml()); 
    }); 
    route.load("from: 500 Memorial Drive, Cambridge, MA to: 4 Yawkey Way, Boston, MA 02215 (Fenway Park)");    
    } 
} 
+0

這是正確的。謝謝。 – 2009-10-18 23:30:39