0

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

计算距离路由.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());
      }
}

里程.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(). 其他一切都失败了。

4

1 回答 1

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)");             
  }
}
于 2009-10-18T23:01:31.110 回答