如何从谷歌路线结果中获取可拖动的航点的位置

时间:2019-02-18 14:11:14

标签: javascript google-maps-api-3

<!DOCTYPE html>
<html>

<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Lokacija Partnerja</title>

  <!--stili za elemente na mapi-->
  <style type="text/css">
    html {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 15px;
      height: 100%;
    }
    
    body {
      height: 100%;
      width: 100%;
      margin: 0;
      padding: 0;
    }
    /*	start styles for the ContextMenu	*/
    
    .context_menu {
      background-color: white;
      border: 1px solid gray;
    }
    
    .context_menu_item {
      padding: 3px 6px;
    }
    
    .context_menu_item:hover {
      background-color: #CCCCCC;
    }
    
    .context_menu_separator {
      background-color: gray;
      height: 1px;
      margin: 0;
      padding: 0;
    }
    /*	end styles for the ContextMenu	*/
    
    #map_container {
      height: 100%;
    }
  </style>


  <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=quarterly&key=#YOURAPIKEY#&sensor=false"></script>
  
  <script type="text/javascript">
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map_container'), {
        zoom: 4,
        center: {
          lat: -24.345,
          lng: 134.46
        } // Australia.
      });

      var directionsService = new google.maps.DirectionsService;
      var directionsDisplay = new google.maps.DirectionsRenderer({
        draggable: true,
        map: map,
        panel: document.getElementById('right-panel')
      });

      directionsDisplay.addListener('directions_changed', function() {
        computeTotalDistance(directionsDisplay.getDirections());
      });

      displayRoute('Perth, WA', 'Sydney, NSW', directionsService,
        directionsDisplay);
    }

    function displayRoute(origin, destination, service, display) {
      service.route({
        origin: origin,
        destination: destination,
        waypoints: [{
          location: 'Adelaide, SA'
        }, {
          location: 'Broken Hill, NSW'
        }],
        travelMode: 'DRIVING',
        avoidTolls: true
      }, function(response, status) {
        if (status === 'OK') {
          display.setDirections(response);
        } else {
          alert('Could not display directions due to: ' + status);
        }
      });
    }

    function computeTotalDistance(result) {
      var total = 0;
      var route = result.routes[0];
      for (var ij = 0; ij < route.legs[0].via_waypoints.length; ij++) {
        counter = counter + 1;
        //alert(counter + ", " + route.legs[i].via_waypoints[ij].B + ", " + route.legs[i].via_waypoints[ij].k)

        route.legs[0].via_waypoints[ij].k,
          route.legs[0].via_waypoints[ij].D
      }
    }
  </script>

</head>

<body onload="initMap()">
  <div id="map_container"></div>
</body>

</html>

我正在尝试在Google方向javascript API中捕获可拖动航点的位置,因此我可以将其保存在数据库中,并在以后加载相同的方向。

我尝试通过result.routes[0].legs[0].via_waypoints[0]访问航路点的位置,这向我提供nothing useful-latlng对象是“空”的,而不是包含地理位置(同样如此) result.routes[0].legs[0].via_waypoint[0].location

我在代码中有一条评论,指出无法通过result.routes[0].legs[0].via_waypoints[0].kresult.routes[0].legs[0].via_waypoints[0].D访问航点的地理位置。我从2011年开始发现stackoverflow a similar question,建议使用location.walocation.ya,但它们也不起作用。

我已经添加了一个代码段,您应该将#YOURAPIKEY#替换为您的Google API密钥,该示例才能正常工作。这是对Google's documentation

的稍作修改的示例

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

路线的每条腿都是一组步骤,在您提交的情况下,每条腿都对应一个停靠点(起点,航路点,目的地)之间的方向。

  • leg[0]从珀斯到阿德莱德
  • leg[1]从阿德莱德到布罗肯希尔
  • leg[2]从布罗肯希尔到悉尼

因此via_waypoints道具中什么也没有。

如果您不希望将其视为真正的停留站,则需要在航路点设置stopover: false。然后,您将获得每条腿(如果有多条腿)的via_waypoints属性填充。

waypoints: [{
  location: 'Adelaide, SA',
  stopover: false
}, {
  location: 'Broken Hill, NSW',
  stopover: false
}],

然后您可以遍历via_waypoints并获取坐标。

latlng是方法,而不是属性,因此您需要调用它们,例如:

let firstWaypointLat = result.routes[0].legs[0].via_waypoints[0].lat();

以下示例如何获取航点坐标:

function initMap() {

  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 4,
    center: {
      lat: -24.345,
      lng: 134.46
    } // Australia.
  });

  var directionsService = new google.maps.DirectionsService;
  var directionsDisplay = new google.maps.DirectionsRenderer({
    draggable: true,
    map: map,
    panel: document.getElementById('right-panel')
  });

  directionsDisplay.addListener('directions_changed', function() {
    computeTotalDistance(directionsDisplay.getDirections());
  });

  displayRoute('Perth, WA', 'Sydney, NSW', directionsService,
    directionsDisplay);
}

function displayRoute(origin, destination, service, display) {
  service.route({
    origin: origin,
    destination: destination,
    waypoints: [{
      location: 'Adelaide, SA',
      stopover: false
    }, {
      location: 'Broken Hill, NSW',
      stopover: false
    }],
    travelMode: 'DRIVING',
    avoidTolls: true
  }, function(response, status) {
    if (status === 'OK') {
      display.setDirections(response);
    } else {
      alert('Could not display directions due to: ' + status);
    }
  });
}

function computeTotalDistance(result) {

  let leg = result.routes[0].legs[0];
  for (let i=0; i<leg.via_waypoints.length; i++) {
  
    console.log('Waypoint ' + i + ' coords: ' + leg.via_waypoints[i].lat() + ', ' + leg.via_waypoints[i].lng());
  }
}

initMap();
#map-canvas {
  height: 180px;
}
<div id="map-canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="//maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>