折线的距离

时间:2012-12-26 10:39:43

标签: google-maps-api-3 google-polyline

我在折线工作,我需要获得这个距离。所以,如果有人能提供帮助,我将非常感激。

最好的问候。

这是我的代码:

function polyline() {
downloadUrl("xmlPolyline.asp", function(data) {
    var xml = xmlParse(data);
    var markersPath = xml.documentElement.getElementsByTagName("marker");   
    var path = [];


    for (var i = 0; i < markersPath.length; i++) {
    var lat = parseFloat(markersPath[i].getAttribute("lat"));
    var lng = parseFloat(markersPath[i].getAttribute("lng"));
    pointPath = new google.maps.LatLng(lat,lng);


    path.push(pointPath);

}//finish loop

 polyline = new google.maps.Polyline({
  path: path,
  strokeColor: "#FF0000",
  strokeOpacity: 1.0,
  strokeWeight: 2
});


//new polyline

polyline.setMap(map);

}); //end download url

}

2 个答案:

答案 0 :(得分:9)

很简单 - 使用几何库中的内置函数...

polyLengthInMeters = google.maps.geometry.spherical.computeLength(yourPolyline.getPath().getArray());

要使用几何库,请在加载地图api

时声明它
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key={YOUR_KEY}&amp;sensor=false&amp;libraries=geometry"></script>

了解更多信息,请参阅:

Google API Polyline reference

Google API mcvArray reference

Google API Spherical geometry reference

答案 1 :(得分:4)

"geometry" library has a computeDistanceBetween method

这样的事情(未经测试)应该以米为单位返回结果:

var polylineLength = 0;
for (var i = 0; i < markersPath.length; i++) {
  var lat = parseFloat(markersPath[i].getAttribute("lat"));
  var lng = parseFloat(markersPath[i].getAttribute("lng"));
  var pointPath = new google.maps.LatLng(lat,lng);
  path.push(pointPath);
  if (i > 0) polylineLength += google.maps.geometry.spherical.computeDistanceBetween(path[i], path[i-1]);

}
alert("the length of the polyline is "+polylineLength+" meters");