JavaScript如何计算lat longs的2个位置之间的路线图距离

时间:2016-07-08 06:05:16

标签: javascript angularjs google-maps

我在使用JavaScript计算lat longs的2个位置之间的RoadMap距离时遇到了麻烦。

找到答案:

有了这个链接:

var service = new google.maps.DistanceMatrixService;
service.getDistanceMatrix({
    origins: [origin1],
destinations: [destinationA],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus.OK) {
        alert('Error was: ' + status);
  return;
    }

https://jsfiddle.net/c6omLvso/

2 个答案:

答案 0 :(得分:1)

您使用的是谷歌地图javascript api吗?如果是这样,你可以尝试"Distance Matrix Service"

答案 1 :(得分:1)

您可以使用谷歌距离矩阵实现目标,如下所示:

google.maps.event.addDomListener(window, "load", function () {
    var map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(55.53, 9.4),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  
    var origin1 = {lat: 55.93, lng: -3.118};
    var origin2 = 'Greenwich, England';
    var destinationA = 'Stockholm, Sweden';
    var destinationB = {lat: 50.087, lng: 14.421};
  
    var service = new google.maps.DistanceMatrixService;
    service.getDistanceMatrix({
        origins: [origin1, origin2],
        destinations: [destinationA, destinationB],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, function(response, status) {
        if (status !== google.maps.DistanceMatrixStatus.OK) {
            alert('Error was: ' + status);
            return;
        }

        var originList = response.originAddresses;
  	var destinationList = response.destinationAddresses;
        var output = document.getElementById("output");
        output.innerHTML = "";
    
    for (var i = 0; i < originList.length; i++) {
      var results = response.rows[i].elements;
      for (var j = 0; j < results.length; j++) {
        output.innerHTML += originList[i] + ' to ' + destinationList[j] +
          ': ' + results[j].distance.text + ' in ' +
          results[j].duration.text + '<br>';
      }
    }    
  });
});
body {
  margin: 0;
  padding: 0;
  font: 12px sans-serif;
}

#map {
  width: 400px;
  height: 400px;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map"></div>
<div id="output"></div>

enter code here