Calculating polyline length

8,811 views
Skip to first unread message

formazzasport

unread,
Oct 29, 2009, 2:55:01 PM10/29/09
to Google Maps JavaScript API v3
Is there some methods to calculate polyline length?

thanks
Message has been deleted

Esa

unread,
Nov 2, 2009, 10:27:33 PM11/2/09
to Google Maps JavaScript API v3
That must be done segment by segment. First you need Haversine
distance method equal to distanceFrom() of v2.

There is an unexposed method LatLng.Hj() that looks exactly like that.
However it returned invalid results. Finally I found out that there
were radian conversions missing. I imitated that method but added
those conversions.

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;
}

Then another method loops through the polyline and increments the
final length using the previous method.

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;
}


If the name of your polyline is poly, you can write:

alert(poly.inKm());

The result is the length of the polyline in kilometers. The optional
parameter is the path index of multi path polylines. I will put an
example online one of these days.

viper

unread,
Nov 16, 2009, 6:39:06 PM11/16/09
to Google Maps JavaScript API v3
Hi esa,

i tried the code you posted but i get an error at "var a = this.getPath
(n)". The error description is "Object doesent support this property
or method".

I'm using IE7

my polyline name is "polyline" and i use this to get the length "alert
(polyline.inKm())"

any idea what might be wrong?




Esa

unread,
Nov 18, 2009, 3:50:55 PM11/18/09
to Google Maps JavaScript API v3

On Nov 17, 1:39 am, viper <vi...@columbianet.gr> wrote:

> any idea what might be wrong?

I made some testing with IE7 and cannot reproduce the error. Script
works with no errors. Even the parameter seem to have no effect with a
single path polyline.

A link to your page would be most informative.
Reply all
Reply to author
Forward
0 new messages