Skip to content

Instantly share code, notes, and snippets.

@Kenny806
Last active October 7, 2021 11:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kenny806/37c767f46bcb2687e0ae to your computer and use it in GitHub Desktop.
Save Kenny806/37c767f46bcb2687e0ae to your computer and use it in GitHub Desktop.
A script that splits an ol3 LineString geometry into n segments of the same length, creates a point geometry at each split point and returns an array of the point geometries.
/**
* Accepts an ol.geom.LineString instance and a number (the desired number of segments) as parameters
*/
var splitLineString = function(geometry, n) {
var splitPoints = new Array(n);
var coords = geometry.getCoordinates();
var coordIndex = 0;
var startPoint = coords[coordIndex];
var nextPoint = coords[coordIndex + 1];
var segmentLength = geometry.getLength() / n;
var currentSegmentLength = 0;
for (var i = 0; i <= n; i++) {
var distanceBetweenPoints = calculatePointsDistance(startPoint, nextPoint);
currentSegmentLength += distanceBetweenPoints;
if (currentSegmentLength < segmentLength) {
coordIndex++;
startPoint = coords[coordIndex];
nextPoint = coords[coordIndex + 1];
continue;
} else {
var distanceToSplitPoint = currentSegmentLength - segmentLength;
var splitPointCoords = calculateSplitPointCoords(startPoint, nextPoint, distanceBetweenPoints, distanceToSplitPoint);
var splitPoint = new ol.geom.Point(splitPointCoords);
splitPoints.push(splitPoint);
startPoint = splitPoint.getCoordinates();
currentSegmentLength = 0;
}
}
return splitPoints;
};
var calculateSplitPointCoords = function(startNode, nextNode, distanceBetweenNodes, distanceToSplitPoint) {
var d = distanceToSplitPoint / distanceBetweenNodes;
var x = nextNode[0] + (startNode[0] - nextNode[0]) * d;
var y = nextNode[1] + (startNode[1] - nextNode[1]) * d;
return [x, y];
};
var calculatePointsDistance = function(coord1, coord2) {
var dx = coord1[0] - coord2[0];
var dy = coord1[1] - coord2[1];
return Math.sqrt(dx * dx + dy * dy);
};
@shenchaoran
Copy link

shenchaoran commented Apr 26, 2018

In the if section, it's better to change to this

if (currentSegmentLength < segmentLength) {
    coordIndex++;
    if(coordIndex< coords.length - 1) {
        startPoint = coords[coordIndex];
        nextPoint = coords[coordIndex + 1];
        i--;
        continue;
    }
    else {
        break;
    }
}

@ShahriatHossain
Copy link

@shenchaoran, @Kenny806: When I am drawing marker icon like pin the line's start and end point doesn't contain any pin. For example my desired number of segment in 2 and if I draw the line the marker pin just drawn middle of the line and last of the line instead I want to have those pins in the first point of the line and last point of the line. Is it possible?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment