how to calculate polyline distance?

2020-02-13 04:48发布

function createLine()
{

geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(7.5653, 80.4303);
var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("directionpanel"), mapOptions);

var address = document.getElementById('startvalue').value;
var address2 = document.getElementById('endvalue').value;

var temp, temp2;

geocoder.geocode({ 'address': address }, function (results, status) {
    temp = results[0].geometry.location;
    geocoder.geocode({ 'address': address2 }, function (results, status) {
        temp2 = results[0].geometry.location;

    var route = [
      temp,
      temp2
    ];

    var polyline = new google.maps.Polyline({
        path: route,
        strokeColor: "#ff0000",
        strokeOpacity: 0.6,
        strokeWeight: 5
    });

    polyline.setMap(map);
    });
});
}

This code work fine. I want to calculate the distance of the line which I created. I want to display this value in meters via an alert. Please help me... (In this case two points connect directly with the line. I want to calculate that direct line distance. )

1条回答
▲ chillily
2楼-- · 2020-02-13 05:27

Use google.maps.geometry.spherical.computeLength (be sure to include the geometry library)

function createLine()
{

geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(7.5653, 80.4303);
var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("directionpanel"), mapOptions);

var address = document.getElementById('startvalue').value;
var address2 = document.getElementById('endvalue').value;

var temp, temp2;

geocoder.geocode({ 'address': address }, function (results, status) {
    temp = results[0].geometry.location;
    geocoder.geocode({ 'address': address2 }, function (results, status) {
        temp2 = results[0].geometry.location;

    var route = [
      temp,
      temp2
    ];

    var polyline = new google.maps.Polyline({
        path: route,
        strokeColor: "#ff0000",
        strokeOpacity: 0.6,
        strokeWeight: 5
    });

    var lengthInMeters = google.maps.geometry.spherical.computeLength(polyline.getPath());
    alert("polyline is "+lengthInMeters+" long");

    polyline.setMap(map);
    });
});
}

Working example (updated the example from your last question to include the length calculation)

查看更多
登录 后发表回答