How can I split a LINESTRING into two LINESTRINGs at a given point?
- by sabbour
Hello,
I'm trying to write a function that will split a LINESTRING into two LINESTRINGs given the split point. What I'm trying to achieve is a function that given a LINESTRING and a distance, it will return N LINESTRINGS for the original linestring splitted at multiples of that distance.
This is what I have so far (I'm using SQL Server Spatial Tools from CodePlex):
DECLARE @testLine geography;
DECLARE @slicePoint geography;
SET @testLine = geography::STGeomFromText('LINESTRING (34.5157942 28.5039665, 34.5157079 28.504725, 34.5156881 28.5049565, 34.5156773 28.505082, 34.5155642 28.5054437, 34.5155498 28.5054899, 34.5154937 28.5058826, 34.5154643 28.5060218, 34.5153968 28.5063415, 34.5153322 28.5065338, 34.5152031 28.5069178, 34.5150603 28.5072288, 34.5148716 28.5075501, 34.5146106 28.5079974, 34.5143617 28.5083813, 34.5141373 28.5086414, 34.5139954 28.5088441, 34.5138874 28.5089983, 34.5138311 28.5091054, 34.5136783 28.5093961, 34.5134336 28.5097531, 34.51325 28.5100794, 34.5130256 28.5105078, 34.5128754 28.5107957, 34.5126258 28.5113222, 34.5123984 28.5117673)', 4326)
DECLARE @pointOne geography;
declare @result table (segment geography)
DECLARE @sliceDistance float
DECLARE @nextSliceAt float
SET @sliceDistance = 100 -- slice every 100 meters
SET @nextSliceAt = @sliceDistance
SELECT @pointOne = @testLine.STStartPoint()
WHILE(@nextSliceAt < @testLine.STLength())
BEGIN
SELECT @slicePoint = dbo.LocateAlongGeog(@testLine,@nextSliceAt)
DECLARE @subLineString geography;
SET @subLineString = geography::STGeomFromText('LINESTRING (' + dbo.FloatToVarchar(@pointOne.Long) + ' ' + dbo.FloatToVarchar(@pointOne.Lat) + ',' + dbo.FloatToVarchar(@slicePoint.Long) + ' ' + dbo.FloatToVarchar(@slicePoint.Lat) +')', 4326)
insert into @result SELECT @subLineString
SET @pointOne = @slicePoint
set @nextSliceAt = @nextSliceAt + @sliceDistance
END
SET @subLineString = geography::STGeomFromText('LINESTRING (' + dbo.FloatToVarchar(@pointOne.Long) + ' ' + dbo.FloatToVarchar(@pointOne.Lat) + ',' + dbo.FloatToVarchar(@testLine.STEndPoint().Long) + ' ' + dbo.FloatToVarchar(@testLine.STEndPoint().Lat) +')', 4326)
insert into @result SELECT @subLineString
select * from @result
I know it is not the best looking code, but there is another problem. The above code approximates the resulting LINESTRING because it does not follow the curvature of the original LINESTRING as it only takes into consideration the start and end points when creating the new segment.
Is there a way take a substring out of the original LINESTRING given the start and end points?