Skip to content

Commit

Permalink
Merge pull request #76 from jb2b38/fix_66
Browse files Browse the repository at this point in the history
Interpolation could return an incorrect index. Fix: #66
  • Loading branch information
mdartic authored Jun 26, 2018
2 parents 0e06d47 + 5d6611d commit 7046005
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 19 deletions.
5 changes: 5 additions & 0 deletions spec/test.interpolateOnLine.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,9 @@ describe('Interpolate on line', function() {
assert.isDefined(interp2.latLng.lat);
assert.isDefined(interp2.latLng.lng);
});

it('It should not return a negative predecessor index when interpolating a point on the first segment', function() {
var interp = L.GeometryUtil.interpolateOnLine(map, [llA, llB], 0.5);
assert.isTrue(interp.predecessor >= 0);
});
});
40 changes: 21 additions & 19 deletions src/leaflet.geometryutil.js
Original file line number Diff line number Diff line change
Expand Up @@ -491,26 +491,28 @@ L.GeometryUtil = L.extend(L.GeometryUtil || {}, {
}

var ratioDist = lineLength * ratio;
var a = pts[0],
b = pts[1],
distA = 0,
distB = a.distanceTo(b);
// follow the line segments [ab], adding lengths,

// follow the line segments [ab], adding lengths,
// until we find the segment where the points should lie on
var index = 1;
for (; index < n && distB < ratioDist; index++) {
a = b;
distA = distB;
b = pts[index];
distB += a.distanceTo(b);
}
// compute the ratio relative to the segment [ab]
var segmentRatio = ((distB - distA) !== 0) ? ((ratioDist - distA) / (distB - distA)) : 0;
var interpolatedPoint = L.GeometryUtil.interpolateOnPointSegment(a, b, segmentRatio);
return {
latLng: map.unproject(interpolatedPoint, maxzoom),
predecessor: index-2
};
var cumulativeDistanceToA = 0, cumulativeDistanceToB = 0;
for (var i = 0; cumulativeDistanceToB < ratioDist; i++) {
var pointA = pts[i], pointB = pts[i+1];

cumulativeDistanceToA = cumulativeDistanceToB;
cumulativeDistanceToB += pointA.distanceTo(pointB);
}

if (pointA == undefined && pointB == undefined) { // Happens when line has no length
var pointA = pts[0], pointB = pts[1], i = 1;
}

// compute the ratio relative to the segment [ab]
var segmentRatio = ((cumulativeDistanceToB - cumulativeDistanceToA) !== 0) ? ((ratioDist - cumulativeDistanceToA) / (cumulativeDistanceToB - cumulativeDistanceToA)) : 0;
var interpolatedPoint = L.GeometryUtil.interpolateOnPointSegment(pointA, pointB, segmentRatio);
return {
latLng: map.unproject(interpolatedPoint, maxzoom),
predecessor: i-1
};
},

/**
Expand Down

0 comments on commit 7046005

Please sign in to comment.