Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get length of polyline in google maps v3

Tags:

maps

polyline

Does anyone know how you can get the length of a polyline in google maps v3? At the moment I am using Haversine fomula but if the polyline meets the start then it calculates the shortest length. Does anyone know how I can calculate the polyline lenght?

Thanks a lot. Mark

like image 737
mark harding Avatar asked Dec 18 '10 21:12

mark harding


2 Answers

Extend Google Maps API with these functions:

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

and then you can call:

var length_in_km = yourPoly.inKm();

source: http://groups.google.com/forum/#!topic/google-maps-js-api-v3/Op87g7lBotc

like image 156
Ladik Avatar answered Dec 05 '22 13:12

Ladik


Use Google Geometry:

<script type="text/javascript" src="//maps.google.com/maps/api/js?v=3.exp&libraries=geometry"></script>

Then its as easy as this:

var meters = google.maps.geometry.spherical.computeLength(myPolyline.getPath());
like image 22
kosemuckel Avatar answered Dec 05 '22 13:12

kosemuckel