private NetTopologySuite.Geometries.Geometry KmlGeometryToGeometry(SharpKml.Dom.Geometry geometry)
 {
     NetTopologySuite.Geometries.Geometry result = null;
     if (geometry is SharpKml.Dom.Point)
     {
         var kmlPoint = geometry as SharpKml.Dom.Point;
         result = new NetTopologySuite.Geometries.Point(new Coordinate(kmlPoint.Coordinate.Longitude, kmlPoint.Coordinate.Latitude));
     }
     else if (geometry is SharpKml.Dom.Polygon)
     {
         var kmlPolygon = geometry as SharpKml.Dom.Polygon;
         if (kmlPolygon.OuterBoundary == null || kmlPolygon.OuterBoundary.LinearRing == null || kmlPolygon.OuterBoundary.LinearRing.Coordinates == null)
         {
             throw new Exception("Polygon is null");
         }
         var coordinates = new Coordinate[kmlPolygon.OuterBoundary.LinearRing.Coordinates.Count];
         int i           = 0;
         foreach (var coordinate in kmlPolygon.OuterBoundary.LinearRing.Coordinates)
         {
             coordinates[i++] = new Coordinate(coordinate.Longitude, coordinate.Latitude);
         }
         result = new NetTopologySuite.Geometries.Polygon(new NetTopologySuite.Geometries.LinearRing(coordinates));
     }
     else if (geometry is SharpKml.Dom.MultipleGeometry)
     {
         var mgeometry = geometry as SharpKml.Dom.MultipleGeometry;
         var polygons  = new List <NetTopologySuite.Geometries.Polygon>();
         foreach (var poly in mgeometry.Geometry)
         {
             var kmlPolygon = poly as SharpKml.Dom.Polygon;
             if (kmlPolygon.OuterBoundary == null || kmlPolygon.OuterBoundary.LinearRing == null || kmlPolygon.OuterBoundary.LinearRing.Coordinates == null)
             {
                 throw new Exception("Polygon is null");
             }
             var coordinates = new Coordinate[kmlPolygon.OuterBoundary.LinearRing.Coordinates.Count];
             int i           = 0;
             foreach (var coordinate in kmlPolygon.OuterBoundary.LinearRing.Coordinates)
             {
                 coordinates[i++] = new Coordinate(coordinate.Longitude, coordinate.Latitude);
             }
             polygons.Add(new NetTopologySuite.Geometries.Polygon(new NetTopologySuite.Geometries.LinearRing(coordinates)));
         }
         result = new NetTopologySuite.Geometries.MultiPolygon(polygons.ToArray());
     }
     return(result);
 }
        /// <summary>
        /// Creates a <see cref="MultiPolygon"/> using the next token in the stream.
        /// </summary>
        /// <param name="tokenizer">tokenizer over a stream of text in Well-known Text
        /// format. The next tokens must form a MultiPolygon.</param>
        /// <returns>a <code>MultiPolygon</code> specified by the next token in the 
        /// stream, or if if the coordinates used to create the <see cref="Polygon"/>
        /// shells and holes do not form closed linestrings.</returns>
        private static MultiPolygon ReadMultiPolygonText(WktStreamTokenizer tokenizer)
        {
            var arrpolys = new List<IPolygon>();
            
            string nextToken = GetNextEmptyOrOpener(tokenizer);
            if (nextToken == "EMPTY")
                return new MultiPolygon(arrpolys.ToArray());

            Polygon polygon = ReadPolygonText(tokenizer);
            arrpolys.Add(polygon);
            nextToken = GetNextCloserOrComma(tokenizer);
            while (nextToken == ",")
            {
                polygon = ReadPolygonText(tokenizer);
                arrpolys.Add(polygon);
                nextToken = GetNextCloserOrComma(tokenizer);
            }

            MultiPolygon polygons = new MultiPolygon(arrpolys.ToArray());
            return polygons;
        }
        private static MultiPolygon CreateWKBMultiPolygon(BinaryReader reader, WkbByteOrder byteOrder)
        {
            // Get the number of Polygons.
            int numPolygons = (int) ReadUInt32(reader, byteOrder);
            var arrpolygons = new IPolygon[numPolygons];

            // Loop on the number of polygons.
            for (int i = 0; i < numPolygons; i++)
            {
                // read polygon header
                reader.ReadByte();
                ReadUInt32(reader, byteOrder);

                // TODO: Validate type

                // Create the next polygon and add it to the array.
                arrpolygons[i] = CreateWKBPolygon(reader, byteOrder);
            }

            // Create a new array for the Polygons.
            MultiPolygon polygons = new MultiPolygon(arrpolygons);

            //Create and return the MultiPolygon.
            return polygons;
        }
        public static GoalTriggers LoadTestData(
            this GoalTriggers goalTriggers,
            Guid realmRefId,
            Goal goal,
            Actions actions,
            NetTopologySuite.Geometries.MultiPolygon insideOf,
            NetTopologySuite.Geometries.MultiPolygon outsideOf,
            List <string> tags)
        {
            var rnd = new Random();

            for (int i = 0; i < rnd.Next(1, 10); i++)
            {
                var simpleName = $"Goal Trigger [{i}]";

                var goalTrigger = new GoalTrigger()
                {
                    RealmRefId = realmRefId,
                    GoalRefId  = goal.EntityRefId,
                    SimpleName = simpleName,
                    Priority   = i,
                    ReleaseOn  = DateTimeOffset.UtcNow.AddDays(-365),
                    ExpireOn   = DateTimeOffset.MaxValue,
                    Tags       = tags,
                    RollingPeriodActionFilter = TimeSpan.FromDays(-30),
                };

                goalTrigger.NameTranslations.Add(
                    new StringTranslation()
                {
                    Locale = "en-Us", LocalName = simpleName
                }
                    );

                goalTrigger.Steps.Add(
                    new TriggerStep()
                {
                    ExecutionOrder   = i,
                    PeriodRecurrence = new PeriodRecurrence()
                    {
                        PeriodMinuteBeginOn = Convert.ToInt32(TimeSpan.FromMinutes(0).TotalMinutes),
                        PeriodTimeSpan      = TimeSpan.FromSeconds((24 * 60 * 60) - 1),
                        PeriodPattern       =
                            new RecurrencePattern(FrequencyType.Daily, interval: 1)
                        {
                            Until = DateTime.MaxValue
                        }.ToString()
                    },
                    ActionOccurrenceRules = new ActionOccurrenceRules()
                    {
                        new ActionOccurrenceRule()
                        {
                            ActionRefId      = actions[0].EntityRefId,
                            OperationType    = Core.Enums.OperationRuleType.And,
                            TenseType        = Core.Enums.TenseRuleType.Did,
                            CompareType      = Core.Enums.CompareRuleType.GreaterOrEqual,
                            Count            = 1,
                            PeriodRecurrence = new PeriodRecurrence()
                            {
                                PeriodMinuteBeginOn = Convert.ToInt32(TimeSpan.FromMinutes(0).TotalMinutes),
                                PeriodTimeSpan      = TimeSpan.FromSeconds((24 * 60 * 60) - 1),
                                PeriodPattern       =
                                    new RecurrencePattern(FrequencyType.Daily, interval: 1)
                                {
                                    Until = DateTime.MaxValue
                                }.ToString()
                            },
                            InsideOf  = insideOf,
                            OutsideOf = outsideOf
                        }
                    }
                }
                    );;

                goalTriggers.Add(goalTrigger);
            }

            return(goalTriggers);
        }
 private Feature ConvertToMultipolygon(CompleteRelation relation)
 {
     var outerWays = GetAllWaysByRole(relation).Where(kvp => kvp.Key == OUTER).SelectMany(kvp => kvp.Value).ToList();
     var outerPolygons = GetGeometriesFromWays(outerWays).OfType<IPolygon>().ToList();
     var innerWays = GetAllWaysByRole(relation).Where(kvp => kvp.Key != OUTER).SelectMany(kvp => kvp.Value).ToList();
     var innerPolygons = GetGeometriesFromWays(innerWays).OfType<IPolygon>().ToList();
     MergeInnerIntoOuterPolygon(ref outerPolygons, ref innerPolygons);
     var multiPolygon = new MultiPolygon(outerPolygons.Union(innerPolygons).ToArray());
     return new Feature(multiPolygon, ConvertTags(relation.Tags, relation.Id));
 }
