distance of a polyline

2020-03-07 08:30发布

I am working in a polyline and I need to obtain the distance of this. So if anyone can help I would be very gratefully.

Best regards.

This is my code:

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条回答
冷血范
2楼-- · 2020-03-07 08:49

The "geometry" library has a computeDistanceBetween method.

Something like this (not tested) should return the result in meters:

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");
查看更多
倾城 Initia
3楼-- · 2020-03-07 08:53

It's easy - using built in functions in the geometry library...

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

To use the geometry library you declare it when you load the map api

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

for more info see:

Google API Polyline reference

Google API mcvArray reference

Google API Spherical geometry reference

查看更多
登录 后发表回答