我在折线工作,我需要获得这个距离。所以,如果有人能提供帮助,我将非常感激。
最好的问候。
这是我的代码:
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
}
答案 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}&sensor=false&libraries=geometry"></script>
了解更多信息,请参阅:
答案 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");