Exemple #6
0
        public static System.Collections.Generic.List <OSM.API.v0_6.GeoPoint> GetUnionPolygon(
            System.Collections.Generic.IEnumerable <System.Collections.Generic.IEnumerable <OSM.API.v0_6.GeoPoint> > polygons)
        {
            NetTopologySuite.Geometries.GeometryFactory geomFactory = new NetTopologySuite.Geometries.GeometryFactory();


            System.Collections.Generic.List <NetTopologySuite.Geometries.Geometry> lsPolygons =
                new System.Collections.Generic.List <NetTopologySuite.Geometries.Geometry>();

            foreach (System.Collections.Generic.IEnumerable <OSM.API.v0_6.GeoPoint> coords in polygons)
            {
                NetTopologySuite.Geometries.Polygon poly = geomFactory.CreatePolygon(ToNetTopologyCoordinates(coords));
                lsPolygons.Add(poly);
            }


            NetTopologySuite.Geometries.Geometry ig = NetTopologySuite.Operation.Union.CascadedPolygonUnion.Union(lsPolygons);
            System.Console.WriteLine(ig.GetType().FullName);



            if (ig is NetTopologySuite.Geometries.Polygon)
            {
                System.Console.WriteLine("mulip");
                goto SIMPLIFY_POLYGON_AND_GET_UNION;
            }


            if (!(ig is NetTopologySuite.Geometries.MultiPolygon))
            {
                System.Console.WriteLine("Error: Geometry is not a multipolygon!");
                throw new System.InvalidOperationException("Geometry is not a multipolygon");
            }


            NetTopologySuite.Geometries.MultiPolygon lalala = (NetTopologySuite.Geometries.MultiPolygon)ig;

            // var convaveHull = ConcaveHull.Init.foo(lalala.Coordinates);
            // convaveHull = ToCounterClockWise(convaveHull);
            // return convaveHull;



            // var cc = new NetTopologySuite.Hull.ConcaveHull(ig, 0);
            // var cc = new NetTopologySuite.Hull.ConcaveHull(ig, 0.00049);
            var cc = new NetTopologySuite.Hull.ConcaveHull(ig, 0.00001);

            ig = cc.GetConcaveHull;

SIMPLIFY_POLYGON_AND_GET_UNION:

            ig = NetTopologySuite.Simplify.DouglasPeuckerSimplifier.Simplify(ig, 0.00001);
            NetTopologySuite.Geometries.Polygon unionPolygon = (NetTopologySuite.Geometries.Polygon)ig;



            System.Console.WriteLine(unionPolygon.Shell.Coordinates);



            System.Collections.Generic.List <OSM.API.v0_6.GeoPoint> lsUnionPolygonPoints = new System.Collections.Generic.List <OSM.API.v0_6.GeoPoint>();

            for (int i = 0; i < unionPolygon.Shell.Coordinates.Length; ++i)
            {
                lsUnionPolygonPoints.Add(new OSM.API.v0_6.GeoPoint(unionPolygon.Shell.Coordinates[i].X, unionPolygon.Shell.Coordinates[i].Y));
            }

            lsUnionPolygonPoints = ToCounterClockWise(lsUnionPolygonPoints);

            return(lsUnionPolygonPoints);
        }
        /// <summary>
        /// This method produces instances of type <see cref="MultiPolygon"/>.
        /// </summary>
        /// <returns>The created geometries</returns>
        internal override Collection<SimpleGisShape> createGeometries()
        {
            SimpleGisShape shp = null;

            IPathNode multiPolygonNode = new PathNode(_GMLNS, "MultiPolygon", (NameTable)_xmlReader.NameTable);
            IPathNode multiSurfaceNode = new PathNode(_GMLNS, "MultiSurface", (NameTable)_xmlReader.NameTable);
            IPathNode multiPolygonNodeAlt = new AlternativePathNodesCollection(multiPolygonNode, multiSurfaceNode);
            IPathNode polygonMemberNode = new PathNode(_GMLNS, "polygonMember", (NameTable)_xmlReader.NameTable);
            IPathNode surfaceMemberNode = new PathNode(_GMLNS, "surfaceMember", (NameTable)_xmlReader.NameTable);
            IPathNode polygonMemberNodeAlt = new AlternativePathNodesCollection(polygonMemberNode, surfaceMemberNode);
            IPathNode linearRingNode = new PathNode(_GMLNS, "LinearRing", (NameTable)_xmlReader.NameTable);
            string[] labelValue = new string[1];

            try
            {
                ParseBoundingBox();

                // Reading the entire feature's node makes it possible to collect label values that may appear before or after the geometry property
                while ((_featureReader = GetSubReaderOf(_xmlReader, null, _featureNode)) != null)
                {
                    while ((_geomReader = GetSubReaderOf(_featureReader, null, _propertyNode)) != null)
                    {
                        bool isSelected;
                        int uid;
                        List<string> ll = ParseProperties(_geomReader, out isSelected, out uid);

                        _geomReader = GetSubReaderOf(_featureReader, labelValue, multiPolygonNodeAlt, polygonMemberNodeAlt);

                        GeometryFactory geomFactory = new PolygonFactory(_geomReader, _featureTypeInfo, _fieldNames);
                        Collection<SimpleGisShape> shpPolygons = geomFactory.createGeometries();

                        var polygons = new List<IPolygon>();

                        foreach (var shp1 in shpPolygons)
                        {
                            polygons.Add(shp1.Geometry as IPolygon);                            
                        }

                        MultiPolygon multiPolygon = new MultiPolygon(polygons.ToArray());
                        shp = new SimpleGisShape(multiPolygon);
                        shp.IsSelected = isSelected;
                        shp.UID = uid;

                        _shapes.Add(shp);
                        FillShapeFields(shp, ll);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return _shapes;
        }
        /// <summary>
        /// Writes a multipolygon.
        /// </summary>
        /// <param name="mp">The mulitpolygon to be written.</param>
        /// <param name="bWriter">Stream to write to.</param>
        /// <param name="byteorder">Byte order</param>
        private static void WriteMultiPolygon(MultiPolygon mp, BinaryWriter bWriter, WkbByteOrder byteorder)
        {
            //Write the number of polygons.
            WriteUInt32((uint) mp.Geometries.Length, bWriter, byteorder);

            //Loop on the number of polygons.
            foreach (var g in mp.Geometries)
            {
                var poly = g as Polygon;
                if (poly == null)
                    throw new ArgumentNullException("Polygon inside a multipolygon");

                //Write polygon header
                bWriter.Write((byte) byteorder);
                WriteUInt32((uint) WKBGeometryType.wkbPolygon, bWriter, byteorder);
                //Write each polygon.
                WritePolygon(poly, bWriter, byteorder);
            }
        }
  private DataTable GetShapeTable(string sql, OgcGeometryType geometryType)
  {
    DataTable table = null;

    using (OleDbConnection connection = AppContext.GetDatabaseConnection())
    {
      table = new DataTable();

      using (OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connection))
      {
        adapter.Fill(table);
      }

      table.Columns["Shape"].ColumnName = "ShapeString";

      switch (geometryType)
      {
        case OgcGeometryType.Point: table.Columns.Add("Shape", typeof(IPoint)); break;
        case OgcGeometryType.LineString: table.Columns.Add("Shape", typeof(IMultiLineString)); break;
        case OgcGeometryType.Polygon: table.Columns.Add("Shape", typeof(IMultiPolygon)); break;
      }

      WKTReader wktReader = new WKTReader();

      foreach (DataRow row in table.Rows)
      {
        switch (geometryType)
        {
          case OgcGeometryType.Point:
            row["Shape"] = (IPoint)wktReader.Read((string)row["ShapeString"]);
            break;

          case OgcGeometryType.LineString:
            ILineString lineString = (ILineString)wktReader.Read((string)row["ShapeString"]);
            IMultiLineString multiLineString = new MultiLineString(new ILineString[] { lineString });
            row["Shape"] = multiLineString;
            break;

          case OgcGeometryType.Polygon:
            IPolygon polygon = (IPolygon)wktReader.Read((string)row["ShapeString"]);
            IMultiPolygon multiPolygon = new MultiPolygon(new IPolygon[] { polygon });
            row["Shape"] = multiPolygon;
            break;
        }
      }

      table.Columns.Remove("ShapeString");
    }

    return table;
  }
 /// <summary>
 /// Converts a MultiPolygon to &lt;MultiPolygon Text&gt; format, then Appends to it to the writer.
 /// </summary>
 /// <param name="multiPolygon">The MultiPolygon to process.</param>
 /// <param name="writer">The output stream to Append to.</param>
 private static void AppendMultiPolygonText(MultiPolygon multiPolygon, StringWriter writer)
 {
     if (multiPolygon == null || multiPolygon.IsEmpty)
         writer.Write("EMPTY");
     else
     {
         writer.Write("(");
         for (int i = 0; i < multiPolygon.Geometries.Length; i++)
         {
             if (i > 0)
                 writer.Write(", ");
             AppendPolygonText(multiPolygon.Geometries[i] as Polygon, writer);
         }
         writer.Write(")");
     }
 }
 /// <summary>
 /// Converts a MultiPolygon to &lt;MultiPolygon Tagged
 /// Text&gt; format, then Appends it to the writer.
 /// </summary>
 /// <param name="multiPolygon">The MultiPolygon to process</param>
 /// <param name="writer">The output stream writer to Append to.</param>
 private static void AppendMultiPolygonTaggedText(MultiPolygon multiPolygon, StringWriter writer)
 {
     writer.Write("MULTIPOLYGON ");
     AppendMultiPolygonText(multiPolygon, writer);
 }