Ton Snoei
Ton Snoei

Reputation: 3205

How to create one or more polygons from OpenStreetMap boundary relation in C#?

I am using OSMSharp (C# OpenStreetMap library) to get the boundary of a region (e.g. a city, state) from an osm.pbf file. The structure I get is a Relation containing Ways which consists of Nodes. The Ways contains a set of WGS84 points (lat., long.) represented by the Nodes that are part of the Ways. Combining the Ways (Ways are like lines with multiple points) can result in one or more polygons representing the area of region. I need help to get there.

The order of the ways is not sequential and it is unclear which way is part of which region polygon (if there are multiple). I thought the C# NetTopologySuite has a method to combine these ways to one or more polygons in order to use OsmSharp.FilterSpatial method. But I cannot find it. Does any body know a C# library that can perform this action?

Upvotes: 3

Views: 746

Answers (1)

Ton Snoei
Ton Snoei

Reputation: 3205

Found the solution. The NetTopologySuite Polygonizer is a good fit to fix this problem.

List<IGeometry> lines = new List<IGeometry>();
lines.Add(new LineString(new Coordinate[] { new Coordinate(0, 0), new Coordinate(1, 0) }));
lines.Add(new LineString(new Coordinate[] { new Coordinate(1, 0), new Coordinate(1, 1) }));
lines.Add(new LineString(new Coordinate[] { new Coordinate(1, 1), new Coordinate(0, 1) }));
lines.Add(new LineString(new Coordinate[] { new Coordinate(0, 1), new Coordinate(0, 0) }));

Polygonizer polygonizer = new Polygonizer();
polygonizer.Add(lines);

IList<IGeometry> polys = polygonizer.GetPolygons();

Upvotes: 5

Related Questions