Google Maps API:GDirections对象文字的问题

时间:2009-10-18 20:13:48

标签: javascript xhtml google-maps gdirections

我成功调用GDirections来获取一张地图,其中包含我指定的A点和B点之间的路线。但是,我似乎无法获得某些返回值。

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:

<!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电话是route.load()。其他一切都失败了。

1 个答案:

答案 0 :(得分:1)

您需要订阅路由的load事件,因为路由的加载是异步发生的。这是带有load事件的新初始化函数:

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)");             
  }
}