Calculate midpoint of Polyline

Sometimes it might be important to calculate the midpoint along a polyline. this can be done by first calculating the total length of a polyline and then to iterate through the points of the polyline, calculating the distance between points until  we find the points where the midpoint falls between. From here we can calculate the coordinate of the midpoint. The following functions can calculate the midpoint coordinate of a polyline.

function PolylineCentroid(points){
var totalDistance = PolylineLength(points);
var midpoint = FindMidPoint(points,totalDistance);
return midpoint;
}

function PolylineLength(points){
var distance = 0;

for(var i=0;i<points.length-1;i++)
{
distance += haversineDistance(points[i],points[i+1]);
}

return distance;
}

function FindMidPoint(points,totalDistance){
var midDistance = totalDistance/2;
var distance = 0;
var subDistance=0;
var i;

for(i=0;i<points.length-1;i++)
{
subDistance = haversineDistance(points[i],points[i+1]);

if((subDistance+distance)<midDistance)
distance += subDistance;
else
break;
}

subDistance = midDistance – distance;
var bearing  = calculateBearing(points[i],points[i+1]);
return calculateCoord(points[i], bearing, subDistance);
}

Information on the haversineDistance method can be found here: http://rbrundritt.spaces.live.com/blog/cns!E7DBA9A4BFD458C5!317.entry

Information on the calculateBearing method can be found here: http://rbrundritt.spaces.live.com/blog/cns!E7DBA9A4BFD458C5!393.entry

Information on the calculateCoord method can be found here: http://rbrundritt.spaces.live.com/blog/cns!E7DBA9A4BFD458C5!400.entry

Advertisements