Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I have been messing around with the SqlGeometry in the Microsoft.SqlServer.Types namespace in .NET, and have been rather impressed.

Can anyone provide me with an example of how I could clip a geometry by another geometry? I know there are other libraries (ex. NetTopologySuite) that do this type of stuff in .NET, but I am trying to do this without any additional dependencies.

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

The first thing that comes to mind is SqlGeometry.STDifference. See the documentation for use. I don't know what happens when you attempt to construct the difference of two lines. I'll run a couple of tests and report back.

Edit: Actual results.

As an aside, I really like being able to play in SQL Server Management Studio and get immediate gratification.

Given:
declare @line1 geometry declare @line2 geometry declare @poly1 geometry

set @line1 = Geometry::STGeomFromText( 'LINESTRING(0 0, 10 10)', 0 ); set @line2 = Geometry::STGeomFromText( 'LINESTRING(0 10, 10 0)', 0 ); select @poly1 = @line2.STBuffer(.5);

select @line1.STDifference(@line2) union all select @line1.STIntersection(@line2).STBuffer(.1)

select @line1.STDifference(@poly1) select (@line1.STDifference(@poly1)).STAsText();

Which gives us:
result number 1
and
result number 2

Neither are exactly helpful, but result 2 is what you'd expect at least.

The resulting linestring is MULTILINESTRING ((10 10, 5.353553295135498 5.353553295135498), (4.646446704864502 4.646446704864502, 0 0))

Short version: you get to do trim (if you're talking lines) yourself. You do get a lot of help from Sql Server in the form of StIntersection, which will give you a (multi)point geometry of all the locations the lines intersect, but you're then responsible for building the new geometry. For instance:

declare @line1 geometry declare @line2 geometry

set @line1 = Geometry::STGeomFromText( 'LINESTRING(2 0, 2 10, 4 10, 4 0)', 0 ); set @line2 = Geometry::STGeomFromText( 'LINESTRING(0 10, 10 0)', 0 );

select @line1.STIntersection(@line2).STAsText();

yields MULTIPOINT ((2 8), (4 6))

Extra added bonus:
select @line1.STUnion(@line1.STIntersection(@line2)).STAsText();
returns LINESTRING (4 0, 4 6, 4 10, 2 10, 2 8, 2 0), which is line1 plus the intersection points with line2 embedded in it in the correct location. This would make walking the line determining which side it's on & keeping the point or tossing it much easier.

share|improve this answer
    
Exactly what I was looking for, thanks. –  user890 Oct 12 '10 at 12:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.