折线长度

时间:2013-06-05 11:46:55

标签: javascript google-maps-api-3

我通过这个函数获得行长。

            google.maps.LatLng.prototype.kmTo = function(a){ 
    var e = Math, ra = e.PI/180; 
    var b = this.lat() * ra, c = a.lat() * ra, d = b - c; 
    var g = this.lng() * ra - a.lng() * ra; 
    var f = 2 * e.asin(e.sqrt(e.pow(e.sin(d/2), 2) + e.cos(b) * e.cos 
    (c) * e.pow(e.sin(g/2), 2))); 
    return f * 6378.137; 
}

google.maps.Polyline.prototype.inKm = function(n){ 
    var a = this.getPath(n), len = a.getLength(), dist = 0; 
    for (var i=0; i < len-1; i++) { 
       dist += a.getAt(i).kmTo(a.getAt(i+1)); 
    }
    return dist; 
}

并使用:

   alert('Line Length:  '+ poly1.inKm() +'');

一切正常。但我有一个小问题。 它告诉我:&gt;&gt;线长:8.8 54502612255438 km&lt;&lt;

数字很长我想让它只显示8.8我该怎么做?

抱歉我的英文!

1 个答案:

答案 0 :(得分:1)

尝试类似:

Math.floor(x * 10) / 10

其中x是您要显示的数字(8.854502612255438)。

而不是地板(将变为88.5到88)你可能想尝试回合(将88.5变为89)。

编辑 - 啊不,这不会起作用,因为你的号码是一个字符串,最后是'km'(没有发现)......

所以...尝试使用parseFloat这样:

Math.floor(parseFloat(x, 10) * 10) / 10

你必须在你自己的字符串末尾添加'km',所以完整的东西变成了:

alert('Line Length:  '+ (Math.floor(parseFloat(poly1.inKm(), 10) * 10) / 10) +'km');