【问题标题】:dynamic route with Google directions API使用 Google 路线 API 的动态路线
【发布时间】:2014-04-30 02:28:52
【问题描述】:

最初我在地图上有两个点。其中一个是起点,另一个是目的地。

原点是可拖动的,而目的地是固定的。

在页面加载后第一次绘制地图时,我有一些原点的默认值,而目标点从数据库中获取值。初始加载工作正常。我能够在起点和终点之间绘制路线。

我使用以下函数在地图上绘制方向

function calcRoute() {
  var request = {
      origin:myLatLng1,
      destination:myLatLng,
      optimizeWaypoints: true,
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

现在我有一个事件监听器,每当拖动我的原点标记时,它会获取原点标记新位置的新纬度,然后我调用上面的相同函数来获取新路线。

function togglePos(){
    myLatLng1 = new google.maps.LatLng(marker1.getPosition());
    calcRoute();
}

这是我面临的问题,我无法在新标记的起点和同一个旧目的地之间重绘新路线。 如果 any1 需要,这是我的初始化函数。

function initialize() {
    var mapOptions = {
        zoom: 13,
        center: myLatLng
    };
    map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);

    directionsDisplay.setMap(map);

    var image = 'myimage.png';

    marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          icon: image,
    });
    marker1 = new google.maps.Marker({
          position: myLatLng1,
          map: map,
          draggable: true
    });
    google.maps.event.addListener(marker1, 'dragend', togglePos);

    calcRoute();
}

我没有收到任何 javascript 错误。 我正在构建这样的东西。
https://developers.google.com/maps/documentation/javascript/examples/directions-simple

但我不是从下拉框中选择它,而是在移动标记时调用该函数。

小提琴链接:http://jsfiddle.net/FvqAL/4/ 但我不知道为什么它不能在小提琴上工作:|

【问题讨论】:

  • 你能提供一个展示问题的小提琴吗?还是指向该页面的链接?
  • 已添加,请查看。
  • 修复了fiddle,不确定我是否理解这个问题。当目的地在偏僻的地方时,路线服务返回 ZERO_RESULTS 并且不显示路线。
  • 我已经更新了fiddle,现在它确实显示了结果,但是在移动标记后,它显示了 zero_results 错误。
  • 如果我不在 renderOptions1 中使用 suppressMarkers,我会得到两个标记,我希望其中一个是固定的,另一个是可移动的。 renderOptions1 中的可拖动属性允许您使两者都可拖动,但没有允许您仅修复一个的属性。所以我使用了抑制标记,并放置了我自己的标记(其中一个是可拖动的)。我想让其中一个可拖动,当它被拖动时,新路线被计算出来并显示在地图上。

标签: javascript google-maps google-maps-api-3 map directions


【解决方案1】:

我对 calc route 进行了一些更改,现在无论何时调用它,它都会获取 marker1 的位置并通过它绘制路线。

function calcRoute() {
  var request = {
      origin:marker1.getPosition(),
      destination:myLatLng,
      optimizeWaypoints: true,
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

这里是最终的fiddle,如果您想查看的话。 感谢您的帮助:)

【讨论】:

    猜你喜欢
    • 2012-12-05
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多